From 6c6cf198b0a536b5c9ef6eef41d23c1111d22f53 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Wed, 5 Aug 2026 02:53:28 -0500 Subject: [PATCH 01/47] security: remediate 2026-08-02 audit (33/33 findings), bind bundle entries via AAD MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit All findings from the 2026-08-02 security audit dispositioned: - HIGH (5): O1, A1-A4 fixed. - MEDIUM (11): O2-O4, A5-A11 fixed; strict:false investigated and closed (no fail-open beyond A3; --verify-keys is now fail-closed under any skip). - LOW+INFO (16): 12 fixed, 4 documented as accepted in the threat model (A14, A18, A24, A25). A7 (no AAD binding): bundle entries are now name-bound — resolve_bundle decrypts each ciphertext with AAD = the entry's map key, so relocating a ciphertext under a different entry fails authentication. Suite bumped to ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad (pre-AAD bundles fail loudly rather than silently). AAD support comes from the ecies fork branch aad-support (additive encrypt_with_aad/decrypt_with_aad; upstream PR ecies/rs#159), consumed via [patch.crates-io] git+rev pin 81e1b84; deny.toml gains a [sources] allow-git entry for the fork. nix cargoLock.outputHashes is pending a nix-equipped machine (fill-in steps documented in package.nix and nixpkgs-package.nix). Also: docs and threat model brought in line with the new behavior; daemon hardening (signal deferral across the plaintext-write window on macOS, logged hardening failures, fd-pinned writes, O_NOFOLLOW opens, sentinel-guarded bulk cleanup, keychain reads via security-framework). Verified: fmt, clippy (macOS dev + x86_64-linux-gnu + macOS release, -D warnings), full locked test suite, mdbook build. --- .github/CODE_OF_CONDUCT.md | 91 ++ .github/SECURITY.md | 4 +- .github/actions/setup-rust/action.yml | 95 ++ .github/workflows/ci.yml | 35 +- .github/workflows/docs.yml | 24 +- .github/workflows/nix.yml | 25 +- .github/workflows/security.yml | 33 +- CHANGELOG.md | 2 +- Cargo.lock | 43 +- Cargo.toml | 34 +- Justfile | 176 ++- README.md | 15 +- deny.toml | 6 + docs/mdbook-build-issue.md | 84 ++ docs/src/architecture/materialization-abi.md | 22 +- docs/src/architecture/threat-model.md | 54 +- docs/src/getting-started/key-provisioning.md | 2 +- docs/src/getting-started/quick-start.md | 15 +- docs/src/reference/cli.md | 8 +- docs/src/reference/launcher-contract.md | 26 +- nixpkgs-package.nix | 5 +- package.nix | 7 + src/adapter.rs | 66 +- src/bundle.rs | 70 +- src/config.rs | 417 +----- src/exec_config.rs | 408 ++++++ src/key_provisioning.rs | 657 +++++++++ src/key_source.rs | 249 ++++ src/keys.rs | 167 ++- src/launcher.rs | 1372 +++--------------- src/lib.rs | 12 +- src/ramdisk.rs | 207 +++ src/secret_files.rs | 318 ++++ src/server.rs | 162 ++- tests/exec_check.rs | 2 +- tests/exec_conformance.rs | 71 + 36 files changed, 3184 insertions(+), 1800 deletions(-) create mode 100644 .github/CODE_OF_CONDUCT.md create mode 100644 .github/actions/setup-rust/action.yml create mode 100644 docs/mdbook-build-issue.md create mode 100644 src/exec_config.rs create mode 100644 src/key_provisioning.rs create mode 100644 src/key_source.rs create mode 100644 src/ramdisk.rs create mode 100644 src/secret_files.rs diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..f7869bc --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,91 @@ + +# Contributor Covenant 3.0 Code of Conduct + +## Our Pledge + +We pledge to make our community welcoming, safe, and equitable for all. + +We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant. + +## Encouraged Behaviors + +While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language. + +With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including: + +1. Respecting the **purpose of our community**, our activities, and our ways of gathering. +2. Engaging **kindly and honestly** with others. +3. Respecting **different viewpoints** and experiences. +4. **Taking responsibility** for our actions and contributions. +5. Gracefully giving and accepting **constructive feedback**. +6. Committing to **repairing harm** when it occurs. +7. Behaving in other ways that promote and sustain the **well-being of our community**. + + +## Restricted Behaviors + +We agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct. + +1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop. +2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people. +3. **Stereotyping or discrimination.** Characterizing anyone’s personality or behavior on the basis of immutable identities or traits. +4. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community. +5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission. +6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group. +7. Behaving in other ways that **threaten the well-being** of our community. + +### Other Restrictions + +1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions. +2. **Failing to credit sources.** Not properly crediting the sources of content you contribute. +3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community. +4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviors. + + +## Reporting an Issue + +Tensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviors and norms that can help avoid conflicts and minimize harm. + +When an incident does occur, it is important to report it promptly. To report a possible violation, **send an email .** + +Community Moderators take reports of violations seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Community Moderators will keep investigation and enforcement actions as transparent as possible while prioritizing safety and confidentiality. In order to honor these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution. + + +## Addressing and Repairing Harm + +**** + +If an investigation by the Community Moderators finds that this Code of Conduct has been violated, the following enforcement ladder may be used to determine how best to repair harm, based on the incident's impact on the individuals involved and the community as a whole. Depending on the severity of a violation, lower rungs on the ladder may be skipped. + +1) Warning + 1) Event: A violation involving a single incident or series of incidents. + 2) Consequence: A private, written warning from the Community Moderators. + 3) Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations. +2) Temporarily Limited Activities + 1) Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation. + 2) Consequence: A private, written warning with a time-limited cooldown period designed to underscore the seriousness of the situation and give the community members involved time to process the incident. The cooldown period may be limited to particular communication channels or interactions with particular community members. + 3) Repair: Examples of repair may include making an apology, using the cooldown period to reflect on actions and impact, and being thoughtful about re-entering community spaces after the period is over. +3) Temporary Suspension + 1) Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation. + 2) Consequence: A private written warning with conditions for return from suspension. In general, temporary suspensions give the person being suspended time to reflect upon their behavior and possible corrective actions. + 3) Repair: Examples of repair include respecting the spirit of the suspension, meeting the specified conditions for return, and being thoughtful about how to reintegrate with the community when the suspension is lifted. +4) Permanent Ban + 1) Event: A pattern of repeated code of conduct violations that other steps on the ladder have failed to resolve, or a violation so serious that the Community Moderators determine there is no way to keep the community safe with this person as a member. + 2) Consequence: Access to all community spaces, tools, and communication channels is removed. In general, permanent bans should be rarely used, should have strong reasoning behind them, and should only be resorted to if working through other remedies has failed to change the behavior. + 3) Repair: There is no possible repair in cases of this severity. + +This enforcement ladder is intended as a guideline. It does not limit the ability of Community Managers to use their discretion and judgment, in keeping with the best interests of our community. + + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public or other spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/). + +Contributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this license, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/) + +For answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla’s code of conduct team](https://github.com/mozilla/inclusion). diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 129708e..eb64a45 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -24,10 +24,10 @@ Preferred channels (either is fine): 1. **GitHub private advisory (recommended).** Open a report at - https://github.com/beardedeagle/postmaster/security/advisories/new + [security advisories](https://github.com/beardedeagle/postmaster/security/advisories/new). This keeps the discussion private and allows coordinated disclosure. -2. **Email.** Write to randy@heroictek.com. +2. **Email.** Write to . Please include as much of the following as you can: diff --git a/.github/actions/setup-rust/action.yml b/.github/actions/setup-rust/action.yml new file mode 100644 index 0000000..a244074 --- /dev/null +++ b/.github/actions/setup-rust/action.yml @@ -0,0 +1,95 @@ +name: Setup Rust and just +description: Install the pinned Rust toolchain (from rust-toolchain.toml), just, and optional cargo tools. + +inputs: + targets: + description: Optional space-separated list of additional Rust targets to install. + required: false + default: "" + install-just: + description: Whether to install the pinned just command runner. + required: false + default: "true" + just-version: + description: just runner version to install (not the Rust compiler version). + required: false + default: "1.51.0" + install-cargo-deny: + description: Whether to install cargo-deny. + required: false + default: "false" + install-cargo-audit: + description: Whether to install cargo-audit. + required: false + default: "false" + install-target-dir: + description: Cargo target directory for tool installation builds. + required: false + default: target/cargo-install + +runs: + using: composite + steps: + - name: Install pinned Rust toolchain + shell: bash + env: + RUST_TARGETS: ${{ inputs.targets }} + run: | + set -euo pipefail + if ! command -v rustup >/dev/null 2>&1; then + echo "rustup must be preinstalled; refusing to run an unpinned remote installer" >&2 + exit 1 + fi + if [[ -n "${GITHUB_PATH:-}" ]]; then + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + fi + # Installs the toolchain and components pinned in rust-toolchain.toml. + rustup show + if [[ -n "$RUST_TARGETS" ]]; then + rustup target add $RUST_TARGETS + fi + + - name: Install just + if: ${{ inputs.install-just == 'true' }} + shell: bash + env: + JUST_VERSION: ${{ inputs.just-version }} + CARGO_INSTALL_TARGET_DIR: ${{ inputs.install-target-dir }} + run: | + set -euo pipefail + # Probe by actually running `just`, not `command -v just`: a mise/asdf + # shim on PATH satisfies `command -v` but fails at call time with + # "No version is set for shim: just" when no version is pinned. If it + # does not run, install a pinned just and prepend ~/.cargo/bin so the + # real binary shadows any lingering shim for the rest of the job. + if just --version >/dev/null 2>&1; then + echo "just already available: $(command -v just) -> $(just --version)" + else + cargo install just --version "$JUST_VERSION" --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" + if [[ -n "${GITHUB_PATH:-}" ]]; then + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + fi + "$HOME/.cargo/bin/just" --version + fi + + - name: Install cargo-deny + if: ${{ inputs.install-cargo-deny == 'true' }} + shell: bash + env: + CARGO_INSTALL_TARGET_DIR: ${{ inputs.install-target-dir }} + run: | + set -euo pipefail + if ! command -v cargo-deny >/dev/null 2>&1; then + cargo install cargo-deny --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" + fi + + - name: Install cargo-audit + if: ${{ inputs.install-cargo-audit == 'true' }} + shell: bash + env: + CARGO_INSTALL_TARGET_DIR: ${{ inputs.install-target-dir }} + run: | + set -euo pipefail + if ! command -v cargo-audit >/dev/null 2>&1; then + cargo install cargo-audit --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" + fi diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d52b976..53acb5d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,29 +32,15 @@ jobs: - macos-latest steps: - name: Checkout - uses: actions/checkout@v5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 with: persist-credentials: false - - name: Setup Rust - uses: dtolnay/rust-toolchain@stable - with: - components: rustfmt, clippy - - - name: Cache Cargo - uses: Swatinem/rust-cache@v2 - - - name: Check formatting - run: cargo fmt --all --check + - name: Setup Rust and just + uses: ./.github/actions/setup-rust - - name: Run Clippy - run: cargo clippy --all-targets -- -D warnings - - - name: Build - run: cargo build --locked - - - name: Test - run: cargo test --locked + - name: Quality gate (fmt, clippy, build, test) + run: just ci-rust deny: name: Dependency policy @@ -63,11 +49,14 @@ jobs: timeout-minutes: 15 steps: - name: Checkout - uses: actions/checkout@v5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 with: persist-credentials: false - - name: Dependency policy (cargo-deny) - uses: EmbarkStudios/cargo-deny-action@v2 + - name: Setup Rust, just, and cargo-deny + uses: ./.github/actions/setup-rust with: - manifest-path: Cargo.toml + install-cargo-deny: "true" + + - name: Dependency policy + run: just deny diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 3bb9c88..e4c0410 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -29,15 +29,27 @@ jobs: timeout-minutes: 15 steps: - name: Checkout - uses: actions/checkout@v5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 with: persist-credentials: false - name: Install Nix - uses: DeterminateSystems/nix-installer-action@v16 - with: - extra-conf: | - experimental-features = nix-command flakes + shell: bash + run: | + if ! command -v nix >/dev/null 2>&1; then + curl -sSf -L https://nixos.org/nix/install | sh -s -- install --no-confirm + fi + + - name: Enable nix-command and flakes + shell: bash + run: | + mkdir -p "$HOME/.config/nix" + if ! grep -q 'experimental-features' "$HOME/.config/nix/nix.conf" 2>/dev/null; then + echo 'experimental-features = nix-command flakes' >> "$HOME/.config/nix/nix.conf" + fi + + - name: Install just + uses: ./.github/actions/setup-rust - name: Build book - run: nix run nixpkgs#mdbook -- build docs + run: just docs diff --git a/.github/workflows/nix.yml b/.github/workflows/nix.yml index 2adf045..e6bd8cc 100644 --- a/.github/workflows/nix.yml +++ b/.github/workflows/nix.yml @@ -29,18 +29,33 @@ jobs: - macos-latest steps: - name: Checkout - uses: actions/checkout@v5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 with: persist-credentials: false - name: Install Nix - uses: DeterminateSystems/nix-installer-action@v16 + shell: bash + run: | + if ! command -v nix >/dev/null 2>&1; then + curl -sSf -L https://nixos.org/nix/install | sh -s -- install --no-confirm + fi + + - name: Enable nix-command and flakes + shell: bash + run: | + mkdir -p "$HOME/.config/nix" + if ! grep -q 'experimental-features' "$HOME/.config/nix/nix.conf" 2>/dev/null; then + echo 'experimental-features = nix-command flakes' >> "$HOME/.config/nix/nix.conf" + fi + + - name: Install just + uses: ./.github/actions/setup-rust with: - extra-conf: | - experimental-features = nix-command flakes + install-cargo-deny: "false" + install-cargo-audit: "false" - name: nix flake check - run: nix flake check + run: just flake-check - name: nix flake check (eval-only, all systems) run: nix flake check --all-systems --no-build diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index a878eee..9ac1e32 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -30,27 +30,17 @@ jobs: timeout-minutes: 15 steps: - name: Checkout - uses: actions/checkout@v5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 with: persist-credentials: false - - name: Setup Rust - uses: dtolnay/rust-toolchain@stable - - - name: Cache cargo-audit - uses: actions/cache@v5 + - name: Setup Rust, just, and cargo-audit + uses: ./.github/actions/setup-rust with: - path: ~/.cargo/bin/cargo-audit - key: cargo-audit-0.20 - - - name: Install cargo-audit - run: | - if ! command -v cargo-audit &> /dev/null; then - cargo install cargo-audit --locked - fi + install-cargo-audit: "true" - - name: Run cargo-audit - run: cargo audit --deny warnings + - name: Security audit + run: just audit deny: name: Dependency Check @@ -59,11 +49,14 @@ jobs: timeout-minutes: 15 steps: - name: Checkout - uses: actions/checkout@v5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 with: persist-credentials: false - - name: Dependency policy (cargo-deny) - uses: EmbarkStudios/cargo-deny-action@v2 + - name: Setup Rust, just, and cargo-deny + uses: ./.github/actions/setup-rust with: - manifest-path: Cargo.toml + install-cargo-deny: "true" + + - name: Dependency policy + run: just deny diff --git a/CHANGELOG.md b/CHANGELOG.md index 6619275..33e43aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [0.1.0] - 2026-07-28 ### Added diff --git a/Cargo.lock b/Cargo.lock index 2cdd0fc..e62c504 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -92,6 +92,22 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -168,8 +184,7 @@ checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" [[package]] name = "ecies" version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a2df85e2b13a5f7fa61e7f0ee776acfe74da80bf2fb1bcde2725af19c197b33" +source = "git+https://github.com/beardedeagle/rs.git?rev=81e1b84#81e1b840d99f2787b5c208f8172a496be304daf5" dependencies = [ "aes-gcm", "getrandom", @@ -451,6 +466,7 @@ dependencies = [ "hex", "libc", "rustix", + "security-framework", "serde", "serde_json", "zeroize", @@ -530,6 +546,29 @@ dependencies = [ "zeroize", ] +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "serde" version = "1.0.228" diff --git a/Cargo.toml b/Cargo.toml index f54c74d..2ab3515 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,9 +14,10 @@ repository = "https://github.com/beardedeagle/postmaster" # We use a fairly strict set of lints. One deliberate deviation: we allow # `unsafe_code` (some stricter projects deny it outright). postmaster is a # syscall-level socket-activation daemon and needs a handful of justified -# `unsafe` blocks (getpeereid(2), best-effort mlock()-style hardening, and -# UnixListener::from_raw_fd on the one inherited systemd fd) — each site in -# src/main.rs carries a SAFETY comment, so `unsafe_code` is left at rustc's +# `unsafe` blocks (getpeereid(2), best-effort mlock()-style hardening, +# signal-mask deferral around the plaintext-write window, and +# UnixListener::from_raw_fd on the one inherited systemd fd) — each site +# carries a SAFETY comment, so `unsafe_code` is left at rustc's # default (allow) rather than denied or blanket-warned. [lints.rust] future_incompatible = { level = "deny", priority = -1 } @@ -28,12 +29,14 @@ explicit_outlives_requirements = "warn" if_let_rescope = "warn" impl_trait_overcaptures = "warn" impl_trait_redundant_captures = "warn" -# `let _ = …` is postmaster's deliberate best-effort idiom: hardening calls -# (mlockall-style, non-dumpable, core limits, ptrace-deny) and cleanup paths -# (socket shutdown, stale-socket unlink, thread join at teardown) may -# legitimately fail, and the adjacent comments explain why that's acceptable. -# Converting them to unwrap/expect/error handling would CHANGE behavior in a -# fail-closed daemon, so the lint stays off. +# `let _ = …` is postmaster's deliberate best-effort idiom for cleanup +# paths (socket shutdown, stale-socket unlink, read-timeout set, thread +# join at teardown) that may legitimately fail, and the adjacent comments +# explain why that's acceptable. Security-relevant hardening calls +# (mlockall-style, non-dumpable, core limits, ptrace-deny) LOG their +# failures instead (audit 2026-08-02 A10). Converting either to +# unwrap/expect/error handling would CHANGE behavior in a fail-closed +# daemon, so the lint stays off. let_underscore_drop = "allow" macro_use_extern_crate = "warn" meta_variable_misuse = "warn" @@ -100,11 +103,19 @@ zeroize = "1" # single fd-ownership assertion at the systemd socket-activation boundary. rustix = { version = "1", features = ["net", "process", "mm", "fs"] } +# AAD support for the bundle adapter (audit 2026-08-02 A7) lives on the +# `aad-support` branch of the author's ecies fork pending the upstream PR +# against ecies/rs. Pinned by rev for reproducibility; drop this section +# once the PR merges and ships in a crates.io release. +[patch.crates-io] +ecies = { git = "https://github.com/beardedeagle/rs.git", rev = "81e1b84" } + [target.'cfg(target_os = "macos")'.dependencies] # Darwin's stable kernel ABI *is* libc (raw syscalls are unsupported there; # rustix itself calls through libc on darwin). Two narrow calls use it # directly: getpeereid for the peer check and PT_DENY_ATTACH hardening. libc = "0.2" +security-framework = "3.7.0" [profile.release] # Everything here is stable-toolchain and arch-agnostic: safe under nixpkgs @@ -114,6 +125,11 @@ opt-level = 3 lto = "fat" codegen-units = 1 strip = "symbols" +# PT_DENY_ATTACH (macOS hardening) is gated on not(debug_assertions); pin +# this so a profile override can't silently compile it out (audit +# 2026-08-02 A23). This is already the release default — explicitness is +# the guard. +debug-assertions = false # Arithmetic bugs become panic → abort → Restart=on-failure: fail closed, # never a wrong answer. Cost is ~nil (crypto deps use wrapping intrinsics). overflow-checks = true diff --git a/Justfile b/Justfile index 5c70074..d7a8a6a 100644 --- a/Justfile +++ b/Justfile @@ -36,10 +36,19 @@ flake-check: # ============================================================================= docs: + #!/usr/bin/env bash + set -euo pipefail + cp CHANGELOG.md docs/src/changelog.md mdbook build docs + rm -f docs/src/changelog.md + echo "Documentation built: docs/book/" docs-serve: - cd docs && mdbook serve + #!/usr/bin/env bash + set -euo pipefail + cp CHANGELOG.md docs/src/changelog.md + cd docs && mdbook serve --open + rm -f docs/src/changelog.md # ============================================================================= # Dependency policy @@ -57,3 +66,168 @@ audit: ci-rust: fmt-check clippy build test ci: ci-rust flake-check + +# ============================================================================= +# Build Matrix — Cross-platform builds with varying optimization levels +# ============================================================================= +# +# Optimization Levels: +# debug - Fast compile, no optimizations, debug symbols (for development) +# release - Cargo defaults (opt-level=3, no LTO) +# optimized - Thin LTO + single codegen unit (good balance of size/speed) +# max - Fat LTO + strip + CPU targeting (smallest, fastest binary) +# +# Targets: +# native - Current platform +# linux - x86_64-unknown-linux-gnu +# linux-musl - x86_64-unknown-linux-musl (static binary, no glibc dependency) +# linux-arm - aarch64-unknown-linux-gnu (ARM64 Linux: Graviton, Pi 4/5) +# macos - x86_64-apple-darwin (Intel Mac) +# macos-arm - aarch64-apple-darwin (Apple Silicon: M1 through M5) +# +# Usage: +# just build-matrix optimized linux # Build optimized for Linux +# just build-matrix max macos-arm # Max optimization for Apple Silicon +# just build-matrix release # Release build for current platform +# just build-all optimized # Build all platforms at optimization level +# ============================================================================= + +# Build with specific optimization level, optional target +build-matrix level target="native": + #!/usr/bin/env bash + set -euo pipefail + + LEVEL="{{level}}" + TARGET="{{target}}" + + # Validate optimization level + case "$LEVEL" in + debug|release|optimized|max) ;; + *) + echo "Error: Invalid optimization level '$LEVEL'" + echo "Valid levels: debug, release, optimized, max" + exit 1 + ;; + esac + + # Map target alias to Rust target triple + case "$TARGET" in + native) RUST_TARGET="" ;; + linux) RUST_TARGET="x86_64-unknown-linux-gnu" ;; + linux-musl) RUST_TARGET="x86_64-unknown-linux-musl" ;; + linux-arm) RUST_TARGET="aarch64-unknown-linux-gnu" ;; + macos) RUST_TARGET="x86_64-apple-darwin" ;; + macos-arm) RUST_TARGET="aarch64-apple-darwin" ;; + *) + echo "Error: Invalid target '$TARGET'" + echo "Valid targets: native, linux, linux-musl, linux-arm, macos, macos-arm" + exit 1 + ;; + esac + + # Set optimization flags based on level + case "$LEVEL" in + debug) + CARGO_ARGS="" + export CARGO_PROFILE_DEV_OPT_LEVEL=0 + echo "Building: debug (fast compile, no optimizations)" + ;; + release) + CARGO_ARGS="--release" + echo "Building: release (Cargo defaults)" + ;; + optimized) + CARGO_ARGS="--release" + export CARGO_PROFILE_RELEASE_LTO=thin + export CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 + echo "Building: optimized (LTO=thin, codegen-units=1)" + ;; + max) + CARGO_ARGS="--release" + export CARGO_PROFILE_RELEASE_LTO=fat + export CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 + export CARGO_PROFILE_RELEASE_OPT_LEVEL=3 + export CARGO_PROFILE_RELEASE_STRIP=symbols + # Use native CPU for ARM, x86-64-v3 for x86 targets + if [[ "$TARGET" == "macos-arm" ]] || [[ "$TARGET" == "linux-arm" ]] || [[ "$TARGET" == "native" && "$(uname -m)" == "arm64" ]]; then + export RUSTFLAGS="-C target-cpu=native" + else + export RUSTFLAGS="-C target-cpu=x86-64-v3" + fi + echo "Building: max (LTO=fat, strip, target-cpu optimized)" + ;; + esac + + # Build command + if [[ -n "$RUST_TARGET" ]]; then + echo "Target: $RUST_TARGET" + cargo +{{stable_toolchain}} build --locked $CARGO_ARGS --target "$RUST_TARGET" + echo "Output: target/$RUST_TARGET/$([ "$LEVEL" = "debug" ] && echo "debug" || echo "release")/postmaster" + else + echo "Target: native ($(rustc +{{stable_toolchain}} -vV | grep host | cut -d' ' -f2))" + cargo +{{stable_toolchain}} build --locked $CARGO_ARGS + echo "Output: target/$([ "$LEVEL" = "debug" ] && echo "debug" || echo "release")/postmaster" + fi + +# Build all platforms at a given optimization level (requires cross-compilation setup) +build-all level="release": + @echo "Building all platforms at '{{level}}' optimization level..." + @echo "Note: Cross-compilation requires 'cross' tool or appropriate toolchains" + @echo "" + just build-matrix {{level}} native + @echo "" + @echo "For cross-compilation to other platforms, install targets with:" + @echo " rustup target add x86_64-unknown-linux-gnu" + @echo " rustup target add x86_64-unknown-linux-musl" + @echo " rustup target add aarch64-unknown-linux-gnu" + @echo " rustup target add x86_64-apple-darwin" + @echo " rustup target add aarch64-apple-darwin" + @echo "" + @echo "Or use 'cross' for easier cross-compilation: cargo install cross" + +# Show build matrix help +build-help: + @echo "Build Matrix — Cross-platform builds with optimization levels" + @echo "" + @echo "USAGE:" + @echo " just build-matrix [target]" + @echo "" + @echo "ARGUMENTS:" + @echo " level Required. Optimization level (see below)" + @echo " target Optional. Platform target (default: native)" + @echo "" + @echo "OPTIMIZATION LEVELS:" + @echo " debug Fast compile, no optimizations, includes debug symbols" + @echo " Best for: development, debugging, quick iteration" + @echo "" + @echo " release Cargo defaults (opt-level=3, no LTO)" + @echo " Best for: testing release behavior, CI builds" + @echo "" + @echo " optimized LTO (thin) + single codegen unit" + @echo " Best for: staging deployments, performance testing" + @echo "" + @echo " max LTO (fat) + strip + CPU targeting (x86-64-v3 or native ARM)" + @echo " Best for: production deployments, final releases" + @echo "" + @echo "TARGETS:" + @echo " native Current platform (default)" + @echo " linux x86_64-unknown-linux-gnu" + @echo " linux-musl x86_64-unknown-linux-musl (static binary)" + @echo " linux-arm aarch64-unknown-linux-gnu (ARM64: Graviton, Pi 4/5)" + @echo " macos x86_64-apple-darwin (Intel Mac)" + @echo " macos-arm aarch64-apple-darwin (Apple Silicon: M1-M5)" + @echo "" + @echo "EXAMPLES:" + @echo " just build-matrix debug # Quick dev build" + @echo " just build-matrix release # Standard release" + @echo " just build-matrix optimized linux # Optimized for Linux" + @echo " just build-matrix max macos-arm # Max for Apple Silicon" + @echo " just build-matrix max linux-arm # Max for ARM Linux" + @echo "" + @echo "TRADE-OFFS (times/sizes vary with codebase growth):" + @echo " Level Compile Time Binary Size Runtime Perf" + @echo " --------- ------------- ----------- ------------" + @echo " debug fastest largest 1x (baseline)" + @echo " release ~1.3x debug ~3-4x smaller 3-5x faster" + @echo " optimized ~2x debug ~4-5x smaller 5-7x faster" + @echo " max ~3x debug smallest 7-10x faster" diff --git a/README.md b/README.md index 647ad3d..84d5281 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ environment. Runtime flow per service (systemd path): -``` +```text 1. Nix store holds the encrypted .env file (ciphertext, public) ↓ 2. systemd LoadCredential= places key material in $CREDENTIALS_DIRECTORY @@ -132,12 +132,17 @@ See [docs/src/SUMMARY.md](docs/src/SUMMARY.md) for the table of contents. ## Building ```console -$ cargo build -$ cargo test -$ cargo clippy --all-targets -$ cargo fmt --check +$ just build # debug build +$ just test # run tests +$ just clippy # lint +$ just fmt-check # format check +$ just ci-rust # all of the above in one command +$ just build-matrix max macos-arm # optimized release ``` +See `just build-help` for the full build matrix (optimization levels +and cross-compilation targets). + With Nix: ```console diff --git a/deny.toml b/deny.toml index 4672a7f..f568047 100644 --- a/deny.toml +++ b/deny.toml @@ -39,3 +39,9 @@ confidence-threshold = 0.93 # The postmaster crate is the only member today. [licenses.private] ignore = true + +[sources] +# The ecies fork in [patch.crates-io] (audit 2026-08-02 A7) is the only +# sanctioned git source; drop this entry together with the patch section +# once the upstream PR ships in a crates.io release. +allow-git = ["https://github.com/beardedeagle/rs.git"] diff --git a/docs/mdbook-build-issue.md b/docs/mdbook-build-issue.md new file mode 100644 index 0000000..8d4621b --- /dev/null +++ b/docs/mdbook-build-issue.md @@ -0,0 +1,84 @@ +# mdbook build is broken: SUMMARY.md references a missing `changelog.md` + +> **Status:** Pre-existing — not introduced by any recent documentation +> edits. It blocks `mdbook build docs`, so the rendered site under +> `docs/book/` is stale and cannot be regenerated until resolved. + +## Summary + +`docs/src/SUMMARY.md` declares a `Changelog` chapter pointing at +`./changelog.md`, which resolves to `docs/src/changelog.md` — a file that +does not exist. The project's changelog actually lives at the repository +root (`CHANGELOG.md`). mdbook fails fast on the missing chapter and emits +no rendered output. + +## Reproduction + +```console +$ mdbook build docs +ERROR failed to read chapter `./changelog.md` + Caused by: No such file or directory (os error 2) +``` + +## Evidence + +- `docs/src/SUMMARY.md:24` → `- [Changelog](./changelog.md)` +- `docs/src/changelog.md` → **missing** (`No such file or directory`) +- `CHANGELOG.md` (repo root) → present (~2.8 KB) +- `docs/book/` is `.gitignore`d (generated output), so this affects only + local/CI rendering, not committed source. + +## Impact + +- `mdbook build docs` and `mdbook serve docs` fail; no rendered book is + produced. +- Edits to the markdown source under `docs/src/` (e.g. `getting-started/`) + do **not** propagate to the rendered HTML until this is fixed. +- The gitignored `docs/book/` is frozen at whatever was last successfully + built. + +## Fix options (in order of preference) + +### 1. Include the root changelog via mdbook `{{#include}}` (recommended) + +Create `docs/src/changelog.md` as a thin page that pulls in the root file, +keeping a single source of truth. `SUMMARY.md` stays as-is (`./changelog.md` +now exists): + +```markdown +# Changelog + +{{#include ../../CHANGELOG.md}} +``` + +mdbook resolves the include at build time; the root `CHANGELOG.md` remains +authoritative and there is no duplicated content to drift. + +### 2. Repoint SUMMARY.md at the root file + +Change `docs/src/SUMMARY.md:24` to: + +```markdown +- [Changelog](../../CHANGELOG.md) +``` + +Caveat: verify mdbook accepts a chapter path outside `src/` (it generally +does, but worth confirming on your mdbook version). + +### 3. Symlink + +`docs/src/changelog.md` → `../../CHANGELOG.md`. Single source of truth, but +symlinks can be awkward across platforms/git checkouts, and mdbook's +handling of symlinked chapters should be confirmed. + +### 4. Copy via a pre-build step + +Have the `Justfile` copy `CHANGELOG.md` → `docs/src/changelog.md` before +`mdbook build`. Simple, but introduces a duplicate that can drift unless +the copy is automated and enforced. + +## Recommendation + +**Option 1 (`{{#include}}`)** — idiomatic mdbook, no duplication, root +`CHANGELOG.md` stays the single source of truth, and `SUMMARY.md` needs no +change. diff --git a/docs/src/architecture/materialization-abi.md b/docs/src/architecture/materialization-abi.md index 6b74ddd..42a1bc3 100644 --- a/docs/src/architecture/materialization-abi.md +++ b/docs/src/architecture/materialization-abi.md @@ -120,7 +120,8 @@ filename selects the private key variable: - `.env` maps to `DOTENV_PRIVATE_KEY` - `.env.production` maps to `DOTENV_PRIVATE_KEY_PRODUCTION` -- non-alphanumeric environment suffix bytes normalize to `_` +- environment names must be non-empty `[A-Za-z0-9_]` (letters fold to + upper case); anything else is rejected The `.env` adapter is the first adapter, not the ceiling of the system. @@ -139,7 +140,7 @@ diff, while encrypted values remain opaque base64 strings. "format": "postmaster.bundle", "version": 1, "profile": "production", - "suite": "ecies-secp256k1-hkdf-sha256-aes-256-gcm", + "suite": "ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad", "recipients": [ { "id": "host:api-01", @@ -160,10 +161,16 @@ diff, while encrypted values remain opaque base64 strings. ``` All fields above are public metadata except `ciphertext`, which is encrypted -and authenticated. The metadata that affects interpretation must be covered -by authentication so a store or repo adversary cannot rename a key, change a -profile, change a recipient id, switch an encoding, or replay a value between -profiles without detection. +and authenticated. Each entry's ciphertext is additionally bound to its key +name as AES-GCM additional authenticated data (the `-entry-aad` suite): a +store or repo adversary who cuts a ciphertext from one entry and pastes it +under another key name gets an authentication failure at decryption, not a +mislabeled secret. + +The remaining metadata (profile, recipient ids, encodings) is not yet +cryptographically bound. Binding it requires specifying canonical serialized +bytes for the authenticated metadata first — generated artifacts need +deterministic bytes for reproducible builds and stable test vectors. The design constraints are: @@ -179,9 +186,6 @@ The design constraints are: - `encoding` is either `utf8` or `bytes`. `env` projection rejects bytes that cannot become a POSIX environment value; `files` and `credentials` preserve byte-exact values. -- The canonical serialized bytes for authenticated metadata must be specified - before implementation. Generated artifacts need deterministic bytes for - reproducible builds and stable test vectors. - A bundle can contain many entries for one projection, but it does not encode service-manager policy. Projection remains in the `postmaster` config, not inside the encrypted artifact. diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index eee1e7f..744416a 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -181,15 +181,15 @@ read or written: ### External binary verification -Postmaster verifies the integrity of external binaries before -invoking them in the secret path: +Keychain access on macOS uses the Security.framework API in-process — +no external binary is invoked for it. The external binaries postmaster +does invoke in secret-adjacent paths (`/usr/bin/id`, `/sbin/mount`, +`/usr/bin/hdiutil`) are verified before use: -- **macOS:** `/usr/bin/security` is verified via `codesign -v` before - being invoked for keychain access. This ensures the binary has a - valid Apple code signature and has not been tampered with or - replaced. -- **Linux:** External binaries are verified as regular files owned - by root (uid 0) and not world-writable. +- **macOS:** `codesign -v` verifies a valid Apple code signature + (defense-in-depth; the binaries are also SIP-protected). +- **Linux:** verified as regular files owned by root (uid 0) and not + world-writable. ### Input validation @@ -217,11 +217,14 @@ the secret path: ### Key freshness verification Postmaster provides `--verify-keys` on `exec` to detect stale keys -from a previous rotation cycle. After loading and decrypting, if the -resolved values are empty but the env files contain `encrypted:` -values, the keys are stale and the exec aborts with a clear error. -This catches the `strict: false` case where stale keys would silently -skip undecryptable values and launch the child with no secrets. +from a previous rotation cycle. After loading and decrypting, if any +value was skipped because the key ring could not decrypt it, the exec +aborts with a clear error naming the key. This catches the +`strict: false` case where stale keys would otherwise silently skip +undecryptable values and launch the child with a partial or empty +secret set. Bundle files need no such check: bundle resolution is +all-or-nothing, so a stale bundle key already aborts the exec +regardless of `strict`. ## Residuals: what postmaster cannot fully prevent @@ -250,6 +253,31 @@ A process running as root can read any other process's memory via always game over. Postmaster's `PR_SET_DUMPABLE=0` and `PT_DENY_ATTACH` prevent non-privileged peers from attaching, but cannot stop root. +### Rotation timing oracle + +When multiple private keys are configured for one variable (the +comma-separated rotation convention), decryption tries each candidate in +order and stops at the first that works. A local observer measuring +launch or fetch latency can infer which candidate matched — i.e., the +rotation position of the current key. Accepted (audit 2026-08-02 A14): +the observer learns only the rotation index, not key material, and +already needs same-host access; equalizing the timing would require +attempting every candidate on every decryption for no meaningful gain. + +### Env-file content is trusted input (no variable-name denylist) + +Postmaster injects what the configured env files and bundles say, +including plaintext passthrough entries. There is no denylist of +environment variable names (audit 2026-08-02 A18): names like +`LD_PRELOAD` or `PATH` are honored, because real deployments +legitimately set variables of this family (`LD_LIBRARY_PATH` is common). +The protection boundary is artifact authorship: anyone who can write the +env file (or produce valid ciphertext for it) already controls what the +child process receives. Treat plaintext passthrough entries in +world-readable artifacts as code-level intent, and keep artifact write +access tight. If a denylist is ever wanted, it belongs in config +validation as an explicit opt-in policy, not a silent default. + ### Swap and core dumps Swap and core dumps are the two ways plaintext can leak from memory to diff --git a/docs/src/getting-started/key-provisioning.md b/docs/src/getting-started/key-provisioning.md index 8e06cbb..8d96dd4 100644 --- a/docs/src/getting-started/key-provisioning.md +++ b/docs/src/getting-started/key-provisioning.md @@ -126,5 +126,5 @@ Use `--verify-keys` to catch stale keys before they cause a silent failure: ```console -$ postmaster exec --config exec.json --verify-keys -- /bin/true +$ postmaster exec --config exec.json --verify-keys -- /usr/bin/true ``` diff --git a/docs/src/getting-started/quick-start.md b/docs/src/getting-started/quick-start.md index 6359621..bf73d7c 100644 --- a/docs/src/getting-started/quick-start.md +++ b/docs/src/getting-started/quick-start.md @@ -39,14 +39,21 @@ API_TOKEN="encrypted:BGAAAAAADWyy..." ## Step 2: Provision keys -Postmaster needs the private key to decrypt the values. The key lives in -a `.env.keys` file: +Postmaster needs the private key to decrypt the values. `dotenvx set` +above wrote it to a `.env.keys` file alongside your env file: ```console -$ dotenvx keys -f secrets/.env.production -DOTENV_PRIVATE_KEY_PRODUCTION="a1b2c3d4e5f6..." +$ cat secrets/.env.keys +DOTENV_PRIVATE_KEY_PRODUCTION=a1b2c3d4e5f6... ``` +> **dotenvx version note:** the CLI changes across releases. Older +> versions exposed the private key through a `dotenvx keys` subcommand +> (since removed); current versions write it to the `.env.keys` file +> next to your env file, and the value may be quoted or unquoted +> depending on version. Treat the `.env.keys` file as the durable +> source — copy the `DOTENV_PRIVATE_KEY_*` value from it. + Place the keys file on the host (Linux): ```console diff --git a/docs/src/reference/cli.md b/docs/src/reference/cli.md index 11d7596..86b52a2 100644 --- a/docs/src/reference/cli.md +++ b/docs/src/reference/cli.md @@ -65,10 +65,10 @@ $ postmaster exec --config [--check] [--verify-keys] -- [a - On failure the error is logged and the process exits non-zero. - `--check` does not accept a command after `--`. - `--verify-keys` performs a preflight check: after loading and - decrypting, if the resolved values are empty but the env files - contain `encrypted:` values, the keys are stale and the exec - aborts. This catches the `strict: false` case where stale keys - would silently skip undecryptable values. + decrypting, if any value was skipped because the key ring could not + decrypt it, the keys are stale and the exec aborts naming the key. + This catches the `strict: false` case where stale keys would + otherwise silently skip undecryptable values (partial or empty set). Exit codes: diff --git a/docs/src/reference/launcher-contract.md b/docs/src/reference/launcher-contract.md index 0b710b8..5ec24d6 100644 --- a/docs/src/reference/launcher-contract.md +++ b/docs/src/reference/launcher-contract.md @@ -48,7 +48,7 @@ binding to emit `exec.json`; it is not privileged over any other binding. **A binding is correct if and only if the `exec.json` it emits is described by this document and passes the conformance suite.** Nothing here documents intent or a roadmap; every claim below is true -of the committed parser and launcher (`src/config.rs`, +of the committed parser and launcher (`src/exec_config.rs`, `src/launcher.rs`, `src/keys.rs`) as of this writing. ### Config to launch flow @@ -100,11 +100,13 @@ $ postmaster cleanup --config reading key material, checking the filesystem, fetching sockets, or launching the child command. It does not accept a command after `--`. - `--verify-keys` performs a preflight check: after loading and decrypting, - if the resolved values are empty but the env files contain `encrypted:` - values, the keys are stale (from a previous rotation cycle) and the exec - aborts with a clear error. This catches the `strict: false` case where - stale keys would silently skip undecryptable values and launch the child - with no secrets. + if any value was skipped because the key ring could not decrypt it + (stale keys from a previous rotation cycle), the exec aborts with a + clear error naming the key. This catches the `strict: false` case where + stale keys would otherwise silently skip undecryptable values and + launch the child with a partial or empty secret set. Bundle files need + no such check: bundle resolution is all-or-nothing, so a stale bundle + key already aborts the exec regardless of `strict`. - `setup` verifies platform prerequisites, creates keys directory with 0700, verifies/creates keys files with 0600, optionally seeds keychain items (macOS), and validates the environment. Idempotent. `--recheck` @@ -126,7 +128,7 @@ $ postmaster cleanup --config ## `ExecConfig` fields -`exec.json` deserializes into this struct (`src/config.rs`). +`exec.json` deserializes into this struct (`src/exec_config.rs`). Unknown root fields are rejected. ABI fields such as `version` or `adapter` must not be emitted until the parser and schema explicitly define them. A machine-readable JSON Schema for this current shape is kept at @@ -345,10 +347,12 @@ this mode — it dispatches on whether `sockets` is empty: keys file with `O_NOFOLLOW` and `fstat`s the fd to verify: no group/world access (`mode & 0o077 == 0`), and owned by the current euid. A world-readable or symlinked keys file fails closed. -- **External binary verification.** On macOS, `from_keychain` verifies - the code signature of `/usr/bin/security` via `codesign -v` before - invoking it. On Linux, external binaries are verified as regular files - owned by root (uid 0) and not world-writable. +- **External binary verification.** Keychain access uses the + Security.framework API in-process — no external binary is invoked for + it. The external binaries postmaster does invoke (`/usr/bin/id`, + `/sbin/mount`, `/usr/bin/hdiutil` on macOS) are verified first: + `codesign -v` on macOS; on Linux, verified as regular files owned by + root (uid 0) and not world-writable. - **`verify_ramdisk` (darwin ramdisk guard).** When set, before any plaintext is written the launcher runs two checks: it shells out to `/sbin/mount` and requires the configured mount point to appear as an diff --git a/nixpkgs-package.nix b/nixpkgs-package.nix index 3bec812..2456a91 100644 --- a/nixpkgs-package.nix +++ b/nixpkgs-package.nix @@ -38,7 +38,10 @@ rustPlatform.buildRustPackage rec { cargoLock = { lockFile = src + "/postmaster/Cargo.lock"; - # No outputHashes needed — all dependencies come from crates.io. + # While ecies is git-pinned via [patch.crates-io] (audit 2026-08-02 A7), + # this also needs: outputHashes."ecies-0.2.11" = "sha256-…"; (fill via + # the fake-hash trick). Unneeded again once the upstream ecies PR ships + # on crates.io and the patch section is dropped. }; meta = { diff --git a/package.nix b/package.nix index 99d3f51..b5ef214 100644 --- a/package.nix +++ b/package.nix @@ -25,6 +25,13 @@ rustPlatform.buildRustPackage { ]; }; cargoLock.lockFile = ./Cargo.lock; + # Cargo.lock currently pins ecies to a git rev (see [patch.crates-io] in + # Cargo.toml, audit 2026-08-02 A7), so importCargoLock additionally needs: + # cargoLock.outputHashes."ecies-0.2.11" = "sha256-…"; + # Fill it in on a machine with nix using the fake-hash trick: set a dummy + # (sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=), run `just + # flake-check`, and copy the "got:" hash from the error. Drop this again + # when the upstream ecies PR ships on crates.io and the patch is removed. meta = { description = cargoToml.package.description; diff --git a/src/adapter.rs b/src/adapter.rs index 5b75ddc..cf8b8a2 100644 --- a/src/adapter.rs +++ b/src/adapter.rs @@ -11,8 +11,6 @@ //! every adapter at compile time — adding a variant is a deliberate act //! that forces all code paths to acknowledge it. -#![allow(missing_docs, missing_debug_implementations)] - use std::path::Path; /// The key-naming convention for a secret input adapter. @@ -74,16 +72,17 @@ impl KeyNaming { let env = rest.strip_prefix('.').ok_or_else(|| { format!("{base}: env files must follow the `.env[.]` convention") })?; - let suffix: String = env - .chars() - .map(|c| { - if c.is_ascii_alphanumeric() { - c.to_ascii_uppercase() - } else { - '_' - } - }) - .collect(); + // Reject anything outside [A-Za-z0-9_]: such characters + // would sanitize to '_', making distinct filenames collide + // on the same key variable (`.env..x` ≡ `.env._x`) + // (audit 2026-08-02 A20). Letters fold to upper case, the + // dotenvx convention. + if env.is_empty() || !env.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + return Err(format!( + "{base}: environment name must be non-empty [A-Za-z0-9_] only" + )); + } + let suffix: String = env.chars().map(|c| c.to_ascii_uppercase()).collect(); Ok(format!("{}_{}", self.key_prefix(), suffix)) } KeyNaming::Bundle => Ok(self.key_prefix().into()), @@ -98,3 +97,46 @@ impl KeyNaming { } } } + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn key_var_for_env_mapping() { + assert_eq!( + KeyNaming::Env.key_var_for(Path::new("/x/.env")).unwrap(), + "DOTENV_PRIVATE_KEY" + ); + assert_eq!( + KeyNaming::Env + .key_var_for(Path::new("/x/.env.production")) + .unwrap(), + "DOTENV_PRIVATE_KEY_PRODUCTION" + ); + } + + #[test] + fn key_var_for_rejects_aliasing_names() { + // audit 2026-08-02 A20: `.env..x` used to alias `.env._x` onto the + // same key variable (DOTENV_PRIVATE_KEY__X); lossy names now fail. + assert!(KeyNaming::Env.key_var_for(Path::new("/x/.env..x")).is_err()); + assert!(KeyNaming::Env.key_var_for(Path::new("/x/.env.-x")).is_err()); + assert!(KeyNaming::Env.key_var_for(Path::new("/x/.env.")).is_err()); + assert_eq!( + KeyNaming::Env.key_var_for(Path::new("/x/.env._x")).unwrap(), + "DOTENV_PRIVATE_KEY__X" + ); + } + + #[test] + fn key_var_for_bundle_is_constant() { + assert_eq!( + KeyNaming::Bundle + .key_var_for(Path::new("/x/anything.json")) + .unwrap(), + "POSTMASTER_KEY" + ); + } +} diff --git a/src/bundle.rs b/src/bundle.rs index 57a2e60..11dd8fb 100644 --- a/src/bundle.rs +++ b/src/bundle.rs @@ -10,10 +10,11 @@ //! - `entries`: map of key name → `{ encoding, ciphertext }` //! //! All fields are public metadata except `ciphertext`, which is -//! encrypted and authenticated. Entries use the same identifier rule -//! as `.env`-derived keys: `[A-Za-z_][A-Za-z0-9_]*`. - -#![allow(missing_docs, missing_debug_implementations)] +//! encrypted and authenticated. Each entry's ciphertext is additionally +//! bound to its key name as AES-GCM additional authenticated data (AAD): +//! a ciphertext cut from one entry and pasted under another name fails +//! decryption (audit 2026-08-02 A7). Entries use the same identifier +//! rule as `.env`-derived keys: `[A-Za-z_][A-Za-z0-9_]*`. use std::path::Path; @@ -71,10 +72,18 @@ pub struct BundleEntry { #[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum Encoding { + /// UTF-8 string value (env projection rejects non-UTF-8). Utf8, + /// Raw byte value (files/credentials preserve byte-exact). Bytes, } +/// The only supported crypto suite: ECIES (secp256k1, HKDF-SHA256, +/// AES-256-GCM) with the entry name bound as AES-GCM additional +/// authenticated data. Pre-AAD v1 ciphertexts are rejected at decryption +/// (authentication failure), not just here. +const SUITE: &str = "ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad"; + /// Parse a bundle JSON file from raw bytes. pub fn parse_bundle(raw: &[u8], path: &Path) -> Result { let bundle: Bundle = @@ -93,9 +102,9 @@ pub fn parse_bundle(raw: &[u8], path: &Path) -> Result { bundle.version )); } - if bundle.suite != "ecies-secp256k1-hkdf-sha256-aes-256-gcm" { + if bundle.suite != SUITE { return Err(format!( - "{}: unsupported suite {:?} (expected ecies-secp256k1-hkdf-sha256-aes-256-gcm)", + "{}: unsupported suite {:?} (expected {SUITE})", path.display(), bundle.suite )); @@ -136,9 +145,11 @@ pub fn resolve_bundle( .decode(&entry.ciphertext) .map_err(|_| format!("{}: {name} is not valid base64", bundle_path.display()))?, ); + // AAD = the entry name: a ciphertext pasted under a different + // entry fails authentication here (audit 2026-08-02 A7). let mut decrypted: Option>> = None; for sk in candidates { - if let Ok(pt) = ecies::decrypt(&sk[..], &ciphertext) { + if let Ok(pt) = ecies::decrypt_with_aad(&sk[..], &ciphertext, name.as_bytes()) { decrypted = Some(Zeroizing::new(pt)); break; } @@ -147,10 +158,10 @@ pub fn resolve_bundle( Some(pt) => out.push((name.clone(), pt, entry.encoding)), None => { let _ = ciphertext; // zeroize on drop + // No candidate count in the error text (audit 2026-08-02 A15). return Err(format!( - "{}: no key under {var} decrypts {name} ({} candidate(s) tried)", - bundle_path.display(), - candidates.len() + "{}: no key under {var} decrypts {name}", + bundle_path.display() )); } } @@ -186,7 +197,7 @@ mod tests { format: "postmaster.bundle".into(), version: 1, profile: Some("test".into()), - suite: "ecies-secp256k1-hkdf-sha256-aes-256-gcm".into(), + suite: SUITE.into(), recipients: vec![Recipient { id: "test".into(), public_key: test_pk_hex(), @@ -195,9 +206,9 @@ mod tests { } } - fn enc(value: &str) -> String { + fn enc(name: &str, value: &str) -> String { let pk = hex::decode(test_pk_hex()).unwrap(); - let ct = ecies::encrypt(&pk, value.as_bytes()).unwrap(); + let ct = ecies::encrypt_with_aad(&pk, value.as_bytes(), name.as_bytes()).unwrap(); BASE64.encode(ct) } @@ -206,7 +217,7 @@ mod tests { let raw = serde_json::json!({ "format": "wrong", "version": 1, - "suite": "ecies-secp256k1-hkdf-sha256-aes-256-gcm", + "suite": "ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad", "recipients": [], "entries": {} }); @@ -223,7 +234,7 @@ mod tests { let raw = serde_json::json!({ "format": "postmaster.bundle", "version": 99, - "suite": "ecies-secp256k1-hkdf-sha256-aes-256-gcm", + "suite": "ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad", "recipients": [], "entries": {} }); @@ -257,7 +268,7 @@ mod tests { let raw = serde_json::json!({ "format": "postmaster.bundle", "version": 1, - "suite": "ecies-secp256k1-hkdf-sha256-aes-256-gcm", + "suite": "ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad", "recipients": [], "entries": { "BAD.KEY": { "encoding": "utf8", "ciphertext": "dGVzdA==" } @@ -276,7 +287,7 @@ mod tests { let raw = serde_json::json!({ "format": "postmaster.bundle", "version": 1, - "suite": "ecies-secp256k1-hkdf-sha256-aes-256-gcm", + "suite": "ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad", "recipients": [], "entries": {}, "unknown_field": "should fail" @@ -292,7 +303,7 @@ mod tests { #[test] fn resolve_bundle_decrypts_entries() { - let ct = enc("hello-bundle"); + let ct = enc("SECRET", "hello-bundle"); let bundle = make_bundle(vec![("SECRET", &ct, Encoding::Utf8)]); let ring = crate::keys::tests::make_test_ring(); let resolved = resolve_bundle(&bundle, &ring, Path::new("/test")).unwrap(); @@ -302,14 +313,27 @@ mod tests { assert_eq!(resolved[0].2, Encoding::Utf8); } + #[test] + fn resolve_bundle_rejects_relocated_ciphertext() { + // audit 2026-08-02 A7: a ciphertext encrypted under one entry + // name must not decrypt under another. + let ct = enc("REAL", "top-secret"); + let bundle = make_bundle(vec![("FAKE", &ct, Encoding::Utf8)]); + let ring = crate::keys::tests::make_test_ring(); + let err = resolve_bundle(&bundle, &ring, Path::new("/test")).unwrap_err(); + assert!(err.contains("no key under"), "{err}"); + } + #[test] fn resolve_bundle_fails_on_wrong_key() { let other_sk = "22".repeat(32); let other_sk_bytes = hex::decode(&other_sk).unwrap(); let other_sk = ecies::SecretKey::parse_slice(&other_sk_bytes).unwrap(); let other_pk = ecies::PublicKey::from_secret_key(&other_sk); - let ct = BASE64 - .encode(ecies::encrypt(&other_pk.serialize_compressed(), b"unreachable").unwrap()); + let ct = BASE64.encode( + ecies::encrypt_with_aad(&other_pk.serialize_compressed(), b"unreachable", b"SECRET") + .unwrap(), + ); let bundle = make_bundle(vec![("SECRET", &ct, Encoding::Utf8)]); let ring = crate::keys::tests::make_test_ring(); let err = resolve_bundle(&bundle, &ring, Path::new("/test")).unwrap_err(); @@ -320,7 +344,7 @@ mod tests { fn resolve_bundle_handles_bytes_encoding() { let binary_val = b"\x00\x01\x02\xff"; let pk = hex::decode(test_pk_hex()).unwrap(); - let ct = BASE64.encode(ecies::encrypt(&pk, binary_val).unwrap()); + let ct = BASE64.encode(ecies::encrypt_with_aad(&pk, binary_val, b"TLS_KEY").unwrap()); let bundle = make_bundle(vec![("TLS_KEY", &ct, Encoding::Bytes)]); let ring = crate::keys::tests::make_test_ring(); let resolved = resolve_bundle(&bundle, &ring, Path::new("/test")).unwrap(); @@ -330,8 +354,8 @@ mod tests { #[test] fn resolve_bundle_multiple_entries() { - let ct1 = enc("value1"); - let ct2 = enc("value2"); + let ct1 = enc("KEY_A", "value1"); + let ct2 = enc("KEY_B", "value2"); let bundle = make_bundle(vec![ ("KEY_A", &ct1, Encoding::Utf8), ("KEY_B", &ct2, Encoding::Utf8), diff --git a/src/config.rs b/src/config.rs index 33245c9..7657afa 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,17 +3,16 @@ //! The config is generated by the Nix module as JSON. It contains only //! public information (store paths for ciphertext + key *names*). -#![allow(missing_docs, missing_debug_implementations)] - use std::collections::HashMap; -use std::path::{Component, Path, PathBuf}; +use std::path::PathBuf; use serde::Deserialize; -use crate::adapter::KeyNaming; - /// Full configuration loaded from the JSON file produced by the Nix module. +/// Unknown fields are rejected (audit 2026-08-02 A21) — same strictness +/// as the exec config. #[derive(Deserialize, Debug)] +#[serde(deny_unknown_fields)] pub struct Config { /// Where the .env.keys material comes from. pub keys: KeysSource, @@ -45,28 +44,40 @@ pub struct Entry { pub peer_user: Option, } +/// Parsed command-line arguments for the `serve` invocation. #[derive(Debug)] pub struct Args { + /// Path to the daemon config JSON file. pub config: PathBuf, + /// Bind listener sockets even when not socket-activated. pub bind: bool, + /// Allow non-root peers to connect (dangerous, darwin only). pub allow_nonroot: bool, } +/// The parsed top-level invocation selected from CLI arguments. #[derive(Debug)] pub enum Invocation { + /// `postmaster --config [--bind] [--allow-nonroot]`: + /// run the credential daemon (socket-activated on Linux, bind on macOS). Serve(Args), + /// `postmaster fetch `: connect to a running daemon + /// socket and write the decrypted bytes to stdout. Fetch(PathBuf), /// `postmaster exec --config [--check] [--verify-keys]` /// `-- `: decrypt + inject per the launcher contract, then /// execvp argv. See launcher.rs. Exec { + /// Path to the exec config JSON. config: PathBuf, + /// Validate config shape only — no decryption, no exec. check: bool, /// Preflight: attempt a test decryption of one encrypted value /// from each env file before proceeding to exec. Catches stale /// keys from a previous rotation cycle that are valid hex but /// no longer match the ciphertext (audit finding #4). verify_keys: bool, + /// Child argv — everything after `--` on the command line. argv: Vec, }, /// `postmaster setup --config [--recheck] [--unattended] @@ -76,10 +87,15 @@ pub enum Invocation { /// steps that are already correct. `--recheck` re-verifies without /// creating or modifying anything. Setup { + /// Path to the exec config JSON. config: PathBuf, + /// Verification only — no creation or modification. recheck: bool, + /// Non-interactive mode for automation (fail closed, no prompts). unattended: bool, + /// Re-create or re-seed even if already correct. force: bool, + /// Override the default keys directory path. keys_dir: Option, }, /// `postmaster cleanup --config `: remove all secret files @@ -88,6 +104,7 @@ pub enum Invocation { /// service managers. Does not decrypt — only removes files that /// postmaster would have written. Cleanup { + /// Path to the exec config JSON. config: PathBuf, }, /// Print help text and exit successfully. @@ -96,8 +113,10 @@ pub enum Invocation { Version, } +/// Crate version, resolved at compile time from `CARGO_PKG_VERSION`. pub const VERSION: &str = env!("CARGO_PKG_VERSION"); +/// Top-level help text shown by `postmaster --help` or `postmaster help`. pub const HELP_TOP: &str = "postmaster — standalone secret materialization engine\n\n\ USAGE:\n \ postmaster --config [--bind] [--allow-nonroot]\n \ @@ -124,6 +143,7 @@ OPTIONS:\n \ --version, -V Print version and exit\n \ --help, -h Show this help message\n"; +/// Help text for the `exec` subcommand. pub const HELP_EXEC: &str = "postmaster exec — decrypt secrets and exec a child process\n\n\ USAGE:\n \ postmaster exec --config [--check] [--verify-keys] -- [args…]\n\n\ @@ -138,6 +158,7 @@ OPTIONS:\n \ The config must specify mode (env/files/credentials), key sources, and\n\ artifact paths. See docs/src/launcher-contract.md for the full contract.\n"; +/// Help text for the `fetch` subcommand. pub const HELP_FETCH: &str = "postmaster fetch — fetch a secret from a daemon socket\n\n\ USAGE:\n \ postmaster fetch \n\n\ @@ -148,6 +169,7 @@ the daemon into the RAM disk.\n\n\ The socket path must be a single relative or absolute path to the AF_UNIX\n\ socket created by `postmaster --config `.\n"; +/// Help text for the `setup` subcommand. pub const HELP_SETUP: &str = "postmaster setup — verify environment and create key material\n\n\ USAGE:\n \ postmaster setup --config [--recheck] [--unattended] [--force] [--keys-dir ]\n\n\ @@ -165,6 +187,7 @@ OPTIONS:\n \ Default keys directory: /var/lib/postmaster (Linux),\n\ ~/Library/Application Support/postmaster (macOS).\n"; +/// Help text for the `cleanup` subcommand. pub const HELP_CLEANUP: &str = "postmaster cleanup — remove secret files from secrets_dir\n\n\ USAGE:\n \ postmaster cleanup --config \n\n\ @@ -176,13 +199,16 @@ Safe to run even if the directory is already empty or does not exist.\n\n\ OPTIONS:\n \ --config Exec config JSON (required)\n"; +/// Short usage string for error messages. pub const USAGE: &str = "usage: postmaster --config [--bind] [--allow-nonroot]\n postmaster fetch \n postmaster exec --config [--check] [--verify-keys]\n postmaster exec --config [--verify-keys] -- [args…]\n postmaster setup --config [--recheck] [--unattended] [--force] [--keys-dir ]\n postmaster cleanup --config "; -/// Parse command line arguments. Kept simple with no external deps. +/// Parse command-line arguments from `std::env::args()`. pub fn parse_args() -> Result { parse_args_from(std::env::args().skip(1)) } +/// Parse command-line arguments from a provided iterator. Kept simple +/// with no external dependencies (no clap). pub fn parse_args_from(args: impl IntoIterator) -> Result { let mut it = args.into_iter().peekable(); @@ -364,241 +390,9 @@ pub fn parse_args_from(args: impl IntoIterator) -> Result, - /// Encrypted env files, in precedence order (first wins unless overload). - #[serde(default)] - pub env_files: Vec, - /// Encrypted `postmaster_bundle` files, in precedence order. - /// Each file is a JSON container with `format: "postmaster.bundle"`. - /// Entries are merged with `env_files` entries; bundle keys use the - /// same identifier rule and the same injection modes. - #[serde(default)] - pub bundle_files: Vec, - /// Any undecryptable value aborts before exec (fail closed). - #[serde(default = "default_true")] - pub strict: bool, - /// File values override process env; later files override earlier. - #[serde(default)] - pub overload: bool, - /// files/credentials(darwin) mode: where plaintext files land. - #[serde(default)] - pub secrets_dir: Option, - /// files mode: keys ALSO exported as real env vars. - #[serde(default)] - pub passthrough: Vec, - /// credentials mode: keys exposed as $CREDENTIALS_DIRECTORY/. - #[serde(default)] - pub credential_keys: Vec, - /// credentials mode, darwin: key → postmaster socket to fetch from. - /// Non-empty selects the fetch path; empty means systemd already - /// materialized the credentials. - #[serde(default)] - pub sockets: HashMap, - /// darwin: refuse to write plaintext unless this mount point is the - /// HFS ramdisk and secrets_dir is a directory we own. - #[serde(default)] - pub verify_ramdisk: Option, -} - -#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum ExecMode { - Env, - Files, - Credentials, -} - -/// Where the launcher's private keys come from. Selection contract: -/// `credential` is skippable (absent $CREDENTIALS_DIRECTORY or file ⇒ try -/// the next source); `file`/`keychain`/`environment` are terminal — once -/// reached, their failure is the launcher's failure (fail closed). -#[derive(Deserialize, Debug, Clone)] -#[serde(rename_all = "snake_case")] -pub enum KeySourceSpec { - Credential(String), - File(PathBuf), - Keychain(String), - Environment, -} - -impl ExecConfig { - /// Validate the public shape of an exec config without touching local - /// secret material, decrypting values, probing sockets, or inspecting the - /// host filesystem. This is the parser-authoritative `--check` contract - /// automation bindings can run in CI before deployment. - pub fn validate_shape(&self) -> Result<(), String> { - validate_key_sources(&self.keys)?; - validate_ident_list("passthrough", &self.passthrough)?; - validate_mode_irrelevant_fields(self)?; - validate_mode_required_fields(self)?; - Ok(()) - } -} - -fn validate_mode_required_fields(cfg: &ExecConfig) -> Result<(), String> { - match cfg.mode { - ExecMode::Env => { - validate_decrypting_mode(cfg, "env")?; - } - ExecMode::Files => { - validate_decrypting_mode(cfg, "files")?; - if cfg.secrets_dir.is_none() { - return Err("files mode requires secrets_dir".into()); - } - } - ExecMode::Credentials => { - if cfg.credential_keys.is_empty() { - return Err("credentials mode requires credential_keys".into()); - } - validate_ident_list("credential_keys", &cfg.credential_keys)?; - if !cfg.sockets.is_empty() { - if cfg.secrets_dir.is_none() { - return Err("credentials(fetch) mode requires secrets_dir".into()); - } - for key in &cfg.credential_keys { - if !cfg.sockets.contains_key(key) { - return Err(format!("{key}: no socket mapped in exec config")); - } - } - } - } - } - Ok(()) -} - -/// Reject fields that are irrelevant to the selected mode. This catches -/// binding bugs early — before any secret material transits — so a config -/// generator that accidentally includes `env_files` in a credentials-mode -/// config or `credential_keys` in an env-mode config fails at `--check` -/// rather than silently ignoring the stray field. Default/empty values -/// (empty vecs, `None`, `false`) are accepted since serde fills them in -/// even when the generator omits the field entirely. -fn validate_mode_irrelevant_fields(cfg: &ExecConfig) -> Result<(), String> { - match cfg.mode { - ExecMode::Env => { - if cfg.secrets_dir.is_some() { - return Err("env mode does not use secrets_dir".into()); - } - if !cfg.credential_keys.is_empty() { - return Err("env mode does not use credential_keys".into()); - } - if !cfg.sockets.is_empty() { - return Err("env mode does not use sockets".into()); - } - if cfg.verify_ramdisk.is_some() { - return Err("env mode does not use verify_ramdisk".into()); - } - if !cfg.passthrough.is_empty() { - return Err("env mode does not use passthrough".into()); - } - } - ExecMode::Files => { - if !cfg.credential_keys.is_empty() { - return Err("files mode does not use credential_keys".into()); - } - if !cfg.sockets.is_empty() { - return Err("files mode does not use sockets".into()); - } - } - ExecMode::Credentials => { - if !cfg.keys.is_empty() { - return Err( - "credentials mode does not use keys (key material lives on the daemon)".into(), - ); - } - if !cfg.env_files.is_empty() { - return Err( - "credentials mode does not use env_files (ciphertext lives on the daemon)" - .into(), - ); - } - if !cfg.bundle_files.is_empty() { - return Err( - "credentials mode does not use bundle_files (ciphertext lives on the daemon)" - .into(), - ); - } - if cfg.overload { - return Err("credentials mode does not use overload".into()); - } - if !cfg.passthrough.is_empty() { - return Err("credentials mode does not use passthrough".into()); - } - } - } - Ok(()) -} - -fn validate_decrypting_mode(cfg: &ExecConfig, mode: &str) -> Result<(), String> { - if cfg.env_files.is_empty() && cfg.bundle_files.is_empty() { - return Err(format!( - "{mode} mode requires env_files or bundle_files (at least one non-empty)" - )); - } - if cfg.keys.is_empty() { - return Err(format!("{mode} mode requires keys")); - } - for path in &cfg.env_files { - KeyNaming::Env.key_var_for(path)?; - } - Ok(()) -} - -fn validate_key_sources(specs: &[KeySourceSpec]) -> Result<(), String> { - for spec in specs { - match spec { - KeySourceSpec::Credential(name) => validate_credential_source_name(name)?, - KeySourceSpec::File(path) if path.starts_with("/nix/store") => { - return Err(format!( - "{}: refusing plaintext private keys from the world-readable Nix store", - path.display() - )); - } - _ => {} - } - } - Ok(()) -} - -fn validate_credential_source_name(name: &str) -> Result<(), String> { - if name.contains('\0') { - return Err(format!( - "credential source {name:?}: contains NUL byte (not a valid path component)" - )); - } - let mut components = Path::new(name).components(); - match (components.next(), components.next()) { - (Some(Component::Normal(_)), None) => Ok(()), - _ => Err(format!( - "credential source {name:?}: must be a single relative path component" - )), - } -} - -fn validate_ident_list(field: &str, keys: &[String]) -> Result<(), String> { - for key in keys { - if !crate::keys::is_ident(key) { - return Err(format!("{field} entry {key:?}: not a valid identifier")); - } - } - Ok(()) -} - -fn default_true() -> bool { - true -} - #[cfg(test)] #[allow(unused_qualifications, clippy::panic, clippy::unwrap_used)] +/// Tests for CLI argument parsing. mod tests { use super::*; @@ -780,149 +574,4 @@ mod tests { Ok(Invocation::Help(Some(s))) if s == "cleanup" )); } - - #[test] - fn key_var_for_edge_cases() { - assert!( - KeyNaming::Env - .key_var_for(std::path::Path::new("no-dot-env")) - .is_err() - ); - } - - #[test] - fn exec_config_parses() { - let json = r#"{ - "mode": "files", - "keys": [{"credential": "postmaster-myapp"}, "environment"], - "env_files": ["/nix/store/x/.env.production"], - "strict": true, - "overload": false, - "secrets_dir": "/run/postmaster", - "passthrough": ["RUST_LOG"] - }"#; - let c: ExecConfig = serde_json::from_str(json).unwrap(); - assert!(matches!(c.mode, ExecMode::Files)); - assert_eq!(c.keys.len(), 2); - assert!(matches!(c.keys[1], KeySourceSpec::Environment)); - assert!(c.strict && !c.overload); - assert!(c.sockets.is_empty() && c.verify_ramdisk.is_none()); - } - - #[test] - fn exec_config_minimal_credentials() { - let json = r#"{"mode":"credentials","credential_keys":["DB_URL"]}"#; - let c: ExecConfig = serde_json::from_str(json).unwrap(); - assert!(matches!(c.mode, ExecMode::Credentials)); - assert!(c.strict, "strict must default to true"); - assert_eq!(c.credential_keys, vec!["DB_URL"]); - c.validate_shape().unwrap(); - } - - #[test] - fn exec_config_rejects_unknown_fields() { - let json = r#"{"mode":"credentials","credential_keys":["DB_URL"],"adapter":"dotenvx"}"#; - let err = serde_json::from_str::(json).unwrap_err(); - assert!( - err.to_string().contains("unknown field"), - "unexpected error: {err}" - ); - } - - #[test] - fn exec_config_validate_shape_catches_mode_requirements() { - let files_missing_dir: ExecConfig = serde_json::from_str( - r#"{"mode":"files","keys":["environment"],"env_files":["/nix/store/x/.env"]}"#, - ) - .unwrap(); - assert!( - files_missing_dir - .validate_shape() - .unwrap_err() - .contains("secrets_dir") - ); - - let invalid_credential_key: ExecConfig = - serde_json::from_str(r#"{"mode":"credentials","credential_keys":["../DB_URL"]}"#) - .unwrap(); - assert!( - invalid_credential_key - .validate_shape() - .unwrap_err() - .contains("identifier") - ); - - let store_key: ExecConfig = serde_json::from_str( - r#"{"mode":"env","keys":[{"file":"/nix/store/abc/.env.keys"}],"env_files":["/nix/store/x/.env"]}"#, - ) - .unwrap(); - assert!( - store_key - .validate_shape() - .unwrap_err() - .contains("Nix store") - ); - } - - #[test] - fn validate_shape_rejects_mode_irrelevant_fields() { - // env mode should reject secrets_dir, credential_keys, sockets, - // verify_ramdisk, and passthrough. - let env_with_secrets_dir: ExecConfig = serde_json::from_str( - r#"{"mode":"env","keys":["environment"],"env_files":["/nix/store/x/.env"],"secrets_dir":"/run/x"}"#, - ) - .unwrap(); - assert!( - env_with_secrets_dir - .validate_shape() - .unwrap_err() - .contains("env mode does not use secrets_dir") - ); - - let env_with_credential_keys: ExecConfig = serde_json::from_str( - r#"{"mode":"env","keys":["environment"],"env_files":["/nix/store/x/.env"],"credential_keys":["DB"]}"#, - ) - .unwrap(); - assert!( - env_with_credential_keys - .validate_shape() - .unwrap_err() - .contains("env mode does not use credential_keys") - ); - - // files mode should reject credential_keys and sockets. - let files_with_sockets: ExecConfig = serde_json::from_str( - r#"{"mode":"files","keys":["environment"],"env_files":["/nix/store/x/.env"],"secrets_dir":"/run/x","sockets":{"DB":"/s.sock"}}"#, - ) - .unwrap(); - assert!( - files_with_sockets - .validate_shape() - .unwrap_err() - .contains("files mode does not use sockets") - ); - - // credentials mode should reject keys, env_files, overload, passthrough. - let creds_with_env_files: ExecConfig = serde_json::from_str( - r#"{"mode":"credentials","credential_keys":["DB"],"env_files":["/nix/store/x/.env"]}"#, - ) - .unwrap(); - assert!( - creds_with_env_files - .validate_shape() - .unwrap_err() - .contains("credentials mode does not use env_files") - ); - - let creds_with_overload: ExecConfig = serde_json::from_str( - r#"{"mode":"credentials","credential_keys":["DB"],"overload":true}"#, - ) - .unwrap(); - assert!( - creds_with_overload - .validate_shape() - .unwrap_err() - .contains("credentials mode does not use overload") - ); - } } diff --git a/src/exec_config.rs b/src/exec_config.rs new file mode 100644 index 0000000..4f53ed7 --- /dev/null +++ b/src/exec_config.rs @@ -0,0 +1,408 @@ +//! Exec configuration — the `exec.json` data model and validation. +//! +//! This module defines the cross-binding contract for `postmaster exec`: +//! the `ExecConfig` struct, `ExecMode` enum, `KeySourceSpec` enum, and +//! all validation functions that check config shape without touching +//! local secret material or the host filesystem. + +use std::collections::HashMap; +use std::path::{Component, Path, PathBuf}; + +use serde::Deserialize; + +use crate::adapter::KeyNaming; + +/// Launcher configuration for `postmaster exec` — THE cross-binding +/// contract. Generated by the Nix module (later: other bindings); contains +/// only public data: store paths of ciphertext, key *names*, socket paths. +#[derive(Deserialize, Debug)] +#[serde(deny_unknown_fields)] +pub struct ExecConfig { + /// How resolved values are projected into the child process. + pub mode: ExecMode, + /// Ordered key sources; see launcher::load_ring for selection rules. + #[serde(default)] + pub keys: Vec, + /// Encrypted env files, in precedence order (first wins unless overload). + #[serde(default)] + pub env_files: Vec, + /// Encrypted `postmaster_bundle` files, in precedence order. + /// Each file is a JSON container with `format: "postmaster.bundle"`. + /// Entries are merged with `env_files` entries; bundle keys use the + /// same identifier rule and the same injection modes. + #[serde(default)] + pub bundle_files: Vec, + /// Any undecryptable value aborts before exec (fail closed). + #[serde(default = "default_true")] + pub strict: bool, + /// File values override process env; later files override earlier. + #[serde(default)] + pub overload: bool, + /// files/credentials(darwin) mode: where plaintext files land. + #[serde(default)] + pub secrets_dir: Option, + /// files mode: keys ALSO exported as real env vars. + #[serde(default)] + pub passthrough: Vec, + /// credentials mode: keys exposed as $CREDENTIALS_DIRECTORY/. + #[serde(default)] + pub credential_keys: Vec, + /// credentials mode, darwin: key → postmaster socket to fetch from. + /// Non-empty selects the fetch path; empty means systemd already + /// materialized the credentials. + #[serde(default)] + pub sockets: HashMap, + /// darwin: refuse to write plaintext unless this mount point is the + /// HFS ramdisk and secrets_dir is a directory we own. + #[serde(default)] + pub verify_ramdisk: Option, +} + +/// How resolved secret values are projected into the child process. +#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ExecMode { + /// Export all resolved values as environment variables. + Env, + /// Write each resolved value as a file under `secrets_dir`. + Files, + /// systemd credentials: export `_FILE` pointers into + /// `$CREDENTIALS_DIRECTORY`. + Credentials, +} + +/// Where the launcher's private keys come from. Selection contract: +/// `credential` is skippable (absent $CREDENTIALS_DIRECTORY or file ⇒ try +/// the next source); `file`/`keychain`/`environment` are terminal — once +/// reached, their failure is the launcher's failure (fail closed). +#[derive(Deserialize, Debug, Clone)] +#[serde(rename_all = "snake_case")] +pub enum KeySourceSpec { + /// Read from `$CREDENTIALS_DIRECTORY/` (systemd LoadCredential). + Credential(String), + /// Read from a local file path (must not be in the Nix store). + File(PathBuf), + /// Read from macOS Keychain (terminal, macOS only). + Keychain(String), + /// Read `DOTENV_PRIVATE_KEY*` from the process environment. + Environment, +} + +impl ExecConfig { + /// Validate the public shape of an exec config without touching local + /// secret material, decrypting values, probing sockets, or inspecting the + /// host filesystem. This is the parser-authoritative `--check` contract + /// automation bindings can run in CI before deployment. + pub fn validate_shape(&self) -> Result<(), String> { + validate_key_sources(&self.keys)?; + validate_ident_list("passthrough", &self.passthrough)?; + validate_mode_irrelevant_fields(self)?; + validate_mode_required_fields(self)?; + Ok(()) + } +} + +fn validate_mode_required_fields(cfg: &ExecConfig) -> Result<(), String> { + match cfg.mode { + ExecMode::Env => { + validate_decrypting_mode(cfg, "env")?; + } + ExecMode::Files => { + validate_decrypting_mode(cfg, "files")?; + if cfg.secrets_dir.is_none() { + return Err("files mode requires secrets_dir".into()); + } + } + ExecMode::Credentials => { + if cfg.credential_keys.is_empty() { + return Err("credentials mode requires credential_keys".into()); + } + validate_ident_list("credential_keys", &cfg.credential_keys)?; + if !cfg.sockets.is_empty() { + if cfg.secrets_dir.is_none() { + return Err("credentials(fetch) mode requires secrets_dir".into()); + } + for key in &cfg.credential_keys { + if !cfg.sockets.contains_key(key) { + return Err(format!("{key}: no socket mapped in exec config")); + } + } + } + } + } + Ok(()) +} + +/// Reject fields that are irrelevant to the selected mode. This catches +/// binding bugs early — before any secret material transits — so a config +/// generator that accidentally includes `env_files` in a credentials-mode +/// config or `credential_keys` in an env-mode config fails at `--check` +/// rather than silently ignoring the stray field. Default/empty values +/// (empty vecs, `None`, `false`) are accepted since serde fills them in +/// even when the generator omits the field entirely. +fn validate_mode_irrelevant_fields(cfg: &ExecConfig) -> Result<(), String> { + match cfg.mode { + ExecMode::Env => { + if cfg.secrets_dir.is_some() { + return Err("env mode does not use secrets_dir".into()); + } + if !cfg.credential_keys.is_empty() { + return Err("env mode does not use credential_keys".into()); + } + if !cfg.sockets.is_empty() { + return Err("env mode does not use sockets".into()); + } + if cfg.verify_ramdisk.is_some() { + return Err("env mode does not use verify_ramdisk".into()); + } + if !cfg.passthrough.is_empty() { + return Err("env mode does not use passthrough".into()); + } + } + ExecMode::Files => { + if !cfg.credential_keys.is_empty() { + return Err("files mode does not use credential_keys".into()); + } + if !cfg.sockets.is_empty() { + return Err("files mode does not use sockets".into()); + } + } + ExecMode::Credentials => { + if !cfg.keys.is_empty() { + return Err( + "credentials mode does not use keys (key material lives on the daemon)".into(), + ); + } + if !cfg.env_files.is_empty() { + return Err( + "credentials mode does not use env_files (ciphertext lives on the daemon)" + .into(), + ); + } + if !cfg.bundle_files.is_empty() { + return Err( + "credentials mode does not use bundle_files (ciphertext lives on the daemon)" + .into(), + ); + } + if cfg.overload { + return Err("credentials mode does not use overload".into()); + } + if !cfg.passthrough.is_empty() { + return Err("credentials mode does not use passthrough".into()); + } + } + } + Ok(()) +} + +fn validate_decrypting_mode(cfg: &ExecConfig, mode: &str) -> Result<(), String> { + if cfg.env_files.is_empty() && cfg.bundle_files.is_empty() { + return Err(format!( + "{mode} mode requires env_files or bundle_files (at least one non-empty)" + )); + } + if cfg.keys.is_empty() { + return Err(format!("{mode} mode requires keys")); + } + for path in &cfg.env_files { + KeyNaming::Env.key_var_for(path)?; + } + Ok(()) +} + +fn validate_key_sources(specs: &[KeySourceSpec]) -> Result<(), String> { + for spec in specs { + match spec { + KeySourceSpec::Credential(name) => validate_credential_source_name(name)?, + KeySourceSpec::File(path) if path.starts_with("/nix/store") => { + return Err(format!( + "{}: refusing plaintext private keys from the world-readable Nix store", + path.display() + )); + } + _ => {} + } + } + Ok(()) +} + +pub(crate) fn validate_credential_source_name(name: &str) -> Result<(), String> { + if name.contains('\0') { + return Err(format!( + "credential source {name:?}: contains NUL byte (not a valid path component)" + )); + } + let mut components = Path::new(name).components(); + match (components.next(), components.next()) { + (Some(Component::Normal(_)), None) => Ok(()), + _ => Err(format!( + "credential source {name:?}: must be a single relative path component" + )), + } +} + +fn validate_ident_list(field: &str, keys: &[String]) -> Result<(), String> { + for key in keys { + if !crate::keys::is_ident(key) { + return Err(format!("{field} entry {key:?}: not a valid identifier")); + } + } + Ok(()) +} + +fn default_true() -> bool { + true +} + +#[cfg(test)] +#[allow(unused_qualifications, clippy::panic, clippy::unwrap_used)] +/// Tests for exec config parsing and validation. +mod tests { + use super::*; + + #[test] + fn key_var_for_edge_cases() { + assert!( + KeyNaming::Env + .key_var_for(std::path::Path::new("no-dot-env")) + .is_err() + ); + } + + #[test] + fn exec_config_parses() { + let json = r#"{ + "mode": "files", + "keys": [{"credential": "postmaster-myapp"}, "environment"], + "env_files": ["/nix/store/x/.env.production"], + "strict": true, + "overload": false, + "secrets_dir": "/run/postmaster", + "passthrough": ["RUST_LOG"] + }"#; + let c: ExecConfig = serde_json::from_str(json).unwrap(); + assert!(matches!(c.mode, ExecMode::Files)); + assert_eq!(c.keys.len(), 2); + assert!(matches!(c.keys[1], KeySourceSpec::Environment)); + assert!(c.strict && !c.overload); + assert!(c.sockets.is_empty() && c.verify_ramdisk.is_none()); + } + + #[test] + fn exec_config_minimal_credentials() { + let json = r#"{"mode":"credentials","credential_keys":["DB_URL"]}"#; + let c: ExecConfig = serde_json::from_str(json).unwrap(); + assert!(matches!(c.mode, ExecMode::Credentials)); + assert!(c.strict, "strict must default to true"); + + c.validate_shape().unwrap(); + } + + #[test] + fn exec_config_rejects_unknown_fields() { + let json = r#"{"mode":"credentials","credential_keys":["DB_URL"],"adapter":"dotenvx"}"#; + let err = serde_json::from_str::(json).unwrap_err(); + assert!( + err.to_string().contains("unknown field"), + "unexpected error: {err}" + ); + } + + #[test] + fn exec_config_validate_shape_catches_mode_requirements() { + let files_missing_dir: ExecConfig = serde_json::from_str( + r#"{"mode":"files","keys":["environment"],"env_files":["/nix/store/x/.env"]}"#, + ) + .unwrap(); + assert!( + files_missing_dir + .validate_shape() + .unwrap_err() + .contains("secrets_dir") + ); + + let invalid_credential_key: ExecConfig = + serde_json::from_str(r#"{"mode":"credentials","credential_keys":["../DB_URL"]}"#) + .unwrap(); + assert!( + invalid_credential_key + .validate_shape() + .unwrap_err() + .contains("identifier") + ); + + let store_key: ExecConfig = serde_json::from_str( + r#"{"mode":"env","keys":[{"file":"/nix/store/abc/.env.keys"}],"env_files":["/nix/store/x/.env"]}"#, + ) + .unwrap(); + assert!( + store_key + .validate_shape() + .unwrap_err() + .contains("Nix store") + ); + } + + #[test] + fn validate_shape_rejects_mode_irrelevant_fields() { + // env mode should reject secrets_dir, credential_keys, sockets, + // verify_ramdisk, and passthrough. + let env_with_secrets_dir: ExecConfig = serde_json::from_str( + r#"{"mode":"env","keys":["environment"],"env_files":["/nix/store/x/.env"],"secrets_dir":"/run/x"}"#, + ) + .unwrap(); + assert!( + env_with_secrets_dir + .validate_shape() + .unwrap_err() + .contains("env mode does not use secrets_dir") + ); + + let env_with_credential_keys: ExecConfig = serde_json::from_str( + r#"{"mode":"env","keys":["environment"],"env_files":["/nix/store/x/.env"],"credential_keys":["DB"]}"#, + ) + .unwrap(); + assert!( + env_with_credential_keys + .validate_shape() + .unwrap_err() + .contains("env mode does not use credential_keys") + ); + + // files mode should reject credential_keys and sockets. + let files_with_sockets: ExecConfig = serde_json::from_str( + r#"{"mode":"files","keys":["environment"],"env_files":["/nix/store/x/.env"],"secrets_dir":"/run/x","sockets":{"DB":"/s.sock"}}"#, + ) + .unwrap(); + assert!( + files_with_sockets + .validate_shape() + .unwrap_err() + .contains("files mode does not use sockets") + ); + + // credentials mode should reject keys, env_files, overload, passthrough. + let creds_with_env_files: ExecConfig = serde_json::from_str( + r#"{"mode":"credentials","credential_keys":["DB"],"env_files":["/nix/store/x/.env"]}"#, + ) + .unwrap(); + assert!( + creds_with_env_files + .validate_shape() + .unwrap_err() + .contains("credentials mode does not use env_files") + ); + + let creds_with_overload: ExecConfig = serde_json::from_str( + r#"{"mode":"credentials","credential_keys":["DB"],"overload":true}"#, + ) + .unwrap(); + assert!( + creds_with_overload + .validate_shape() + .unwrap_err() + .contains("credentials mode does not use overload") + ); + } +} diff --git a/src/key_provisioning.rs b/src/key_provisioning.rs new file mode 100644 index 0000000..888d541 --- /dev/null +++ b/src/key_provisioning.rs @@ -0,0 +1,657 @@ +//! Key provisioning — setup and verification of key sources, key +//! directory creation, keychain seeding, and runtime key source checks. +//! +//! This module implements the `postmaster setup` and `postmaster cleanup` +//! commands, plus the key-provisioning helpers they depend on. + +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; + +use crate::adapter::KeyNaming; +use crate::exec_config::{ExecConfig, KeySourceSpec}; +use crate::server::log; + +/// Default keys directory path: `/var/lib/postmaster` on Linux, +/// `~/Library/Application Support/postmaster` on macOS. +fn default_keys_dir() -> PathBuf { + #[cfg(target_os = "macos")] + { + if let Some(home) = std::env::var_os("HOME") { + return PathBuf::from(home) + .join("Library") + .join("Application Support") + .join("postmaster"); + } + } + PathBuf::from("/var/lib/postmaster") +} + +/// Create the keys directory with 0700 permissions if it doesn't exist. +/// If it exists, verify permissions and ownership are correct. Idempotent +/// — skips if already correct unless `force` is true. +#[allow(clippy::print_stderr)] +fn ensure_keys_dir(keys_dir: &Path, _force: bool) -> Result<(), String> { + if keys_dir.exists() { + // Open the directory itself and work on the fd throughout: + // O_DIRECTORY|O_NOFOLLOW rejects symlinks and non-directories at + // open, and fchmod on the fd eliminates the TOCTOU between a + // path-based check and a path-based chmod (audit 2026-08-02 A5). + let dir_fd = rustix::fs::open( + keys_dir, + rustix::fs::OFlags::RDONLY + | rustix::fs::OFlags::DIRECTORY + | rustix::fs::OFlags::NOFOLLOW + | rustix::fs::OFlags::CLOEXEC, + rustix::fs::Mode::empty(), + ) + .map_err(|e| { + format!( + "{}: cannot open keys directory: {e} (refusing a symlink or non-directory)", + keys_dir.display() + ) + })?; + let stat = rustix::fs::fstat(&dir_fd) + .map_err(|e| format!("{}: fstat: {e}", keys_dir.display()))?; + let mode = rustix::fs::Mode::from_bits_truncate(stat.st_mode); + if mode.intersects(rustix::fs::Mode::RWXG | rustix::fs::Mode::RWXO) { + // Fix permissions if we can + rustix::fs::fchmod(&dir_fd, rustix::fs::Mode::RWXU) + .map_err(|e| format!("{}: cannot fix permissions: {e}", keys_dir.display()))?; + log(&format!( + "{}: permissions corrected to 0700", + keys_dir.display() + )); + } + log(&format!("{}: keys directory verified", keys_dir.display())); + return Ok(()); + } + + // Create the directory with 0700. create_dir_all follows intermediate + // symlinks, so first reject any existing symlink component in the + // prefix (audit 2026-08-02 O5). Residual TOCTOU: a component could be + // swapped between this check and the create, but an attacker with + // that write access could plant the symlink outright — and the open + // below is still NOFOLLOW on the final component. + let mut prefix = PathBuf::new(); + for comp in keys_dir.components() { + prefix.push(comp); + if let Ok(md) = fs::symlink_metadata(&prefix) + && md.file_type().is_symlink() + { + return Err(format!( + "{}: refusing to create keys directory through a symlinked component", + prefix.display() + )); + } + } + fs::create_dir_all(keys_dir) + .map_err(|e| format!("{}: cannot create keys directory: {e}", keys_dir.display()))?; + let dir_fd = rustix::fs::open( + keys_dir, + rustix::fs::OFlags::RDONLY + | rustix::fs::OFlags::DIRECTORY + | rustix::fs::OFlags::NOFOLLOW + | rustix::fs::OFlags::CLOEXEC, + rustix::fs::Mode::empty(), + ) + .map_err(|e| format!("{}: cannot open keys directory: {e}", keys_dir.display()))?; + rustix::fs::fchmod(&dir_fd, rustix::fs::Mode::RWXU) + .map_err(|e| format!("{}: cannot set permissions: {e}", keys_dir.display()))?; + log(&format!( + "{}: keys directory created with 0700", + keys_dir.display() + )); + Ok(()) +} + +/// Verify a keys file exists with correct permissions (0600, owned by +/// euid). If the file doesn't exist, in interactive mode, prompt the +/// operator to create it. In unattended mode, fail closed. If the file +/// exists but has wrong permissions, fix them. +#[allow(clippy::print_stderr)] +fn ensure_keys_file(path: &Path, _force: bool, unattended: bool) -> Result<(), String> { + if path.exists() { + // Verify permissions and ownership (same checks as setup_recheck) + let oflags = + rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC; + let fd = rustix::fs::open(path, oflags, rustix::fs::Mode::empty()) + .map_err(|e| format!("{}: {e} (refusing to follow a symlink)", path.display()))?; + let stat = rustix::fs::fstat(&fd).map_err(|e| format!("{}: fstat: {e}", path.display()))?; + let mode = rustix::fs::Mode::from_bits_truncate(stat.st_mode); + if mode.intersects(rustix::fs::Mode::RWXG | rustix::fs::Mode::RWXO) { + // Fix permissions + rustix::fs::fchmod(&fd, rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR) + .map_err(|e| format!("{}: cannot fix permissions: {e}", path.display()))?; + log(&format!( + "{}: permissions corrected to 0600", + path.display() + )); + } + let euid = rustix::process::geteuid().as_raw(); + if stat.st_uid != euid { + return Err(format!( + "{}: owned by uid {} but postmaster euid is {euid} (cannot fix ownership automatically)", + path.display(), + stat.st_uid + )); + } + log(&format!("{}: keys file verified", path.display())); + return Ok(()); + } + + // File doesn't exist + if unattended { + return Err(format!( + "{}: keys file not found (unattended mode — cannot prompt; create the file manually before running setup)", + path.display() + )); + } + + // Interactive: prompt the operator + eprintln!("{}: keys file not found.", path.display()); + eprintln!( + "Create it now? You will need to paste the key contents (DOTENV_PRIVATE_KEY=<64-hex>...). [y/N] " + ); + let mut input = String::new(); + if std::io::stdin().read_line(&mut input).is_err() { + return Err(format!("{}: cannot read input", path.display())); + } + if !input.trim().eq_ignore_ascii_case("y") { + return Err(format!( + "{}: operator declined to create keys file", + path.display() + )); + } + + eprintln!("Paste the keys file contents (Ctrl+D to finish):"); + // Zeroizing: operator-pasted key material must not linger in freed + // heap pages (audit 2026-08-02 O4). + let mut contents = zeroize::Zeroizing::new(String::new()); + if std::io::stdin().read_to_string(&mut contents).is_err() { + return Err(format!("{}: cannot read key contents", path.display())); + } + + // Write the file with 0600. O_EXCL | O_NOFOLLOW makes creation + // fail-closed: it refuses to overwrite anything already at the path + // and refuses to follow a planted symlink. + let oflags = rustix::fs::OFlags::WRONLY + | rustix::fs::OFlags::CREATE + | rustix::fs::OFlags::EXCL + | rustix::fs::OFlags::NOFOLLOW + | rustix::fs::OFlags::CLOEXEC; + let fd = rustix::fs::open(path, oflags, rustix::fs::Mode::from_bits_truncate(0o600)).map_err( + |e| { + format!( + "{}: cannot create: {e} (refusing to overwrite or follow a symlink)", + path.display() + ) + }, + )?; + let mut file = fs::File::from(fd); + use std::io::Write; + file.write_all(contents.as_bytes()) + .map_err(|e| format!("{}: cannot write: {e}", path.display()))?; + log(&format!("{}: keys file created with 0600", path.display())); + Ok(()) +} + +/// Verify keychain items exist for the wanted key variables. If they +/// don't exist and we're in interactive mode, offer to seed them. +/// On macOS only. +#[cfg(target_os = "macos")] +#[allow(clippy::print_stderr)] +fn ensure_keychain_items( + service: &str, + wanted: &[String], + force: bool, + unattended: bool, +) -> Result<(), String> { + let mut missing: Vec<&str> = Vec::new(); + for var in wanted { + // Existence check via the Security.framework API (F1) — no + // subprocess; retrieved bytes zeroized on drop (A17). + match security_framework::passwords::get_generic_password(service, var) { + Ok(bytes) => { + let _ = zeroize::Zeroizing::new(bytes); // zeroize on drop + } + Err(_) => missing.push(var), + } + } + + if missing.is_empty() && !force { + log(&format!( + "keychain {service}: all {wanted_len} item(s) verified", + wanted_len = wanted.len() + )); + return Ok(()); + } + + if unattended && !missing.is_empty() { + return Err(format!( + "keychain {service}: {missing_len} item(s) missing (unattended mode — cannot prompt)", + missing_len = missing.len() + )); + } + + // Interactive: offer to seed missing items + if !missing.is_empty() { + eprintln!( + "keychain {service}: missing items for: {}", + missing.join(", ") + ); + eprintln!("Seed them now? You will need to paste each key value. [y/N] "); + let mut input = String::new(); + if std::io::stdin().read_line(&mut input).is_err() { + return Err("cannot read input".into()); + } + if !input.trim().eq_ignore_ascii_case("y") { + return Err(format!( + "keychain {service}: operator declined to seed missing items" + )); + } + + for var in &missing { + eprint!("Paste value for {var}: "); + // Zeroizing: pasted key material must not linger in freed + // heap pages (audit 2026-08-02 O4). `trim()` borrows, no copy. + let mut value = zeroize::Zeroizing::new(String::new()); + if std::io::stdin().read_line(&mut value).is_err() { + return Err(format!("cannot read value for {var}")); + } + let value = value.trim(); + if value.is_empty() { + return Err(format!("{var}: empty value, refusing to seed")); + } + // Seed via the Security.framework API, not the security CLI: + // `add-generic-password -w ` exposes key material in + // the subprocess argv, readable by any local process via ps / + // proc_pidinfo (audit 2026-08-02 O3; F1 crate direction). + security_framework::passwords::set_generic_password(service, var, value.as_bytes()) + .map_err(|e| format!("keychain {service}: failed to seed {var}: {e}"))?; + log(&format!("keychain {service}: seeded {var}")); + } + } + + Ok(()) +} + +/// Verify that all configured key sources are accessible. This is the +/// `--recheck` path — same as the old `setup_recheck` function. +fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> { + // `wanted` is only consulted by the macOS keychain check below. + #[cfg(not(target_os = "macos"))] + let _ = wanted; + let mut checked = 0_u32; + let mut found = 0_u32; + + for spec in &cfg.keys { + match spec { + KeySourceSpec::Credential(name) => { + checked += 1; + let dir = std::env::var_os("CREDENTIALS_DIRECTORY") + .ok_or("$CREDENTIALS_DIRECTORY is not set")?; + let p = Path::new(&dir).join(name); + if !p.exists() { + return Err(format!( + "{}: credential source not found under $CREDENTIALS_DIRECTORY", + p.display() + )); + } + found += 1; + } + KeySourceSpec::File(path) => { + checked += 1; + if path.starts_with("/nix/store") { + return Err(format!( + "{}: refusing plaintext private keys from the world-readable Nix store", + path.display() + )); + } + let oflags = rustix::fs::OFlags::RDONLY + | rustix::fs::OFlags::NOFOLLOW + | rustix::fs::OFlags::CLOEXEC; + let fd = + rustix::fs::open(path, oflags, rustix::fs::Mode::empty()).map_err(|e| { + format!("{}: {e} (refusing to follow a symlink)", path.display()) + })?; + let stat = rustix::fs::fstat(&fd) + .map_err(|e| format!("{}: fstat: {e}", path.display()))?; + let mode = rustix::fs::Mode::from_bits_truncate(stat.st_mode); + if mode.intersects(rustix::fs::Mode::RWXG | rustix::fs::Mode::RWXO) { + return Err(format!( + "{}: permissions {:#o} are group/world accessible; expected 0400 or 0600", + path.display(), + stat.st_mode + )); + } + let euid = rustix::process::geteuid().as_raw(); + if stat.st_uid != euid { + return Err(format!( + "{}: owned by uid {} but postmaster euid is {euid}", + path.display(), + stat.st_uid + )); + } + found += 1; + } + KeySourceSpec::Keychain(service) => { + #[cfg(target_os = "macos")] + { + checked += 1; + for var in wanted { + // Security.framework API (F1) — no subprocess; + // retrieved bytes zeroized on drop (A17). + match security_framework::passwords::get_generic_password(service, var) { + Ok(bytes) => { + let _ = zeroize::Zeroizing::new(bytes); // zeroize on drop + } + Err(_) => { + return Err(format!( + "keychain {service}: no item for account {var} (fail closed)" + )); + } + } + } + found += 1; + } + #[cfg(not(target_os = "macos"))] + { + let _ = service; + return Err("keychain source is only available on macOS".into()); + } + } + KeySourceSpec::Environment => { + checked += 1; + let env_prefix = KeyNaming::Env.key_prefix(); + let bundle_prefix = KeyNaming::Bundle.key_prefix(); + let has_key = std::env::vars() + .any(|(k, _)| k.starts_with(env_prefix) || k.starts_with(bundle_prefix)); + if !has_key { + return Err(format!( + "environment: no {env_prefix}* or {bundle_prefix}* variables set" + )); + } + found += 1; + } + } + } + + if checked == 0 { + return Err("no key sources configured (configure keys=[…])".into()); + } + + log(&format!( + "setup: {found}/{checked} key source(s) verified — environment ready" + )); + Ok(()) +} + +/// `postmaster setup`: verify platform prerequisites, create keys +/// directory with correct permissions, optionally seed keychain items, +/// and validate the environment. Idempotent — skips steps that are +/// already correct. +/// +/// `--recheck`: re-run verification checks only, without creating or +/// modifying anything. +/// +/// `--unattended`: non-interactive mode for automation. Uses defaults +/// or env vars instead of prompting. Fail closed on any missing +/// prerequisite. +/// +/// `--force`: re-seed or re-create even if the target state is already +/// present. +/// +/// `--keys-dir `: override the keys directory path. +pub fn setup( + config_path: &Path, + recheck: bool, + unattended: bool, + force: bool, + keys_dir_override: Option, +) -> Result<(), String> { + let cfg = crate::launcher::parse_exec_config(config_path)?; + cfg.validate_shape()?; + + // Build the wanted key variable list from both env and bundle files + let mut wanted: Vec = Vec::new(); + for f in &cfg.env_files { + wanted.push(KeyNaming::Env.key_var_for(f)?); + } + for f in &cfg.bundle_files { + wanted.push(KeyNaming::Bundle.key_var_for(f)?); + } + + if recheck { + // --recheck: verification only, no creation or modification + return verify_key_sources(&cfg, &wanted); + } + + // Step 1: Create or verify keys directory + let keys_dir = keys_dir_override.unwrap_or_else(default_keys_dir); + ensure_keys_dir(&keys_dir, force)?; + + // Step 2: Verify or create key files for file-source keys + for spec in &cfg.keys { + if let KeySourceSpec::File(path) = spec { + ensure_keys_file(path, force, unattended)?; + } + } + + // Step 3: Verify or seed keychain items (macOS only) + #[cfg(target_os = "macos")] + for spec in &cfg.keys { + if let KeySourceSpec::Keychain(service) = spec { + ensure_keychain_items(service, &wanted, force, unattended)?; + } + } + + // Step 4: Verify the full environment (same as --recheck) + verify_key_sources(&cfg, &wanted)?; + + log(&format!( + "setup: complete — keys dir {}, {} key source(s) verified", + keys_dir.display(), + cfg.keys.len() + )); + Ok(()) +} + +/// `postmaster cleanup`: remove all secret files from the secrets_dir +/// configured in the exec config. Intended for `ExecStopPost` in systemd +/// or equivalent lifecycle hooks. Does not decrypt — only removes files +/// that postmaster would have written. Safe to run even if the directory +/// is empty or does not exist. +pub fn cleanup(config_path: &Path) -> Result<(), String> { + let cfg = crate::launcher::parse_exec_config(config_path)?; + let dir = cfg + .secrets_dir + .as_deref() + .ok_or("cleanup: config has no secrets_dir — nothing to clean up")?; + // Refuse to bulk-delete in a directory that isn't clearly + // postmaster-managed (audit 2026-08-02 A19): in a symlinked or + // group/world-accessible dir these deletes could hit foreign files. + let md = match fs::symlink_metadata(dir) { + Ok(md) => md, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + log(&format!( + "cleanup: {} does not exist; nothing to clean up", + dir.display() + )); + return Ok(()); + } + Err(e) => return Err(format!("{}: cleanup: {e}", dir.display())), + }; + if md.file_type().is_symlink() || !md.is_dir() { + return Err(format!( + "{}: cleanup: refusing a symlinked or non-directory secrets dir", + dir.display() + )); + } + let entries = match fs::read_dir(dir) { + Ok(e) => e, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + log(&format!( + "cleanup: {} does not exist; nothing to clean up", + dir.display() + )); + return Ok(()); + } + Err(e) => return Err(format!("{}: cleanup: {e}", dir.display())), + }; + let entries: Vec> = entries.collect(); + if entries.is_empty() { + log(&format!( + "cleanup: {} is empty; nothing to clean up", + dir.display() + )); + return Ok(()); + } + // Managed-dir guard (audit 2026-08-02 A19): non-empty and no + // sentinel means postmaster never wrote here — bulk deletes could + // hit foreign files. Refuse. + match fs::symlink_metadata(dir.join(crate::secret_files::MANAGED_SENTINEL)) { + Ok(smd) if smd.is_file() => {} + _ => { + return Err(format!( + "{}: cleanup: no {} sentinel; refusing to bulk-delete in a directory postmaster did not write to", + dir.display(), + crate::secret_files::MANAGED_SENTINEL + )); + } + } + let mut removed = 0_usize; + for entry in entries { + let entry = match entry { + Ok(e) => e, + Err(e) => { + log(&format!( + "{}: cleanup: skip unreadable entry: {e}", + dir.display() + )); + continue; + } + }; + let path = entry.path(); + // The sentinel is infrastructure, not a secret — skipped here + // and removed last, so an interrupted cleanup can be re-run. + if entry.file_name().to_str() == Some(crate::secret_files::MANAGED_SENTINEL) { + continue; + } + match fs::symlink_metadata(&path) { + Ok(md) if md.is_file() => { + if let Err(e) = fs::remove_file(&path) { + log(&format!("{}: cleanup: {e}", path.display())); + } else { + removed += 1; + } + } + Ok(md) => { + log(&format!( + "{}: cleanup: skipping non-file (type {:?})", + path.display(), + md.file_type() + )); + } + Err(e) => { + log(&format!("{}: cleanup: stat: {e}", path.display())); + } + } + } + // Remove the sentinel last (see above). + let sentinel = dir.join(crate::secret_files::MANAGED_SENTINEL); + if let Err(e) = fs::remove_file(&sentinel) + && e.kind() != std::io::ErrorKind::NotFound + { + log(&format!("{}: cleanup: {e}", sentinel.display())); + } + log(&format!( + "cleanup: removed {removed} file(s) from {}", + dir.display() + )); + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic)] +mod tests { + use super::*; + + #[test] + fn cleanup_removes_all_files_from_secrets_dir() { + let dir = std::env::temp_dir().join(format!("pm-keyprov-cleanup-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + // cleanup requires a postmaster-managed (owner-only) dir + // (audit 2026-08-02 A19); match real deployments. + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); + fs::write(dir.join("KEY_A"), b"secret-a").unwrap(); + fs::write(dir.join("KEY_B"), b"secret-b").unwrap(); + fs::create_dir(dir.join("subdir")).unwrap(); + fs::write(dir.join(crate::secret_files::MANAGED_SENTINEL), b"").unwrap(); + + let cfg_path = dir.join("exec.json"); + fs::write( + &cfg_path, + format!( + r#"{{"mode":"files","keys":["environment"],"env_files":["/nonexistent"],"secrets_dir":"{}"}}"#, + dir.display() + ), + ) + .unwrap(); + + cleanup(&cfg_path).unwrap(); + + assert!(!dir.join("KEY_A").exists(), "KEY_A should be removed"); + assert!(!dir.join("KEY_B").exists(), "KEY_B should be removed"); + assert!(dir.join("subdir").exists(), "subdir should be preserved"); + assert!( + !dir.join(crate::secret_files::MANAGED_SENTINEL).exists(), + "sentinel is removed last" + ); + } + + #[test] + fn cleanup_refuses_unmanaged_dir() { + // audit 2026-08-02 A19: a non-empty dir without the sentinel was + // never written by postmaster; cleanup must refuse to bulk-delete + // there (foreign files could be present). + let dir = std::env::temp_dir().join(format!("pm-keyprov-unmanaged-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("FOREIGN"), b"not-ours").unwrap(); + let cfg_path = dir.join("exec.json"); + fs::write( + &cfg_path, + format!( + r#"{{"mode":"files","keys":["environment"],"env_files":["/nonexistent"],"secrets_dir":"{}"}}"#, + dir.display() + ), + ) + .unwrap(); + + let err = cleanup(&cfg_path).unwrap_err(); + + assert!(err.contains("sentinel"), "{err}"); + assert!(dir.join("FOREIGN").exists(), "nothing may be deleted"); + } + + #[test] + fn cleanup_nonexistent_dir_is_ok() { + let dir = std::env::temp_dir().join(format!("pm-keyprov-missing-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let cfg_path = dir.join("exec.json"); + fs::write( + &cfg_path, + format!( + r#"{{"mode":"files","keys":["environment"],"env_files":["/nonexistent"],"secrets_dir":"{}/no-such-dir"}}"#, + dir.display() + ), + ) + .unwrap(); + + assert!(cleanup(&cfg_path).is_ok()); + } +} diff --git a/src/key_source.rs b/src/key_source.rs new file mode 100644 index 0000000..8555975 --- /dev/null +++ b/src/key_source.rs @@ -0,0 +1,249 @@ +//! Key source selection — loads the private key ring from the first +//! available source per the exec config's ordered `keys` list. +//! +//! `credential` is skippable (absent `$CREDENTIALS_DIRECTORY` or file ⇒ +//! try the next source); every other source is terminal: once selected, +//! its failure fails the launcher. + +use std::fs; +use std::path::Path; + +use crate::adapter::KeyNaming; +use crate::exec_config::KeySourceSpec; +use crate::keys::KeyRing; + +/// Ordered key-source selection. `credential` is skippable (no +/// $CREDENTIALS_DIRECTORY or file absent ⇒ try next source); every other +/// source is terminal: once selected, its failure fails the launcher. +// `wanted_vars` is only consumed by the macOS keychain source; on other +// targets the parameter is unused, so silence that leg's clippy warning +// without touching the signature or source-selection semantics. +#[cfg_attr(not(target_os = "macos"), allow(unused_variables))] +pub fn load_ring(specs: &[KeySourceSpec], wanted_vars: &[String]) -> Result { + for spec in specs { + match spec { + KeySourceSpec::Credential(name) => { + if let Some(dir) = std::env::var_os("CREDENTIALS_DIRECTORY") { + let p = Path::new(&dir).join(name); + // Use symlink_metadata instead of p.exists(): exists() + // follows symlinks, so a planted symlink at + // $CREDENTIALS_DIRECTORY/ pointing to a + // world-readable file would be silently followed. + // Reject symlinks outright (audit finding #2); the + // subsequent KeyRing::load also opens with O_NOFOLLOW + // as defense-in-depth. + match fs::symlink_metadata(&p) { + Ok(md) if md.file_type().is_symlink() => { + return Err(format!( + "{}: credential source is a symlink; refusing to follow (remove the symlink)", + p.display() + )); + } + Ok(md) if md.is_file() => return KeyRing::load(&p, KeyNaming::Env), + Ok(_) => { + return Err(format!( + "{}: credential source is not a regular file", + p.display() + )); + } + Err(_) => { /* absent: fall through to next source */ } + } + } + // absent credential: fall through to the next source + } + KeySourceSpec::File(p) => { + if p.starts_with("/nix/store") { + return Err(format!( + "{}: refusing plaintext private keys from the world-readable Nix store", + p.display() + )); + } + return KeyRing::load(p, KeyNaming::Env); + } + KeySourceSpec::Keychain(service) => { + #[cfg(target_os = "macos")] + return KeyRing::from_keychain(service, wanted_vars, KeyNaming::Env); + #[cfg(not(target_os = "macos"))] + return Err(format!( + "key source keychain({service}) is only available on macOS" + )); + } + KeySourceSpec::Environment => return KeyRing::from_env(KeyNaming::Env), + } + } + Err("no usable key source (configure keys=[…] or set DOTENV_PRIVATE_KEY*)".into()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic, unused_qualifications)] +mod tests { + use super::*; + use crate::exec_config::KeySourceSpec; + + /// Serializes tests that mutate the process-global + /// `CREDENTIALS_DIRECTORY`. The test harness runs tests in parallel + /// threads of one process, so unsynchronized set_var/remove_var on + /// the same variable races (observed as a flaky failure of + /// `load_ring_credential_rejects_non_file`, 2026-08-04). + static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + #[test] + fn load_ring_credential_is_skippable() { + // credential source with no CREDENTIALS_DIRECTORY set should fall + // through to the next source. Here the next source is "environment", + // which is terminal and will fail closed (no DOTENV_PRIVATE_KEY* + // vars in the test runner). The error must be from the environment + // source, not from the credential source. + // + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized via ENV_LOCK against the other + // CREDENTIALS_DIRECTORY-mutating tests in this module. + let _guard = ENV_LOCK.lock().unwrap(); + unsafe { + std::env::remove_var("CREDENTIALS_DIRECTORY"); + } + let specs = vec![ + KeySourceSpec::Credential("nonexistent".to_string()), + KeySourceSpec::Environment, + ]; + let err = load_ring(&specs, &[]).unwrap_err(); + // The error should come from the environment source (terminal), + // proving credential fell through rather than erroring. + assert!( + err.contains("environment:") || err.contains("no usable key source"), + "credential should be skippable; got: {err}" + ); + } + + #[test] + fn load_ring_credential_rejects_symlink() { + // Audit finding #2: a symlink planted at + // $CREDENTIALS_DIRECTORY/ must be rejected, not followed. + use std::os::unix::fs::PermissionsExt; + let d = std::env::temp_dir().join(format!("pm-keysource-symlink-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + let real = d.join("real-keys"); + fs::write(&real, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); + fs::set_permissions(&real, fs::Permissions::from_mode(0o600)).unwrap(); + let cred_dir = d.join("creds"); + fs::create_dir_all(&cred_dir).unwrap(); + let link = cred_dir.join("dotenv-private-key"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized via ENV_LOCK against the other + // CREDENTIALS_DIRECTORY-mutating tests in this module. + let _guard = ENV_LOCK.lock().unwrap(); + unsafe { + std::env::set_var("CREDENTIALS_DIRECTORY", &cred_dir); + } + let specs = vec![KeySourceSpec::Credential("dotenv-private-key".to_string())]; + let err = load_ring(&specs, &[]).unwrap_err(); + unsafe { + std::env::remove_var("CREDENTIALS_DIRECTORY"); + } + assert!( + err.contains("symlink"), + "credential symlink should be rejected; got: {err}" + ); + } + + #[test] + fn load_ring_credential_rejects_non_file() { + // A directory as a credential source name should be rejected, + // not silently skipped or treated as a file. + let d = std::env::temp_dir().join(format!("pm-keysource-dir-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + let cred_dir = d.join("creds"); + fs::create_dir_all(&cred_dir).unwrap(); + let sub = cred_dir.join("subdir"); + fs::create_dir_all(&sub).unwrap(); + + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized via ENV_LOCK against the other + // CREDENTIALS_DIRECTORY-mutating tests in this module. + let _guard = ENV_LOCK.lock().unwrap(); + unsafe { + std::env::set_var("CREDENTIALS_DIRECTORY", &cred_dir); + } + let specs = vec![KeySourceSpec::Credential("subdir".to_string())]; + let err = load_ring(&specs, &[]).unwrap_err(); + unsafe { + std::env::remove_var("CREDENTIALS_DIRECTORY"); + } + assert!( + err.contains("not a regular file"), + "credential directory should be rejected; got: {err}" + ); + } + + #[test] + fn load_ring_file_is_terminal() { + // file source with a nonexistent path should return an error + // immediately, NOT fall through to the next source. We verify this + // by putting a valid "environment" source after the bad file source: + // if file were skippable, load_ring would try environment and fail + // with "environment:" — instead it must fail with the file path. + let ghost_path = std::env::temp_dir() + .join(format!("pm-keysource-terminal-{}", std::process::id())) + .join("ghost.keys"); + let specs = vec![ + KeySourceSpec::File(ghost_path.clone()), + KeySourceSpec::Environment, + ]; + let err = load_ring(&specs, &[]).unwrap_err(); + assert!( + err.contains("ghost.keys"), + "file source should be terminal and error with the path; got: {err}" + ); + } + + #[test] + fn load_ring_file_rejects_nix_store() { + // file source under /nix/store must return immediately with an + // error, not fall through to a subsequent source. + let specs = vec![ + KeySourceSpec::File(std::path::PathBuf::from("/nix/store/abc/.env.keys")), + KeySourceSpec::Environment, + ]; + let err = load_ring(&specs, &[]).unwrap_err(); + assert!( + err.contains("Nix store"), + "file source under /nix/store should be terminal and reject; got: {err}" + ); + } + + #[test] + fn load_ring_environment_is_terminal() { + // environment source with no DOTENV_PRIVATE_KEY* vars should return + // an error immediately, not fall through. Since it's the last source, + // we verify the error is from from_env, not from the "no usable key + // source" fallback message. + // + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized via ENV_LOCK against the other + // CREDENTIALS_DIRECTORY-mutating tests in this module. + let _guard = ENV_LOCK.lock().unwrap(); + let var_name = "DOTENV_PRIVATE_KEY_TESTTERMINAL"; + unsafe { + std::env::remove_var(var_name); + } + let specs = vec![ + KeySourceSpec::Credential("skipped".to_string()), + KeySourceSpec::Environment, + ]; + // Remove CREDENTIALS_DIRECTORY so credential is skippable. + unsafe { + std::env::remove_var("CREDENTIALS_DIRECTORY"); + } + let err = load_ring(&specs, &[]).unwrap_err(); + // The error must be from environment (terminal), not "no usable key + // source" (which would mean environment also fell through). + assert!( + !err.contains("no usable key source"), + "environment should be terminal, not fall through; got: {err}" + ); + } +} diff --git a/src/keys.rs b/src/keys.rs index 9fe9343..a7abc02 100644 --- a/src/keys.rs +++ b/src/keys.rs @@ -7,8 +7,6 @@ //! (see `adapter.rs`), so the core logic is adapter-neutral. The `.env` //! adapter's `KeyNaming::Env` is the first implementation. -#![allow(missing_docs, missing_debug_implementations)] - use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -25,6 +23,16 @@ use crate::config::Entry; #[derive(Debug)] pub struct KeyRing(HashMap>>); +/// True for exactly `PREFIX` or `PREFIX_`. A bare +/// prefix match would slurp unrelated variables like +/// `DOTENV_PRIVATE_KEYFOO` as key material (audit 2026-08-02 A16). +fn is_key_var_name(prefix: &str, name: &str) -> bool { + name == prefix + || name + .strip_prefix(prefix) + .is_some_and(|rest| rest.len() > 1 && rest.starts_with('_')) +} + impl KeyRing { /// Look up candidate keys for a given key variable name. /// Returns `None` if the variable has no candidates in the ring. @@ -132,7 +140,7 @@ impl KeyRing { let prefix = naming.key_prefix(); Self::from_pairs( std::env::vars() - .filter(|(k, _)| k.starts_with(prefix)) + .filter(|(k, _)| is_key_var_name(prefix, k)) .map(|(k, v)| (k, Zeroizing::new(v))), naming, ) @@ -149,32 +157,23 @@ impl KeyRing { vars: &[String], naming: KeyNaming, ) -> Result { - // Audit finding #3: verify the integrity of /usr/bin/security - // before invoking it. On macOS the binary is SIP-protected, but - // verify the code signature at runtime as defense-in-depth rather - // than trusting the path implicitly. - verify_external_binary(Path::new("/usr/bin/security"))?; + // Reads go through the Security.framework API, not the + // /usr/bin/security CLI (F1 direction): no subprocess, no argv, + // and no stdout buffer holding key material — the UTF-8-failure + // path validates from a borrow so the error never carries the + // bytes (audit 2026-08-02 A17). let mut pairs = Vec::new(); for var in vars { - let out = std::process::Command::new("/usr/bin/security") - .args(["find-generic-password", "-s", service, "-a", var, "-w"]) - .output() - .map_err(|e| format!("security: {e}"))?; - if !out.status.success() { - return Err(format!( - "keychain {service}: no item for account {var} (fail closed)" - )); - } - let mut val = Zeroizing::new( - String::from_utf8(out.stdout) - .map_err(|_| format!("keychain {service}/{var}: not UTF-8"))?, + let bytes = Zeroizing::new( + security_framework::passwords::get_generic_password(service, var).map_err( + |_| format!("keychain {service}: no item for account {var} (fail closed)"), + )?, ); - // Zeroizing the trimmed copy: the value is wrapped in Zeroizing - // before being passed to from_pairs, so key material is zeroized - // on drop at every stage. No plain-String window remains. - let trimmed = Zeroizing::new(val.trim().to_string()); - pairs.push((var.clone(), trimmed)); - val.zeroize(); + let s = std::str::from_utf8(&bytes[..]) + .map_err(|_| format!("keychain {service}/{var}: not UTF-8"))?; + // from_pairs trims each comma-separated candidate itself, so + // no separate trim is needed here. + pairs.push((var.clone(), Zeroizing::new(s.to_string()))); } Self::from_pairs(pairs, naming).map_err(|e| format!("keychain {service}: {e}")) } @@ -193,6 +192,14 @@ impl KeyRing { /// and not world-writable. There is no universal code-signing mechanism /// on Linux, so ownership and permission checks are the practical /// defense-in-depth boundary. +/// +/// Bootstrap limitation (audit 2026-08-02 O2): on macOS the verifier +/// itself invokes `/usr/bin/codesign`. Self-verifying codesign with +/// codesign is circular — a compromised codesign would vouch for +/// itself — so codesign is trusted via SIP alone. Moving verification +/// onto the Security.framework StaticCode API (the `security-framework` +/// crate route already chosen for keychain access) would remove this +/// residual trust gap. pub fn verify_external_binary(path: &Path) -> Result<(), String> { #[cfg(target_os = "macos")] { @@ -295,10 +302,11 @@ pub fn decrypt_value( return Ok(Zeroizing::new(pt)); } } + // No candidate count in the error text — the rotation-set size is + // not something errors should leak (audit 2026-08-02 A15). Err(format!( - "{}: no key under {var} decrypts {key} ({} candidate(s) tried)", - env_file.display(), - candidates.len() + "{}: no key under {var} decrypts {key}", + env_file.display() )) } @@ -309,8 +317,20 @@ pub fn resolve( ring: &KeyRing, naming: KeyNaming, ) -> Result>, String> { - let iter = dotenvy::from_path_iter(&entry.env_file) - .map_err(|e| format!("{}: {e}", entry.env_file.display()))?; + // O_NOFOLLOW on the ciphertext open (audit 2026-08-02 A13): refuse + // to read through a planted symlink. + let fd = rustix::fs::open( + &entry.env_file, + rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC, + rustix::fs::Mode::empty(), + ) + .map_err(|e| { + format!( + "{}: {e} (refusing to follow a symlink)", + entry.env_file.display() + ) + })?; + let iter = dotenvy::from_read_iter(std::fs::File::from(fd)); // Last assignment wins, matching dotenv semantics within one file. let mut found: Option> = None; for item in iter { @@ -329,12 +349,27 @@ pub fn resolve( /// Resolved (name, secret-bytes) pairs, in injection order. pub type ResolvedVars = Vec<(String, Zeroizing>)>; +/// Outcome of a [`resolve_all`] pass. +#[derive(Debug)] +pub struct Resolution { + /// Resolved (name, plaintext) pairs in injection order. + pub resolved: ResolvedVars, + /// `(name, error)` for each encrypted value that could not be + /// decrypted and was skipped under `strict: false`. Recorded so + /// `--verify-keys` can fail closed on a partial key rotation + /// (audit 2026-08-02 A3). Always empty under `strict: true`, where + /// the first failure aborts the whole pass instead. + pub failed: Vec<(String, String)>, +} + /// Resolve every key across `files` per the precedence contract /// (see docs/src/launcher-contract.md): within one file the LAST assignment /// wins (dotenv semantics); across files the FIRST file defining a key wins /// unless `overload`; keys already present in the process environment are /// skipped unless `overload`. Adapter metadata keys are dropped; /// non-identifier keys are a hard error (they become env names/filenames). +/// Undecryptable values abort under `strict`; otherwise they are skipped +/// and recorded in [`Resolution::failed`]. pub fn resolve_all( files: &[PathBuf], ring: &KeyRing, @@ -342,12 +377,20 @@ pub fn resolve_all( strict: bool, env_has: &dyn Fn(&str) -> bool, naming: KeyNaming, -) -> Result { +) -> Result { let metadata_prefix = naming.metadata_prefix(); let mut order: Vec = Vec::new(); let mut merged: HashMap)> = HashMap::new(); for f in files { - let iter = dotenvy::from_path_iter(f).map_err(|e| format!("{}: {e}", f.display()))?; + // O_NOFOLLOW on the ciphertext open (audit 2026-08-02 A13): + // refuse to read through a planted symlink. + let fd = rustix::fs::open( + f, + rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC, + rustix::fs::Mode::empty(), + ) + .map_err(|e| format!("{}: {e} (refusing to follow a symlink)", f.display()))?; + let iter = dotenvy::from_read_iter(std::fs::File::from(fd)); let mut file_vals: HashMap> = HashMap::new(); let mut file_order: Vec = Vec::new(); for item in iter { @@ -370,7 +413,12 @@ pub fn resolve_all( file_vals.insert(k, v); // last assignment within a file wins } for k in file_order { - let v = file_vals.remove(&k).expect("key recorded in file_order"); + // Unreachable invariant (file_order mirrors file_vals), but a + // clear error beats an abort under panic=abort (audit + // 2026-08-02 A22). + let Some(v) = file_vals.remove(&k) else { + return Err(format!("internal: {k} in file_order but not file_vals")); + }; if let Some(slot) = merged.get_mut(&k) { if overload { *slot = (f.clone(), v); // later file wins under overload @@ -382,22 +430,34 @@ pub fn resolve_all( } } let mut out = Vec::new(); + let mut failed = Vec::new(); for k in order { if !overload && env_has(&k) { continue; // process environment wins } - let (file, raw) = merged.remove(&k).expect("key recorded in order"); + // Unreachable invariant (order mirrors merged), but a clear error + // beats an abort under panic=abort (audit 2026-08-02 A22). + let Some((file, raw)) = merged.remove(&k) else { + return Err(format!("internal: {k} in order but not merged")); + }; match decrypt_value(&file, &k, &raw, ring, naming) { Ok(v) => out.push((k, v)), Err(e) if strict => return Err(e), - Err(e) => crate::server::log(&format!("non-strict: skipping {k}: {e}")), + Err(e) => { + crate::server::log(&format!("non-strict: skipping {k}: {e}")); + failed.push((k, e)); + } } } - Ok(out) + Ok(Resolution { + resolved: out, + failed, + }) } #[cfg(test)] #[allow(clippy::unwrap_used, clippy::panic, unused_qualifications)] +/// Inline unit tests for key loading, resolution, and decryption. pub mod tests { use super::*; use crate::adapter::KeyNaming; @@ -673,6 +733,19 @@ pub mod tests { assert!(!is_ident("9x") && !is_ident("a-b") && !is_ident("") && !is_ident("a b")); } + #[test] + fn is_key_var_name_rules() { + // audit 2026-08-02 A16: only `PREFIX` or `PREFIX_` match; + // prefix-substring collisions are rejected. + let p = "DOTENV_PRIVATE_KEY"; + assert!(is_key_var_name(p, "DOTENV_PRIVATE_KEY")); + assert!(is_key_var_name(p, "DOTENV_PRIVATE_KEY_PRODUCTION")); + assert!(!is_key_var_name(p, "DOTENV_PRIVATE_KEYFOO")); + assert!(!is_key_var_name(p, "DOTENV_PRIVATE_KEY_")); // empty suffix + assert!(!is_key_var_name(p, "DOTENV_PRIVATE_KE")); + assert!(!is_key_var_name(p, "XDOTENV_PRIVATE_KEY")); + } + #[test] fn resolve_all_precedence() { let d = tdir("prec"); @@ -688,7 +761,11 @@ pub mod tests { // default: first file wins; within a file last assignment wins; // process-env presence suppresses; DOTENV_* filtered. let out = resolve_all(&files, &ring, false, true, &|k| k == "C", KeyNaming::Env).unwrap(); - let got: Vec<(&str, &[u8])> = out.iter().map(|(k, v)| (k.as_str(), &v[..])).collect(); + let got: Vec<(&str, &[u8])> = out + .resolved + .iter() + .map(|(k, v)| (k.as_str(), &v[..])) + .collect(); assert_eq!( got, vec![("A", b"first".as_slice()), ("B", b"two".as_slice())] @@ -696,7 +773,11 @@ pub mod tests { // overload: later file wins, env presence ignored. let out = resolve_all(&files, &ring, true, true, &|k| k == "C", KeyNaming::Env).unwrap(); - let got: Vec<(&str, &[u8])> = out.iter().map(|(k, v)| (k.as_str(), &v[..])).collect(); + let got: Vec<(&str, &[u8])> = out + .resolved + .iter() + .map(|(k, v)| (k.as_str(), &v[..])) + .collect(); assert_eq!( got, vec![ @@ -743,7 +824,9 @@ pub mod tests { ) .is_err() ); - // non-strict: skipped, not served wrong. + // non-strict: skipped, not served wrong — and the skip is + // recorded so --verify-keys can fail closed on it (audit + // 2026-08-02 A3). let out = resolve_all( &[d.join(".env")], &ring, @@ -753,7 +836,9 @@ pub mod tests { KeyNaming::Env, ) .unwrap(); - assert!(out.is_empty()); + assert!(out.resolved.is_empty()); + assert_eq!(out.failed.len(), 1); + assert_eq!(out.failed[0].0, "A"); } #[test] diff --git a/src/launcher.rs b/src/launcher.rs index 3a96ed7..68c6c8c 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -5,373 +5,166 @@ //! modules/lib.nix: values are opaque bytes end to end — no interpolation, //! no eval, no shell. -#![allow(missing_docs, missing_debug_implementations)] - use std::collections::HashMap; use std::ffi::OsString; use std::fs; -use std::io::Read; use std::os::unix::ffi::OsStringExt; -use std::os::unix::fs::MetadataExt; use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; -use zeroize::Zeroizing; - use crate::adapter::KeyNaming; use crate::bundle::{parse_bundle, resolve_bundle}; -use crate::config::{ExecConfig, ExecMode, KeySourceSpec}; -use crate::keys::{KeyRing, resolve_all}; -use crate::server::{fetch_bytes, log}; +use crate::exec_config::{ExecConfig, ExecMode}; +use crate::key_source::load_ring; +use crate::keys::resolve_all; +use crate::ramdisk::verify_ramdisk; +use crate::secret_files::{Resolved, cleanup_written, env_pairs, prune_stale, write_secret_file}; +use crate::server::{fetch_bytes, log, read_capped}; + +/// macOS-only guard deferring termination signals across the window where +/// plaintext secret files exist on the ramdisk (audit 2026-08-02 A11). +/// The ramdisk persists across process death, so a signal landing +/// mid-write would otherwise strand partial plaintext. Signals are +/// *blocked*, not handled — nothing runs in async-signal context; the +/// pending set is checked synchronously before execvp, and the mask is +/// always restored before exec (a child must never inherit blocked +/// termination signals). +/// +/// Linux needs no equivalent: tmpfs does not persist across reboots, +/// systemd's `ExecStopPost` runs `postmaster cleanup`, and the next +/// launch's `prune_stale` removes residuals — documented decision per A11. +#[cfg(target_os = "macos")] +struct TerminationGuard { + old: libc::sigset_t, +} -type Resolved = Vec<(String, Zeroizing>)>; +#[cfg(target_os = "macos")] +impl TerminationGuard { + const SIGNALS: [i32; 4] = [libc::SIGTERM, libc::SIGINT, libc::SIGHUP, libc::SIGQUIT]; -/// Ordered key-source selection. `credential` is skippable (no -/// $CREDENTIALS_DIRECTORY or file absent ⇒ try next source); every other -/// source is terminal: once selected, its failure fails the launcher. -// `wanted_vars` is only consumed by the macOS keychain source; on other -// targets the parameter is unused, so silence that leg's clippy warning -// without touching the signature or source-selection semantics. -#[cfg_attr(not(target_os = "macos"), allow(unused_variables))] -fn load_ring(specs: &[KeySourceSpec], wanted_vars: &[String]) -> Result { - for spec in specs { - match spec { - KeySourceSpec::Credential(name) => { - if let Some(dir) = std::env::var_os("CREDENTIALS_DIRECTORY") { - let p = Path::new(&dir).join(name); - // Use symlink_metadata instead of p.exists(): exists() - // follows symlinks, so a planted symlink at - // $CREDENTIALS_DIRECTORY/ pointing to a - // world-readable file would be silently followed. - // Reject symlinks outright (audit finding #2); the - // subsequent KeyRing::load also opens with O_NOFOLLOW - // as defense-in-depth. - match fs::symlink_metadata(&p) { - Ok(md) if md.file_type().is_symlink() => { - return Err(format!( - "{}: credential source is a symlink; refusing to follow (remove the symlink)", - p.display() - )); - } - Ok(md) if md.is_file() => return KeyRing::load(&p, KeyNaming::Env), - Ok(_) => { - return Err(format!( - "{}: credential source is not a regular file", - p.display() - )); - } - Err(_) => { /* absent: fall through to next source */ } - } - } - // absent credential: fall through to the next source + fn block() -> Self { + unsafe { + // SAFETY: zeroed sigset_t is a valid empty set representation; + // all pointers are valid and outlive the calls. + let mut set: libc::sigset_t = std::mem::zeroed(); + libc::sigemptyset(&mut set); + for sig in Self::SIGNALS { + libc::sigaddset(&mut set, sig); } - KeySourceSpec::File(p) => { - if p.starts_with("/nix/store") { - return Err(format!( - "{}: refusing plaintext private keys from the world-readable Nix store", - p.display() - )); - } - return KeyRing::load(p, KeyNaming::Env); + let mut old: libc::sigset_t = std::mem::zeroed(); + // pthread form: correct in single- and multi-threaded processes. + libc::pthread_sigmask(libc::SIG_BLOCK, &set, &mut old); + Self { old } + } + } + + /// First deferred termination signal currently pending, if any. + fn pending(&self) -> Option { + unsafe { + // SAFETY: zeroed sigset_t is valid; sigpending fills it. + let mut set: libc::sigset_t = std::mem::zeroed(); + if libc::sigpending(&mut set) != 0 { + return None; } - KeySourceSpec::Keychain(service) => { - #[cfg(target_os = "macos")] - return KeyRing::from_keychain(service, wanted_vars, KeyNaming::Env); - #[cfg(not(target_os = "macos"))] - return Err(format!( - "key source keychain({service}) is only available on macOS" - )); + for sig in Self::SIGNALS { + if libc::sigismember(&set, sig) == 1 { + return Some(sig); + } } - KeySourceSpec::Environment => return KeyRing::from_env(KeyNaming::Env), + None } } - Err("no usable key source (configure keys=[…] or set DOTENV_PRIVATE_KEY*)".into()) -} -/// Pure parser for /sbin/mount output: is `mp` mounted as HFS? -fn mount_lists_hfs(mount_out: &str, mp: &Path) -> bool { - // Strip trailing slashes so a mount point like "/foo/" matches - // "/foo" in mount output (which never includes trailing slashes). - let mp_str = mp.to_string_lossy(); - let mp_trimmed = mp_str.trim_end_matches('/'); - let needle = format!(" on {mp_trimmed} (hfs"); - mount_out.lines().any(|l| l.contains(&needle)) -} + /// Restore the saved signal mask. MUST be called before execvp — + /// the child must not inherit blocked termination signals. + fn restore(self) { + // Consuming self runs Drop, which does the restore. + } -/// Extract the device path for a mount point from `mount` output. -/// Format: `/dev/disk8 on /path (hfs, ...)` → `/dev/disk8`. -fn mount_device_for(mount_out: &str, mp: &Path) -> Option { - let mp_str = mp.to_string_lossy(); - let mp_trimmed = mp_str.trim_end_matches('/'); - let needle = format!(" on {mp_trimmed} (hfs"); - for line in mount_out.lines() { - if let Some(idx) = line.find(&needle) { - // The device is everything before " on " - let device = &line[..idx].trim(); - if !device.is_empty() { - return Some(device.to_string()); - } + /// Restore the mask, reset the signal to its default disposition, and + /// re-raise it so the process dies by the signal as the sender + /// intended. Never returns. + fn die_by(&self, sig: i32) -> ! { + unsafe { + // SAFETY: plain single-threaded-at-this-point signal ops; + // SIG_DFL is the documented default-disposition constant. + libc::signal(sig, libc::SIG_DFL); + libc::pthread_sigmask(libc::SIG_SETMASK, &self.old, std::ptr::null_mut()); + libc::raise(sig); + // Unreachable unless raise(3) itself failed. + libc::_exit(128 + sig); } } - None } -/// Verify that a device is backed by RAM (not a file-backed disk image). -/// Parses `hdiutil info` text output for the device's `image-path` -/// field and checks it starts with `ram://`. -fn device_is_ram_backed(device: &str, hdiutil_out: &str) -> bool { - // hdiutil info output structure (per image entry): - // image-path : ram://1024 - // image-type : read/write - // ... - // /dev/disk8 - // - // The device appears as a line by itself after the image properties. - // We find the device line, then scan backwards for the image-path - // field in the same image entry. - - let lines: Vec<&str> = hdiutil_out.lines().collect(); - let device_line = device.trim(); - for (idx, line) in lines.iter().enumerate() { - if line.trim() == device_line { - // Scan backwards from the device line to find image-path - for prev in lines[..idx].iter().rev() { - let trimmed = prev.trim(); - if trimmed.starts_with("image-path") { - // Extract the value after "image-path : " - if let Some(colon_idx) = trimmed.find(':') { - let value = trimmed[colon_idx + 1..].trim(); - return value.starts_with("ram://"); - } - } - // If we hit another device line or a separator, this - // image entry's properties ended — stop scanning. - if trimmed.starts_with("/dev/") || trimmed.starts_with("====") { - break; - } - } - return false; +#[cfg(target_os = "macos")] +impl Drop for TerminationGuard { + fn drop(&mut self) { + unsafe { + // SAFETY: restoring a previously saved valid mask. + libc::pthread_sigmask(libc::SIG_SETMASK, &self.old, std::ptr::null_mut()); } } - false } -/// darwin ramdisk guard (was ramdiskGuard in modules/darwin.nix): plaintext -/// lands only on the postmaster ramdisk, in a directory this user owns. -fn verify_ramdisk(mount_point: &Path, secrets_dir: &Path) -> Result<(), String> { - let out = std::process::Command::new("/sbin/mount") - .output() - .map_err(|e| format!("/sbin/mount: {e}"))?; - let text = String::from_utf8_lossy(&out.stdout); - if !mount_lists_hfs(&text, mount_point) { - return Err(format!( - "{}: not the postmaster ramdisk; refusing to write plaintext to persistent disk", - mount_point.display() - )); - } - // Verify the mount is RAM-backed, not a file-backed HFS image. - // Extract the device from mount output, then check hdiutil info - // for that device's image-path starting with ram://. - let device = mount_device_for(&text, mount_point).ok_or_else(|| { - format!( - "{}: could not determine backing device from mount output", - mount_point.display() - ) - })?; - let hdiutil_out = std::process::Command::new("/usr/bin/hdiutil") - .arg("info") - .output() - .map_err(|e| format!("hdiutil info: {e}"))?; - let hdiutil_text = String::from_utf8_lossy(&hdiutil_out.stdout); - if !device_is_ram_backed(&device, &hdiutil_text) { - return Err(format!( - "{}: mount device {device} is not RAM-backed (image-path does not start with ram://); refusing to write plaintext to a file-backed disk image", - mount_point.display() - )); - } - // Use symlink_metadata instead of metadata: if secrets_dir is itself a - // symlink to persistent disk (planted by a prior compromised launch on - // the darwin ramdisk, which persists across restarts), fs::metadata would - // follow the link and inspect the TARGET — a directory owned by the - // service user on persistent disk — and approve it. Reject symlinks - // outright so the ramdisk invariant is not bypassed. - let md = fs::symlink_metadata(secrets_dir).map_err(|e| { - format!( - "{}: {e} (is postmaster-ramdisk healthy?)", - secrets_dir.display() - ) - })?; - if md.file_type().is_symlink() { - return Err(format!( - "{}: secrets_dir is a symlink; refusing to follow — remove the symlink and ensure the directory is on the ramdisk", - secrets_dir.display() - )); - } - if !md.is_dir() || md.uid() != rustix::process::geteuid().as_raw() { - return Err(format!( - "{}: missing or not owned by this service user (is postmaster-ramdisk healthy?)", - secrets_dir.display() - )); +/// No-op on non-macOS platforms (see the macOS docs above). +#[cfg(not(target_os = "macos"))] +struct TerminationGuard; + +#[cfg(not(target_os = "macos"))] +impl TerminationGuard { + fn block() -> Self { + Self } - Ok(()) -} -/// Resolved values → env pairs. Env values cannot hold NUL; fail closed -/// rather than truncate. -fn env_pairs(resolved: &Resolved) -> Result, String> { - let mut out = Vec::with_capacity(resolved.len()); - for (k, v) in resolved { - if v.contains(&0) { - return Err(format!( - "{k}: value contains a NUL byte; cannot be an environment variable (use files mode)" - )); - } - out.push((OsString::from(k.clone()), OsString::from_vec(v.to_vec()))); + fn pending(&self) -> Option { + None } - Ok(out) -} -/// Writes `value` to `dir.join(key)`. Invariant this enforces: plaintext -/// lands only on the mount `verify_ramdisk` already checked — a symlink -/// planted at the target path (e.g. by leftover/attacker-controlled state -/// in a per-service ramdisk dir that persists across restarts) must never -/// be followed onto persistent disk, so the open refuses symlinks -/// (`O_NOFOLLOW`) and fails closed instead. -fn write_secret_file(dir: &Path, key: &str, value: &[u8]) -> Result { - use std::io::Write; - let path = dir.join(key); - let oflags = rustix::fs::OFlags::WRONLY - | rustix::fs::OFlags::CREATE - | rustix::fs::OFlags::TRUNC - | rustix::fs::OFlags::NOFOLLOW - | rustix::fs::OFlags::CLOEXEC; - let fd = rustix::fs::open(&path, oflags, rustix::fs::Mode::from_bits_truncate(0o600)) - .map_err(|e| format!("{}: {e} (refusing to follow a symlink)", path.display()))?; - // Use fchmod on the fd (not set_permissions on the path) to eliminate a - // TOCTOU: between open(O_NOFOLLOW) and a path-based chmod, an attacker - // with directory write access could unlink the file and create a symlink - // at the same path. fchmod operates on the already-opened fd, which is - // the file we just created — no path re-resolution occurs. - rustix::fs::fchmod(&fd, rustix::fs::Mode::from_bits_truncate(0o600)) - .map_err(|e| format!("{}: fchmod: {e}", path.display()))?; - let mut f = fs::File::from(fd); - f.write_all(value) - .and_then(|()| f.flush()) - .map_err(|e| format!("{}: write: {e}", path.display()))?; - Ok(path) -} + /// No-op (nothing was blocked). + fn restore(self) {} -/// Unlink all paths in `written` (best-effort) after a mid-loop failure so -/// stale plaintext files do not persist on the ramdisk/tmpfs. The caller -/// must only push successfully-written secret file paths here. -fn cleanup_written(written: &[PathBuf]) { - for p in written { - let _ = fs::remove_file(p); + fn die_by(&self, _sig: i32) -> ! { + // Unreachable: pending() is always None here. + std::process::abort() } } -/// Prune stale secret files from `dir` that are not in `keep_keys`. This -/// removes plaintext files left behind by a previous launch whose config -/// has since changed (a key removed from credential_keys or a resolved key -/// set that no longer includes a prior entry). Best-effort: logs but does -/// not fail if a file cannot be removed, since the primary invariant — -/// plaintext is transient — is best served by cleaning what we can rather -/// than aborting the launch over an unrelated stale file. -fn prune_stale(dir: &Path, keep_keys: &[String]) -> Result<(), String> { - let keep: std::collections::HashSet<&str> = keep_keys.iter().map(String::as_str).collect(); - let entries = match fs::read_dir(dir) { - Ok(e) => e, - // If the directory does not exist yet, there is nothing to prune. - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(e) => return Err(format!("{}: prune: {e}", dir.display())), - }; - for entry in entries { - let entry = match entry { - Ok(e) => e, - Err(e) => { - log(&format!( - "{}: prune: skip unreadable entry: {e}", - dir.display() - )); - continue; - } - }; - let name = entry.file_name(); - let Some(name_str) = name.to_str() else { - continue; - }; - if keep.contains(name_str) { - continue; - } - // Only unlink regular files; skip subdirectories and symlinks to - // avoid following attacker-controlled links in a shared dir. - let path = entry.path(); - match fs::symlink_metadata(&path) { - Ok(md) if md.is_file() => { - if let Err(e) = fs::remove_file(&path) { - log(&format!("{}: prune: {e}", path.display())); - } - } - Ok(md) => { - log(&format!( - "{}: prune: skipping non-file (type {:?})", - path.display(), - md.file_type() - )); - } - Err(e) => { - log(&format!("{}: prune: stat: {e}", path.display())); - } - } - } - Ok(()) +/// Read and deserialize an ExecConfig from a JSON file. Shared by +/// `check_config` (validate-only) and `exec` (validate + materialize). +pub fn parse_exec_config(config_path: &Path) -> Result { + let file = + fs::File::open(config_path).map_err(|e| format!("{}: {e}", config_path.display()))?; + let raw = read_capped(file, config_path)?; + serde_json::from_slice(&raw).map_err(|e| format!("{}: {e}", config_path.display())) } -/// Preflight key freshness check (audit finding #4): verify that the -/// loaded key ring can actually decrypt at least one encrypted value -/// from the env files. Catches stale keys from a previous rotation -/// cycle that are valid hex but no longer match the ciphertext. Without -/// this check, `strict: false` would silently skip undecryptable values -/// and launch the child with no secrets. +/// Validate the public shape of an exec config without decrypting, +/// reading key material, or touching the host filesystem. This is +/// the `--check` contract for CI and automation tools. +pub fn check_config(config_path: &Path) -> Result<(), String> { + let cfg = parse_exec_config(config_path)?; + cfg.validate_shape() +} + +/// Preflight key freshness check: fail if any encrypted env value was +/// skipped during resolution because the key ring could not decrypt it +/// (audit 2026-08-02 A3). Under `strict: false` a partial key rotation +/// would otherwise pass silently here — the old check only caught total +/// failure (empty resolved set) — and the child would launch with a +/// partial secret set. The failure list recorded by `resolve_all` makes +/// every skip visible to `--verify-keys`. /// -/// The check scans each env file for the first `encrypted:` value and -/// attempts a test decryption. If no encrypted values exist (all -/// plaintext passthrough), the check passes trivially. -fn verify_key_freshness(resolved: &Resolved, env_files: &[PathBuf]) -> Result<(), String> { - // If we resolved at least one value, the keys are fresh enough. - // An empty resolved vec with encrypted values in the env files means - // the keys are stale (all decryptions failed under strict:false). - if !resolved.is_empty() { - return Ok(()); - } - // resolved is empty: check whether any env file contains encrypted - // values. If none do (all plaintext), the empty result is expected. - for env_file in env_files { - let iter = match dotenvy::from_path_iter(env_file) { - Ok(it) => it, - Err(e) => return Err(format!("{}: {e}", env_file.display())), - }; - for item in iter { - let (k, v) = match item { - Ok(p) => p, - Err(e) => return Err(format!("{}: {e}", env_file.display())), - }; - if let Some(prefix) = KeyNaming::Env.metadata_prefix() - && k.starts_with(prefix) - { - continue; - } - if v.starts_with("encrypted:") { - // Found an encrypted value but resolved is empty: the - // keys are stale and could not decrypt it. - return Err(format!( - "{}: --verify-keys failed: key ring could not decrypt {k} (stale keys from a previous rotation?)", - env_file.display() - )); - } - } +/// Bundle files need no scan here: `resolve_bundle` is all-or-nothing — +/// the first undecryptable entry aborts `decrypt()` regardless of +/// `strict`, so stale bundle keys already fail closed before this check +/// runs (audit 2026-08-02 A4). +fn verify_key_freshness(failed: &[(String, String)]) -> Result<(), String> { + if let Some((k, _)) = failed.first() { + return Err(format!( + "--verify-keys failed: key ring could not decrypt {k} (stale keys from a previous rotation?)" + )); } - // No encrypted values found: the empty resolved vec is expected. Ok(()) } @@ -395,7 +188,10 @@ fn validate_credential_keys(keys: &[String]) -> Result<(), String> { Ok(()) } -fn decrypt(cfg: &ExecConfig) -> Result { +/// Decrypt all configured inputs. Returns the resolved (name, plaintext) +/// pairs plus the `(name, error)` list of encrypted env values skipped +/// under `strict: false` (consumed by `verify_key_freshness`). +fn decrypt(cfg: &ExecConfig) -> Result<(Resolved, Vec<(String, String)>), String> { if cfg.env_files.is_empty() && cfg.bundle_files.is_empty() { return Err("exec config lists no env_files or bundle_files".into()); } @@ -410,23 +206,39 @@ fn decrypt(cfg: &ExecConfig) -> Result { } let ring = load_ring(&cfg.keys, &wanted)?; - // Resolve .env files (if any) via the env adapter - let mut resolved: Resolved = if cfg.env_files.is_empty() { - Vec::new() + // Resolve .env files (if any) via the env adapter. Values skipped + // under strict:false are recorded in `failed` so --verify-keys can + // fail closed on a partial key rotation (audit 2026-08-02 A3). + let (mut resolved, failed): (Resolved, Vec<(String, String)>) = if cfg.env_files.is_empty() { + (Vec::new(), Vec::new()) } else { - resolve_all( + let r = resolve_all( &cfg.env_files, &ring, cfg.overload, cfg.strict, &|k| std::env::var_os(k).is_some(), KeyNaming::Env, - )? + )?; + (r.resolved, r.failed) }; // Resolve bundle files (if any) via the bundle adapter for bundle_path in &cfg.bundle_files { - let raw = fs::read(bundle_path).map_err(|e| format!("{}: {e}", bundle_path.display()))?; + // O_NOFOLLOW on the ciphertext open (audit 2026-08-02 A13): + // refuse to read through a planted symlink. + let bundle_fd = rustix::fs::open( + bundle_path, + rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC, + rustix::fs::Mode::empty(), + ) + .map_err(|e| { + format!( + "{}: {e} (refusing to follow a symlink)", + bundle_path.display() + ) + })?; + let raw = read_capped(fs::File::from(bundle_fd), bundle_path)?; let bundle = parse_bundle(&raw, bundle_path)?; let bundle_resolved = resolve_bundle(&bundle, &ring, bundle_path)?; for (name, value, encoding) in bundle_resolved { @@ -451,539 +263,32 @@ fn decrypt(cfg: &ExecConfig) -> Result { } } - Ok(resolved) -} - -pub fn check_config(config_path: &Path) -> Result<(), String> { - let cfg = parse_exec_config(config_path)?; - cfg.validate_shape() -} - -/// `postmaster setup`: verify platform prerequisites, create keys -/// directory with correct permissions, optionally seed keychain items, -/// and validate the environment. Idempotent — skips steps that are -/// already correct. -/// -/// `--recheck`: re-run verification checks only, without creating or -/// modifying anything. Equivalent to the old `setup_recheck`. -/// -/// `--unattended`: non-interactive mode for automation. Uses defaults -/// or env vars instead of prompting. Fail closed on any missing -/// prerequisite. -/// -/// `--force`: re-seed or re-create even if the target state is already -/// present. -/// -/// `--keys-dir `: override the keys directory path. Default is -/// `postmaster cleanup`: remove all secret files from the secrets_dir -/// configured in the exec config. Intended for `ExecStopPost` in systemd -/// or equivalent lifecycle hooks. Does not decrypt — only removes files -/// that postmaster would have written. Safe to run even if the directory -/// is empty or does not exist. -pub fn cleanup(config_path: &Path) -> Result<(), String> { - let cfg = parse_exec_config(config_path)?; - let dir = cfg - .secrets_dir - .as_deref() - .ok_or("cleanup: config has no secrets_dir — nothing to clean up")?; - let entries = match fs::read_dir(dir) { - Ok(e) => e, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - log(&format!( - "cleanup: {} does not exist; nothing to clean up", - dir.display() - )); - return Ok(()); - } - Err(e) => return Err(format!("{}: cleanup: {e}", dir.display())), - }; - let mut removed = 0_usize; - for entry in entries { - let entry = match entry { - Ok(e) => e, - Err(e) => { - log(&format!( - "{}: cleanup: skip unreadable entry: {e}", - dir.display() - )); - continue; - } - }; - let path = entry.path(); - match fs::symlink_metadata(&path) { - Ok(md) if md.is_file() => { - if let Err(e) = fs::remove_file(&path) { - log(&format!("{}: cleanup: {e}", path.display())); - } else { - removed += 1; - } - } - Ok(md) => { - log(&format!( - "{}: cleanup: skipping non-file (type {:?})", - path.display(), - md.file_type() - )); - } - Err(e) => { - log(&format!("{}: cleanup: stat: {e}", path.display())); - } - } - } - log(&format!( - "cleanup: removed {removed} file(s) from {}", - dir.display() - )); - Ok(()) -} - -/// Default keys directory path: `/var/lib/postmaster` on Linux, -/// `~/Library/Application Support/postmaster` on macOS. -pub fn setup( - config_path: &Path, - recheck: bool, - unattended: bool, - force: bool, - keys_dir_override: Option, -) -> Result<(), String> { - let cfg = parse_exec_config(config_path)?; - cfg.validate_shape()?; - - // Build the wanted key variable list from both env and bundle files - let mut wanted: Vec = Vec::new(); - for f in &cfg.env_files { - wanted.push(KeyNaming::Env.key_var_for(f)?); - } - for f in &cfg.bundle_files { - wanted.push(KeyNaming::Bundle.key_var_for(f)?); - } - - // Step 1: Verify platform prerequisites - verify_platform_prerequisites(&cfg, unattended)?; - - if recheck { - // --recheck: verification only, no creation or modification - return verify_key_sources(&cfg, &wanted); - } - - // Step 2: Create or verify keys directory - let keys_dir = keys_dir_override.unwrap_or_else(default_keys_dir); - ensure_keys_dir(&keys_dir, force)?; - - // Step 3: Verify or create key files for file-source keys - for spec in &cfg.keys { - if let KeySourceSpec::File(path) = spec { - ensure_keys_file(path, force, unattended)?; - } - } - - // Step 4: Verify or seed keychain items (macOS only) - #[cfg(target_os = "macos")] - for spec in &cfg.keys { - if let KeySourceSpec::Keychain(service) = spec { - ensure_keychain_items(service, &wanted, force, unattended)?; - } - } - - // Step 5: Verify the full environment (same as --recheck) - verify_key_sources(&cfg, &wanted)?; - - log(&format!( - "setup: complete — keys dir {}, {} key source(s) verified", - keys_dir.display(), - cfg.keys.len() - )); - Ok(()) -} - -/// Default keys directory path: `/var/lib/postmaster` on Linux, -/// `~/Library/Application Support/postmaster` on macOS. -fn default_keys_dir() -> PathBuf { - #[cfg(target_os = "macos")] - { - if let Some(home) = std::env::var_os("HOME") { - return PathBuf::from(home) - .join("Library") - .join("Application Support") - .join("postmaster"); - } - } - PathBuf::from("/var/lib/postmaster") -} - -/// Verify platform prerequisites: codesign check on macOS, root-owned -/// binary check on Linux. Fails closed in unattended mode if the -/// external binary can't be verified. -fn verify_platform_prerequisites(cfg: &ExecConfig, _unattended: bool) -> Result<(), String> { - // Only check if keychain source is configured (the only source that - // invokes an external binary) - let has_keychain = cfg - .keys - .iter() - .any(|k| matches!(k, KeySourceSpec::Keychain(_))); - if !has_keychain { - return Ok(()); - } - - #[cfg(target_os = "macos")] - { - // Verify /usr/bin/security code signature - crate::keys::verify_external_binary(Path::new("/usr/bin/security")) - .map_err(|e| format!("platform prerequisite: {e}"))?; - log("setup: platform prerequisite verified (codesign /usr/bin/security)"); - } - - #[cfg(not(target_os = "macos"))] - { - let _ = unattended; - log("setup: no platform-specific prerequisites on this OS"); - } - - Ok(()) -} - -/// Create the keys directory with 0700 permissions if it doesn't exist. -/// If it exists, verify permissions and ownership are correct. Idempotent -/// — skips if already correct unless `force` is true. -fn ensure_keys_dir(keys_dir: &Path, _force: bool) -> Result<(), String> { - if keys_dir.exists() { - // Verify it's a directory, not a symlink - let md = - fs::symlink_metadata(keys_dir).map_err(|e| format!("{}: {e}", keys_dir.display()))?; - if md.is_symlink() { - return Err(format!( - "{}: refusing to use a symlink as keys directory", - keys_dir.display() - )); - } - if !md.is_dir() { - return Err(format!( - "{}: exists but is not a directory", - keys_dir.display() - )); - } - // Verify permissions: 0700 (rwx------) - use std::os::unix::fs::PermissionsExt; - let mode = md.permissions().mode(); - if mode & 0o077 != 0 { - // Fix permissions if we can - fs::set_permissions(keys_dir, fs::Permissions::from_mode(0o700)) - .map_err(|e| format!("{}: cannot fix permissions: {e}", keys_dir.display()))?; - log(&format!( - "{}: permissions corrected to 0700", - keys_dir.display() - )); - } - log(&format!("{}: keys directory verified", keys_dir.display())); - return Ok(()); - } - - // Create the directory with 0700 - fs::create_dir_all(keys_dir) - .map_err(|e| format!("{}: cannot create keys directory: {e}", keys_dir.display()))?; - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(keys_dir, fs::Permissions::from_mode(0o700)) - .map_err(|e| format!("{}: cannot set permissions: {e}", keys_dir.display()))?; - log(&format!( - "{}: keys directory created with 0700", - keys_dir.display() - )); - Ok(()) -} - -/// Verify a keys file exists with correct permissions (0600, owned by -/// euid). If the file doesn't exist, in interactive mode, prompt the -/// operator to create it. In unattended mode, fail closed. If the file -/// exists but has wrong permissions, fix them. -#[allow(clippy::print_stderr)] -fn ensure_keys_file(path: &Path, _force: bool, unattended: bool) -> Result<(), String> { - if path.exists() { - // Verify permissions and ownership (same checks as setup_recheck) - let oflags = - rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC; - let fd = rustix::fs::open(path, oflags, rustix::fs::Mode::empty()) - .map_err(|e| format!("{}: {e} (refusing to follow a symlink)", path.display()))?; - let stat = rustix::fs::fstat(&fd).map_err(|e| format!("{}: fstat: {e}", path.display()))?; - let mode = rustix::fs::Mode::from_bits_truncate(stat.st_mode); - if mode.intersects(rustix::fs::Mode::RWXG | rustix::fs::Mode::RWXO) { - // Fix permissions - rustix::fs::fchmod(&fd, rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR) - .map_err(|e| format!("{}: cannot fix permissions: {e}", path.display()))?; - log(&format!( - "{}: permissions corrected to 0600", - path.display() - )); - } - let euid = rustix::process::geteuid().as_raw(); - if stat.st_uid != euid { - return Err(format!( - "{}: owned by uid {} but postmaster euid is {euid} (cannot fix ownership automatically)", - path.display(), - stat.st_uid - )); - } - log(&format!("{}: keys file verified", path.display())); - return Ok(()); - } - - // File doesn't exist - if unattended { - return Err(format!( - "{}: keys file not found (unattended mode — cannot prompt; create the file manually before running setup)", - path.display() - )); - } - - // Interactive: prompt the operator - eprintln!("{}: keys file not found.", path.display()); - eprintln!( - "Create it now? You will need to paste the key contents (DOTENV_PRIVATE_KEY=<64-hex>...). [y/N] " - ); - let mut input = String::new(); - if std::io::stdin().read_line(&mut input).is_err() { - return Err(format!("{}: cannot read input", path.display())); - } - if !input.trim().eq_ignore_ascii_case("y") { - return Err(format!( - "{}: operator declined to create keys file", - path.display() - )); - } - - eprintln!("Paste the keys file contents (Ctrl+D to finish):"); - let mut contents = String::new(); - if std::io::stdin().read_to_string(&mut contents).is_err() { - return Err(format!("{}: cannot read key contents", path.display())); - } - - // Write the file with 0600 - use std::os::unix::fs::OpenOptionsExt; - let mut file = fs::OpenOptions::new() - .write(true) - .create(true) - .truncate(true) - .mode(0o600) - .open(path) - .map_err(|e| format!("{}: cannot create: {e}", path.display()))?; - use std::io::Write; - file.write_all(contents.as_bytes()) - .map_err(|e| format!("{}: cannot write: {e}", path.display()))?; - log(&format!("{}: keys file created with 0600", path.display())); - Ok(()) -} - -/// Verify keychain items exist for the wanted key variables. If they -/// don't exist and we're in interactive mode, offer to seed them. -/// On macOS only. -#[cfg(target_os = "macos")] -#[allow(clippy::print_stderr)] -fn ensure_keychain_items( - service: &str, - wanted: &[String], - force: bool, - unattended: bool, -) -> Result<(), String> { - let mut missing: Vec<&str> = Vec::new(); - for var in wanted { - let out = std::process::Command::new("/usr/bin/security") - .args(["find-generic-password", "-s", service, "-a", var, "-w"]) - .output() - .map_err(|e| format!("security: {e}"))?; - if !out.status.success() { - missing.push(var); - } - } - - if missing.is_empty() && !force { - log(&format!( - "keychain {service}: all {wanted_len} item(s) verified", - wanted_len = wanted.len() - )); - return Ok(()); - } - - if unattended && !missing.is_empty() { - return Err(format!( - "keychain {service}: {missing_len} item(s) missing (unattended mode — cannot prompt)", - missing_len = missing.len() - )); - } - - // Interactive: offer to seed missing items - if !missing.is_empty() { - eprintln!( - "keychain {service}: missing items for: {}", - missing.join(", ") - ); - eprintln!("Seed them now? You will need to paste each key value. [y/N] "); - let mut input = String::new(); - if std::io::stdin().read_line(&mut input).is_err() { - return Err("cannot read input".into()); - } - if !input.trim().eq_ignore_ascii_case("y") { - return Err(format!( - "keychain {service}: operator declined to seed missing items" - )); - } - - for var in &missing { - eprint!("Paste value for {var}: "); - let mut value = String::new(); - if std::io::stdin().read_line(&mut value).is_err() { - return Err(format!("cannot read value for {var}")); - } - let value = value.trim(); - if value.is_empty() { - return Err(format!("{var}: empty value, refusing to seed")); - } - let out = std::process::Command::new("/usr/bin/security") - .args([ - "add-generic-password", - "-s", - service, - "-a", - var, - "-w", - value, - ]) - .output() - .map_err(|e| format!("security: {e}"))?; - if !out.status.success() { - return Err(format!( - "keychain {service}: failed to seed {var}: {}", - String::from_utf8_lossy(&out.stderr) - )); - } - log(&format!("keychain {service}: seeded {var}")); - } - } - - Ok(()) -} - -/// Verify that all configured key sources are accessible. This is the -/// `--recheck` path — same as the old `setup_recheck` function. -fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> { - let mut checked = 0_u32; - let mut found = 0_u32; - - for spec in &cfg.keys { - match spec { - KeySourceSpec::Credential(name) => { - checked += 1; - let dir = std::env::var_os("CREDENTIALS_DIRECTORY") - .ok_or("$CREDENTIALS_DIRECTORY is not set")?; - let p = Path::new(&dir).join(name); - if !p.exists() { - return Err(format!( - "{}: credential source not found under $CREDENTIALS_DIRECTORY", - p.display() - )); - } - found += 1; - } - KeySourceSpec::File(path) => { - checked += 1; - if path.starts_with("/nix/store") { - return Err(format!( - "{}: refusing plaintext private keys from the world-readable Nix store", - path.display() - )); - } - let oflags = rustix::fs::OFlags::RDONLY - | rustix::fs::OFlags::NOFOLLOW - | rustix::fs::OFlags::CLOEXEC; - let fd = - rustix::fs::open(path, oflags, rustix::fs::Mode::empty()).map_err(|e| { - format!("{}: {e} (refusing to follow a symlink)", path.display()) - })?; - let stat = rustix::fs::fstat(&fd) - .map_err(|e| format!("{}: fstat: {e}", path.display()))?; - let mode = rustix::fs::Mode::from_bits_truncate(stat.st_mode); - if mode.intersects(rustix::fs::Mode::RWXG | rustix::fs::Mode::RWXO) { - return Err(format!( - "{}: permissions {:#o} are group/world accessible; expected 0400 or 0600", - path.display(), - stat.st_mode - )); - } - let euid = rustix::process::geteuid().as_raw(); - if stat.st_uid != euid { - return Err(format!( - "{}: owned by uid {} but postmaster euid is {euid}", - path.display(), - stat.st_uid - )); - } - found += 1; - } - KeySourceSpec::Keychain(service) => { - checked += 1; - #[cfg(target_os = "macos")] - { - for var in wanted { - let out = std::process::Command::new("/usr/bin/security") - .args(["find-generic-password", "-s", service, "-a", var, "-w"]) - .output() - .map_err(|e| format!("security: {e}"))?; - if !out.status.success() { - return Err(format!( - "keychain {service}: no item for account {var} (fail closed)" - )); - } - } - found += 1; - } - #[cfg(not(target_os = "macos"))] - { - let _ = service; - return Err("keychain source is only available on macOS".into()); - } - } - KeySourceSpec::Environment => { - checked += 1; - let env_prefix = KeyNaming::Env.key_prefix(); - let bundle_prefix = KeyNaming::Bundle.key_prefix(); - let has_key = std::env::vars() - .any(|(k, _)| k.starts_with(env_prefix) || k.starts_with(bundle_prefix)); - if !has_key { - return Err(format!( - "environment: no {env_prefix}* or {bundle_prefix}* variables set" - )); - } - found += 1; - } - } - } - - if checked == 0 { - return Err("no key sources configured (configure keys=[…])".into()); - } - - log(&format!( - "setup: {found}/{checked} key source(s) verified — environment ready" - )); - Ok(()) -} - -/// Read and deserialize an ExecConfig from a JSON file. Shared by -/// `check_config` (validate-only) and `exec` (validate + materialize). -fn parse_exec_config(config_path: &Path) -> Result { - let raw = fs::read(config_path).map_err(|e| format!("{}: {e}", config_path.display()))?; - serde_json::from_slice(&raw).map_err(|e| format!("{}: {e}", config_path.display())) + Ok((resolved, failed)) } +/// Decrypt configured secret inputs, inject them into the child +/// context, and `execvp` the target binary. The process image is +/// replaced — this function never returns on success. pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<(), String> { let cfg = parse_exec_config(config_path)?; cfg.validate_shape()?; + let program = argv.first().ok_or("exec: empty argv")?; + // Defer termination signals until just before execvp, so a signal + // landing mid-write can't strand plaintext on disk (audit + // 2026-08-02 A11; no-op on Linux — see TerminationGuard docs). + let sig_guard = TerminationGuard::block(); let mut extra: Vec<(OsString, OsString)> = Vec::new(); + // Plaintext files written by Files/Credentials modes, tracked across + // the match so the exec-failure path can remove them (audit + // 2026-08-02 A9). + let mut written: Vec = Vec::new(); match cfg.mode { ExecMode::Env => { - let resolved = decrypt(&cfg)?; + let (resolved, failed) = decrypt(&cfg)?; if verify_keys { - verify_key_freshness(&resolved, &cfg.env_files)?; + verify_key_freshness(&failed)?; } extra = env_pairs(&resolved)?; // resolved (Zeroizing> values) dropped here — @@ -1016,14 +321,14 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() } } } - let resolved = decrypt(&cfg)?; + let (resolved, failed) = decrypt(&cfg)?; if verify_keys { - verify_key_freshness(&resolved, &cfg.env_files)?; + verify_key_freshness(&failed)?; } // Prune stale secret files from a prior launch before writing new ones. let keep_keys: Vec = resolved.iter().map(|(k, _)| k.clone()).collect(); prune_stale(dir, &keep_keys)?; - let mut written: Vec = Vec::with_capacity(resolved.len()); + written.reserve(resolved.len()); for (k, v) in &resolved { let path = match write_secret_file(dir, k, v) { Ok(p) => p, @@ -1076,7 +381,7 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() let sockets: &HashMap = &cfg.sockets; // Prune stale credential files from a prior launch. prune_stale(dir, &cfg.credential_keys)?; - let mut written: Vec = Vec::with_capacity(cfg.credential_keys.len()); + written.reserve(cfg.credential_keys.len()); for k in &cfg.credential_keys { let sock = sockets .get(k) @@ -1106,11 +411,24 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() } } - let program = argv.first().ok_or("exec: empty argv")?; + // A termination signal arrived during the write window: remove the + // plaintext, then die by that signal as the sender intended (A11). + if let Some(sig) = sig_guard.pending() { + cleanup_written(&written); + sig_guard.die_by(sig); + } + // Restore the signal mask before execvp — the child must not inherit + // blocked termination signals. + sig_guard.restore(); let err = std::process::Command::new(program) .args(&argv[1..]) .envs(extra) .exec(); // only returns on failure + // execvp failed: the process image was NOT replaced, so any + // plaintext secret files written above would otherwise persist + // (the macOS ramdisk survives process death). Remove them before + // returning the error (audit 2026-08-02 A9). + cleanup_written(&written); log(&format!("exec {program}: {err}")); Err(format!("exec {program}: {err}")) } @@ -1120,69 +438,6 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() mod tests { use super::*; - #[test] - fn mount_guard_parses_mount_output() { - let out = "/dev/disk3 on / (apfs, local)\n/dev/disk7 on /private/var/run/postmaster (hfs, local, nodev, nosuid, noexec)\n"; - assert!(mount_lists_hfs( - out, - Path::new("/private/var/run/postmaster") - )); - assert!(!mount_lists_hfs(out, Path::new("/private/var/run/other"))); - assert!(!mount_lists_hfs("/dev/disk3 on / (apfs)\n", Path::new("/"))); - } - - #[test] - fn mount_device_for_extracts_device() { - let out = "/dev/disk3 on / (apfs, local)\n/dev/disk7 on /private/var/run/postmaster (hfs, local, nodev, nosuid, noexec)\n"; - assert_eq!( - mount_device_for(out, Path::new("/private/var/run/postmaster")), - Some("/dev/disk7".to_string()) - ); - assert_eq!(mount_device_for(out, Path::new("/nonexistent")), None); - } - - #[test] - fn device_is_ram_backed_detects_ram_prefix() { - let hdiutil = "\ -framework : 683.100.3 -driver : 683.100.3 -================================================ -image-path : ram://1024 -shadow-path : -icon-path : /System/Library/PrivateFrameworks/DiskImages.framework/Resources/CDiskImage.icns -image-type : read/write -system-image : false -blockcount : 1024 -blocksize : 512 -writeable : TRUE -autodiskmount : false -removable : TRUE ---\nframework name : DiskImages -/dev/disk8 -"; - assert!(device_is_ram_backed("/dev/disk8", hdiutil)); - - let hdiutil_file = "\ -================================================ -image-path : /Users/user/image.dmg -shadow-path : -image-type : read/write -/dev/disk9 -"; - assert!(!device_is_ram_backed("/dev/disk9", hdiutil_file)); - - // Device not in hdiutil output at all - assert!(!device_is_ram_backed("/dev/disk99", hdiutil)); - } - - #[test] - fn env_pairs_rejects_interior_nul() { - let ok = vec![("A".to_string(), Zeroizing::new(b"x\ny".to_vec()))]; - assert_eq!(env_pairs(&ok).unwrap().len(), 1); - let bad = vec![("A".to_string(), Zeroizing::new(b"x\0y".to_vec()))]; - assert!(env_pairs(&bad).unwrap_err().contains("NUL")); - } - #[test] fn validate_credential_keys_accepts_identifiers() { assert!(validate_credential_keys(&["DB_URL".to_string()]).is_ok()); @@ -1199,43 +454,15 @@ image-type : read/write } } - fn tdir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("pm-launcher-{tag}-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); - d - } - - #[test] - fn write_secret_file_refuses_symlink() { - let dir = tdir("symlink"); - // A persistent-disk target that must never receive the plaintext. - let real_target = dir.join("real-target"); - fs::write(&real_target, b"untouched").unwrap(); - // Attacker-planted symlink at the path write_secret_file will target. - let link_path = dir.join("KEY"); - std::os::unix::fs::symlink(&real_target, &link_path).unwrap(); - - let result = write_secret_file(&dir, "KEY", b"attacker-controlled-plaintext"); - - assert!( - result.is_err(), - "write_secret_file must refuse to follow a symlink at the target path" - ); - assert_eq!( - fs::read(&real_target).unwrap(), - b"untouched", - "the symlink's target file must not be written to" - ); - } - #[test] fn exec_rejects_empty_argv_instead_of_panicking() { use std::os::unix::fs::PermissionsExt; // A config that resolves cleanly in "env" mode (no ramdisk/creds // machinery involved) so the empty-argv guard is what's exercised, // not an earlier, unrelated failure. - let d = tdir("emptyargv"); + let d = std::env::temp_dir().join(format!("pm-launcher-emptyargv-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); let keys_path = d.join(".env.keys"); fs::write( &keys_path, @@ -1260,235 +487,4 @@ image-type : read/write let err = exec(&cfg_path, &[], false).unwrap_err(); assert!(err.contains("empty argv"), "{err}"); } - - #[test] - fn prune_stale_removes_unconfigured_files() { - let dir = tdir("prune"); - // Simulate a previous launch that wrote KEY_A and KEY_B. - fs::write(dir.join("KEY_A"), b"old-a").unwrap(); - fs::write(dir.join("KEY_B"), b"old-b").unwrap(); - - // New config only keeps KEY_A; KEY_B should be pruned. - prune_stale(&dir, &["KEY_A".to_string()]).unwrap(); - - assert!(dir.join("KEY_A").exists(), "KEY_A should survive prune"); - assert!(!dir.join("KEY_B").exists(), "KEY_B should be pruned"); - } - - #[test] - fn prune_stale_skips_non_files_and_missing_dir() { - let dir = tdir("prune-nonfile"); - // A subdirectory should be skipped, not unlinked. - fs::create_dir(dir.join("subdir")).unwrap(); - // A file that is kept should survive. - fs::write(dir.join("KEEP_ME"), b"data").unwrap(); - - prune_stale(&dir, &["KEEP_ME".to_string()]).unwrap(); - assert!(dir.join("KEEP_ME").exists()); - assert!(dir.join("subdir").is_dir(), "subdir should not be removed"); - - // Non-existent directory: no error, nothing to prune. - let ghost = dir.join("does-not-exist"); - assert!(prune_stale(&ghost, &["X".to_string()]).is_ok()); - } - - #[test] - fn cleanup_written_unlinks_files() { - let dir = tdir("cleanup"); - let f1 = dir.join("A"); - let f2 = dir.join("B"); - fs::write(&f1, b"secret-a").unwrap(); - fs::write(&f2, b"secret-b").unwrap(); - - cleanup_written(&[f1.clone(), f2.clone()]); - - assert!(!f1.exists(), "cleanup should unlink f1"); - assert!(!f2.exists(), "cleanup should unlink f2"); - } - - #[test] - fn cleanup_removes_all_files_from_secrets_dir() { - let dir = tdir("cleanup-subcmd"); - fs::write(dir.join("KEY_A"), b"secret-a").unwrap(); - fs::write(dir.join("KEY_B"), b"secret-b").unwrap(); - fs::create_dir(dir.join("subdir")).unwrap(); - - let cfg_path = dir.join("exec.json"); - fs::write( - &cfg_path, - format!( - r#"{{"mode":"files","keys":["environment"],"env_files":["/nonexistent"],"secrets_dir":"{}"}}"#, - dir.display() - ), - ) - .unwrap(); - - cleanup(&cfg_path).unwrap(); - - assert!(!dir.join("KEY_A").exists(), "KEY_A should be removed"); - assert!(!dir.join("KEY_B").exists(), "KEY_B should be removed"); - assert!(dir.join("subdir").exists(), "subdir should be preserved"); - } - - #[test] - fn cleanup_nonexistent_dir_is_ok() { - let dir = tdir("cleanup-missing"); - let cfg_path = dir.join("exec.json"); - fs::write( - &cfg_path, - format!( - r#"{{"mode":"files","keys":["environment"],"env_files":["/nonexistent"],"secrets_dir":"{}/no-such-dir"}}"#, - dir.display() - ), - ) - .unwrap(); - - assert!(cleanup(&cfg_path).is_ok()); - } - - #[test] - fn load_ring_credential_is_skippable() { - // credential source with no CREDENTIALS_DIRECTORY set should fall - // through to the next source. Here the next source is "environment", - // which is terminal and will fail closed (no DOTENV_PRIVATE_KEY* - // vars in the test runner). The error must be from the environment - // source, not from the credential source. - // - // SAFETY: set_var/remove_var are unsafe on edition 2024 (not - // thread-safe). This test does not spawn threads. - unsafe { - std::env::remove_var("CREDENTIALS_DIRECTORY"); - } - let specs = vec![ - KeySourceSpec::Credential("nonexistent".to_string()), - KeySourceSpec::Environment, - ]; - let err = load_ring(&specs, &[]).unwrap_err(); - // The error should come from the environment source (terminal), - // proving credential fell through rather than erroring. - assert!( - err.contains("environment:") || err.contains("no usable key source"), - "credential should be skippable; got: {err}" - ); - } - - #[test] - fn load_ring_credential_rejects_symlink() { - // Audit finding #2: a symlink planted at - // $CREDENTIALS_DIRECTORY/ must be rejected, not followed. - use std::os::unix::fs::PermissionsExt; - let d = tdir("cred-symlink"); - let real = d.join("real-keys"); - fs::write(&real, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); - fs::set_permissions(&real, fs::Permissions::from_mode(0o600)).unwrap(); - let cred_dir = d.join("creds"); - fs::create_dir_all(&cred_dir).unwrap(); - let link = cred_dir.join("dotenv-private-key"); - std::os::unix::fs::symlink(&real, &link).unwrap(); - - // SAFETY: set_var/remove_var are unsafe on edition 2024 (not - // thread-safe). This test does not spawn threads. - unsafe { - std::env::set_var("CREDENTIALS_DIRECTORY", &cred_dir); - } - let specs = vec![KeySourceSpec::Credential("dotenv-private-key".to_string())]; - let err = load_ring(&specs, &[]).unwrap_err(); - unsafe { - std::env::remove_var("CREDENTIALS_DIRECTORY"); - } - assert!( - err.contains("symlink"), - "credential symlink should be rejected; got: {err}" - ); - } - - #[test] - fn load_ring_credential_rejects_non_file() { - // A directory as a credential source name should be rejected, - // not silently skipped or treated as a file. - let d = tdir("cred-dir"); - let cred_dir = d.join("creds"); - fs::create_dir_all(&cred_dir).unwrap(); - let sub = cred_dir.join("subdir"); - fs::create_dir_all(&sub).unwrap(); - - // SAFETY: set_var/remove_var are unsafe on edition 2024 (not - // thread-safe). This test does not spawn threads. - unsafe { - std::env::set_var("CREDENTIALS_DIRECTORY", &cred_dir); - } - let specs = vec![KeySourceSpec::Credential("subdir".to_string())]; - let err = load_ring(&specs, &[]).unwrap_err(); - unsafe { - std::env::remove_var("CREDENTIALS_DIRECTORY"); - } - assert!( - err.contains("not a regular file"), - "credential directory should be rejected; got: {err}" - ); - } - - #[test] - fn load_ring_file_is_terminal() { - // file source with a nonexistent path should return an error - // immediately, NOT fall through to the next source. We verify this - // by putting a valid "environment" source after the bad file source: - // if file were skippable, load_ring would try environment and fail - // with "environment:" — instead it must fail with the file path. - let ghost_path = tdir("terminal-file").join("ghost.keys"); - let specs = vec![ - KeySourceSpec::File(ghost_path.clone()), - KeySourceSpec::Environment, - ]; - let err = load_ring(&specs, &[]).unwrap_err(); - assert!( - err.contains("ghost.keys"), - "file source should be terminal and error with the path; got: {err}" - ); - } - - #[test] - fn load_ring_file_rejects_nix_store() { - // file source under /nix/store must return immediately with an - // error, not fall through to a subsequent source. - let specs = vec![ - KeySourceSpec::File(std::path::PathBuf::from("/nix/store/abc/.env.keys")), - KeySourceSpec::Environment, - ]; - let err = load_ring(&specs, &[]).unwrap_err(); - assert!( - err.contains("Nix store"), - "file source under /nix/store should be terminal and reject; got: {err}" - ); - } - - #[test] - fn load_ring_environment_is_terminal() { - // environment source with no DOTENV_PRIVATE_KEY* vars should return - // an error immediately, not fall through. Since it's the last source, - // we verify the error is from from_env, not from the "no usable key - // source" fallback message. - // - // SAFETY: set_var/remove_var are unsafe on edition 2024 (not - // thread-safe). This test does not spawn threads. - let var_name = "DOTENV_PRIVATE_KEY_TESTTERMINAL"; - unsafe { - std::env::remove_var(var_name); - } - let specs = vec![ - KeySourceSpec::Credential("skipped".to_string()), - KeySourceSpec::Environment, - ]; - // Remove CREDENTIALS_DIRECTORY so credential is skippable. - unsafe { - std::env::remove_var("CREDENTIALS_DIRECTORY"); - } - let err = load_ring(&specs, &[]).unwrap_err(); - // The error must be from environment (terminal), not "no usable key - // source" (which would mean environment also fell through). - assert!( - !err.contains("no usable key source"), - "environment should be terminal, not fall through; got: {err}" - ); - } } diff --git a/src/lib.rs b/src/lib.rs index b5932f2..33beb00 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,16 +6,20 @@ //! //! Security and fail-closed semantics are preserved exactly. -#![allow(missing_docs, missing_debug_implementations)] - pub mod adapter; pub mod bundle; pub mod config; +pub mod exec_config; +pub mod key_provisioning; +pub mod key_source; pub mod keys; pub mod launcher; +pub mod ramdisk; +pub mod secret_files; pub mod server; pub use config::{Invocation, parse_args, parse_args_from}; +pub use key_provisioning::{cleanup, setup}; pub use server::{fetch, harden_process, run}; /// Re-exported for binary use. The real main is here so tests can call into it. @@ -41,8 +45,8 @@ pub fn main() -> std::process::ExitCode { unattended, force, keys_dir, - }) => launcher::setup(&config, recheck, unattended, force, keys_dir), - Ok(Invocation::Cleanup { config }) => launcher::cleanup(&config), + }) => setup(&config, recheck, unattended, force, keys_dir), + Ok(Invocation::Cleanup { config }) => cleanup(&config), #[allow(clippy::print_stdout, clippy::print_stderr)] Ok(Invocation::Help(sub)) => { let text = match sub.as_deref() { diff --git a/src/ramdisk.rs b/src/ramdisk.rs new file mode 100644 index 0000000..7d89e2a --- /dev/null +++ b/src/ramdisk.rs @@ -0,0 +1,207 @@ +//! macOS ramdisk verification — ensures plaintext secret files land only +//! on a RAM-backed HFS disk image owned by the service user. +//! +//! This module implements the `ramdiskGuard` invariant that was previously +//! templated in `modules/darwin.nix`. On Linux the ramdisk check is not +//! used (tmpfs is already RAM-backed by definition). + +use std::fs; +use std::os::unix::fs::MetadataExt; +use std::path::Path; + +/// Pure parser for /sbin/mount output: is `mp` mounted as HFS? +fn mount_lists_hfs(mount_out: &str, mp: &Path) -> bool { + // Strip trailing slashes so a mount point like "/foo/" matches + // "/foo" in mount output (which never includes trailing slashes). + let mp_str = mp.to_string_lossy(); + let mp_trimmed = mp_str.trim_end_matches('/'); + let needle = format!(" on {mp_trimmed} (hfs"); + mount_out.lines().any(|l| l.contains(&needle)) +} + +/// Extract the device path for a mount point from `mount` output. +/// Format: `/dev/disk8 on /path (hfs, ...)` → `/dev/disk8`. +fn mount_device_for(mount_out: &str, mp: &Path) -> Option { + let mp_str = mp.to_string_lossy(); + let mp_trimmed = mp_str.trim_end_matches('/'); + let needle = format!(" on {mp_trimmed} (hfs"); + for line in mount_out.lines() { + if let Some(idx) = line.find(&needle) { + // The device is everything before " on " + let device = &line[..idx].trim(); + if !device.is_empty() { + return Some(device.to_string()); + } + } + } + None +} + +/// Verify that a device is backed by RAM (not a file-backed disk image). +/// Parses `hdiutil info` text output for the device's `image-path` +/// field and checks it starts with `ram://`. +fn device_is_ram_backed(device: &str, hdiutil_out: &str) -> bool { + // hdiutil info output structure (per image entry): + // image-path : ram://1024 + // image-type : read/write + // ... + // /dev/disk8 + // + // The device appears as a line by itself after the image properties. + // We find the device line, then scan backwards for the image-path + // field in the same image entry. + + let lines: Vec<&str> = hdiutil_out.lines().collect(); + let device_line = device.trim(); + for (idx, line) in lines.iter().enumerate() { + if line.trim() == device_line { + // Scan backwards from the device line to find image-path + for prev in lines[..idx].iter().rev() { + let trimmed = prev.trim(); + if trimmed.starts_with("image-path") { + // Extract the value after "image-path : " + if let Some(colon_idx) = trimmed.find(':') { + let value = trimmed[colon_idx + 1..].trim(); + return value.starts_with("ram://"); + } + } + // If we hit another device line or a separator, this + // image entry's properties ended — stop scanning. + if trimmed.starts_with("/dev/") || trimmed.starts_with("====") { + break; + } + } + return false; + } + } + false +} + +/// darwin ramdisk guard (was ramdiskGuard in modules/darwin.nix): plaintext +/// lands only on the postmaster ramdisk, in a directory this user owns. +pub fn verify_ramdisk(mount_point: &Path, secrets_dir: &Path) -> Result<(), String> { + // Trust boundary (audit 2026-08-02 O2): a compromised /sbin/mount or + // hdiutil could report persistent disk as the RAM-backed postmaster + // ramdisk and let plaintext land on persistent storage. Verify both + // helpers before invoking, same as /usr/bin/security. + crate::keys::verify_external_binary(Path::new("/sbin/mount"))?; + crate::keys::verify_external_binary(Path::new("/usr/bin/hdiutil"))?; + let out = std::process::Command::new("/sbin/mount") + .output() + .map_err(|e| format!("/sbin/mount: {e}"))?; + let text = String::from_utf8_lossy(&out.stdout); + if !mount_lists_hfs(&text, mount_point) { + return Err(format!( + "{}: not the postmaster ramdisk; refusing to write plaintext to persistent disk", + mount_point.display() + )); + } + // Verify the mount is RAM-backed, not a file-backed HFS image. + // Extract the device from mount output, then check hdiutil info + // for that device's image-path starting with ram://. + let device = mount_device_for(&text, mount_point).ok_or_else(|| { + format!( + "{}: could not determine backing device from mount output", + mount_point.display() + ) + })?; + let hdiutil_out = std::process::Command::new("/usr/bin/hdiutil") + .arg("info") + .output() + .map_err(|e| format!("hdiutil info: {e}"))?; + let hdiutil_text = String::from_utf8_lossy(&hdiutil_out.stdout); + if !device_is_ram_backed(&device, &hdiutil_text) { + return Err(format!( + "{}: mount device {device} is not RAM-backed (image-path does not start with ram://); refusing to write plaintext to a file-backed disk image", + mount_point.display() + )); + } + // Use symlink_metadata instead of metadata: if secrets_dir is itself a + // symlink to persistent disk (planted by a prior compromised launch on + // the darwin ramdisk, which persists across restarts), fs::metadata would + // follow the link and inspect the TARGET — a directory owned by the + // service user on persistent disk — and approve it. Reject symlinks + // outright so the ramdisk invariant is not bypassed. + let md = fs::symlink_metadata(secrets_dir).map_err(|e| { + format!( + "{}: {e} (is postmaster-ramdisk healthy?)", + secrets_dir.display() + ) + })?; + if md.file_type().is_symlink() { + return Err(format!( + "{}: secrets_dir is a symlink; refusing to follow — remove the symlink and ensure the directory is on the ramdisk", + secrets_dir.display() + )); + } + if !md.is_dir() || md.uid() != rustix::process::geteuid().as_raw() { + return Err(format!( + "{}: missing or not owned by this service user (is postmaster-ramdisk healthy?)", + secrets_dir.display() + )); + } + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic)] +mod tests { + use super::*; + use std::path::Path; + + #[test] + fn mount_guard_parses_mount_output() { + let out = "/dev/disk3 on / (apfs, local)\n/dev/disk7 on /private/var/run/postmaster (hfs, local, nodev, nosuid, noexec)\n"; + assert!(mount_lists_hfs( + out, + Path::new("/private/var/run/postmaster") + )); + assert!(!mount_lists_hfs(out, Path::new("/private/var/run/other"))); + assert!(!mount_lists_hfs("/dev/disk3 on / (apfs)\n", Path::new("/"))); + } + + #[test] + fn mount_device_for_extracts_device() { + let out = "/dev/disk3 on / (apfs, local)\n/dev/disk7 on /private/var/run/postmaster (hfs, local, nodev, nosuid, noexec)\n"; + assert_eq!( + mount_device_for(out, Path::new("/private/var/run/postmaster")), + Some("/dev/disk7".to_string()) + ); + assert_eq!(mount_device_for(out, Path::new("/nonexistent")), None); + } + + #[test] + fn device_is_ram_backed_detects_ram_prefix() { + let hdiutil = "\ +framework : 683.100.3 +driver : 683.100.3 +================================================ +image-path : ram://1024 +shadow-path : +icon-path : /System/Library/PrivateFrameworks/DiskImages.framework/Resources/CDiskImage.icns +image-type : read/write +system-image : false +blockcount : 1024 +blocksize : 512 +writeable : TRUE +autodiskmount : false +removable : TRUE +-- +framework name : DiskImages +/dev/disk8 +"; + assert!(device_is_ram_backed("/dev/disk8", hdiutil)); + + let hdiutil_file = "\ +================================================ +image-path : /Users/user/image.dmg +shadow-path : +image-type : read/write +/dev/disk9 +"; + assert!(!device_is_ram_backed("/dev/disk9", hdiutil_file)); + + // Device not in hdiutil output at all + assert!(!device_is_ram_backed("/dev/disk99", hdiutil)); + } +} diff --git a/src/secret_files.rs b/src/secret_files.rs new file mode 100644 index 0000000..7cd44ad --- /dev/null +++ b/src/secret_files.rs @@ -0,0 +1,318 @@ +//! Secret file operations — writing, cleanup, and pruning of plaintext +//! secret files on RAM-backed filesystems. +//! +//! All file operations use `O_NOFOLLOW` and fd-based permissions to +//! eliminate TOCTOU race conditions against symlink attacks. + +use std::ffi::OsString; +use std::fs; +use std::io::Write; +use std::os::unix::ffi::OsStringExt; +use std::path::{Path, PathBuf}; + +use zeroize::Zeroizing; + +/// Resolved values keyed by name, each zeroized on drop. +pub type Resolved = Vec<(String, Zeroizing>)>; + +/// Marker file postmaster creates in any secrets_dir it writes to +/// (audit 2026-08-02 A19). `prune_stale` and `cleanup` refuse to +/// bulk-delete in a non-empty directory that lacks it — foreign files +/// could be present. A permission-mode check cannot make that +/// distinction: the Linux files-mode secrets dir is a namespace-private +/// tmpfs systemd mounts 1777, which is dedicated yet world-accessible. +pub const MANAGED_SENTINEL: &str = ".postmaster-managed"; + +/// Resolved values → env pairs. Env values cannot hold NUL; fail closed +/// rather than truncate. +pub fn env_pairs(resolved: &Resolved) -> Result, String> { + let mut out = Vec::with_capacity(resolved.len()); + for (k, v) in resolved { + if v.contains(&0) { + return Err(format!( + "{k}: value contains a NUL byte; cannot be an environment variable (use files mode)" + )); + } + out.push((OsString::from(k.clone()), OsString::from_vec(v.to_vec()))); + } + Ok(out) +} + +/// Writes `value` to `dir.join(key)`. Invariant this enforces: plaintext +/// lands only on the mount `verify_ramdisk` already checked — a symlink +/// planted at the target path (e.g. by leftover/attacker-controlled state +/// in a per-service ramdisk dir that persists across restarts) must never +/// be followed onto persistent disk, so the open refuses symlinks +/// (`O_NOFOLLOW`) and fails closed instead. The directory itself is +/// pinned by fd (audit 2026-08-02 A12): a symlink swapped in at `dir` +/// after the caller's checks is rejected, and the file open is relative +/// to the pinned directory inode, not a path re-resolution. +pub fn write_secret_file(dir: &Path, key: &str, value: &[u8]) -> Result { + let dir_fd = rustix::fs::open( + dir, + rustix::fs::OFlags::RDONLY + | rustix::fs::OFlags::DIRECTORY + | rustix::fs::OFlags::NOFOLLOW + | rustix::fs::OFlags::CLOEXEC, + rustix::fs::Mode::empty(), + ) + .map_err(|e| format!("{}: {e} (refusing to follow a symlink)", dir.display()))?; + let path = dir.join(key); + // Drop the managed-dir sentinel (audit 2026-08-02 A19): prune_stale + // and cleanup refuse to bulk-delete in a non-empty dir lacking it. + let _sentinel_fd = rustix::fs::openat( + &dir_fd, + MANAGED_SENTINEL, + rustix::fs::OFlags::WRONLY + | rustix::fs::OFlags::CREATE + | rustix::fs::OFlags::NOFOLLOW + | rustix::fs::OFlags::CLOEXEC, + rustix::fs::Mode::from_bits_truncate(0o600), + ) + .map_err(|e| format!("{}: sentinel: {e}", path.display()))?; + let oflags = rustix::fs::OFlags::WRONLY + | rustix::fs::OFlags::CREATE + | rustix::fs::OFlags::TRUNC + | rustix::fs::OFlags::NOFOLLOW + | rustix::fs::OFlags::CLOEXEC; + // `key` is a validated identifier (no separators), so this opens + // exactly `dir/key` beneath the pinned directory fd. + let fd = rustix::fs::openat( + &dir_fd, + key, + oflags, + rustix::fs::Mode::from_bits_truncate(0o600), + ) + .map_err(|e| format!("{}: {e} (refusing to follow a symlink)", path.display()))?; + // Use fchmod on the fd (not set_permissions on the path) to eliminate a + // TOCTOU: between open(O_NOFOLLOW) and a path-based chmod, an attacker + // with directory write access could unlink the file and create a symlink + // at the same path. fchmod operates on the already-opened fd, which is + // the file we just created — no path re-resolution occurs. + rustix::fs::fchmod(&fd, rustix::fs::Mode::from_bits_truncate(0o600)) + .map_err(|e| format!("{}: fchmod: {e}", path.display()))?; + let mut f = fs::File::from(fd); + f.write_all(value) + .and_then(|()| f.flush()) + .map_err(|e| format!("{}: write: {e}", path.display()))?; + Ok(path) +} + +/// Unlink all paths in `written` (best-effort) after a mid-loop failure so +/// stale plaintext files do not persist on the ramdisk/tmpfs. The caller +/// must only push successfully-written secret file paths here. +pub fn cleanup_written(written: &[PathBuf]) { + for p in written { + let _ = fs::remove_file(p); + } +} + +/// Prune stale secret files from `dir` that are not in `keep_keys`. This +/// removes plaintext files left behind by a previous launch whose config +/// has since changed (a key removed from credential_keys or a resolved key +/// set that no longer includes a prior entry). Best-effort: logs but does +/// not fail if a file cannot be removed, since the primary invariant — +/// plaintext is transient — is best served by cleaning what we can rather +/// than aborting the launch over an unrelated stale file. +pub fn prune_stale(dir: &Path, keep_keys: &[String]) -> Result<(), String> { + let keep: std::collections::HashSet<&str> = keep_keys.iter().map(String::as_str).collect(); + // Symlinked or non-directory secrets dir: refuse outright. + let md = match fs::symlink_metadata(dir) { + Ok(md) => md, + // If the directory does not exist yet, there is nothing to prune. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(format!("{}: prune: {e}", dir.display())), + }; + if md.file_type().is_symlink() || !md.is_dir() { + return Err(format!( + "{}: prune: refusing a symlinked or non-directory secrets dir", + dir.display() + )); + } + let entries = match fs::read_dir(dir) { + Ok(e) => e, + // Raced away between the stat and here: nothing to prune. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(format!("{}: prune: {e}", dir.display())), + }; + let entries: Vec> = entries.collect(); + // An empty directory is trivially safe (first launch). + if entries.is_empty() { + return Ok(()); + } + // Managed-dir guard (audit 2026-08-02 A19): non-empty and no + // sentinel means postmaster never wrote here — bulk deletes could + // hit foreign files. Refuse. + match fs::symlink_metadata(dir.join(MANAGED_SENTINEL)) { + Ok(smd) if smd.is_file() => {} + _ => { + return Err(format!( + "{}: prune: no {MANAGED_SENTINEL} sentinel; refusing to bulk-delete in a directory postmaster did not write to", + dir.display() + )); + } + } + for entry in entries { + let entry = match entry { + Ok(e) => e, + Err(e) => { + crate::server::log(&format!( + "{}: prune: skip unreadable entry: {e}", + dir.display() + )); + continue; + } + }; + let name = entry.file_name(); + let Some(name_str) = name.to_str() else { + continue; + }; + // The sentinel is infrastructure, not a secret — never prune it. + if name_str == MANAGED_SENTINEL || keep.contains(name_str) { + continue; + } + // Only unlink regular files; skip subdirectories and symlinks to + // avoid following attacker-controlled links in a shared dir. + let path = entry.path(); + match fs::symlink_metadata(&path) { + Ok(md) if md.is_file() => { + if let Err(e) = fs::remove_file(&path) { + crate::server::log(&format!("{}: prune: {e}", path.display())); + } + } + Ok(md) => { + crate::server::log(&format!( + "{}: prune: skipping non-file (type {:?})", + path.display(), + md.file_type() + )); + } + Err(e) => { + crate::server::log(&format!("{}: prune: stat: {e}", path.display())); + } + } + } + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic)] +mod tests { + use super::*; + + fn tdir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("pm-secretfiles-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + // prune_stale requires a postmaster-managed (owner-only) dir + // (audit 2026-08-02 A19); match real deployments. + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&d, fs::Permissions::from_mode(0o700)).unwrap(); + d + } + + #[test] + fn env_pairs_rejects_interior_nul() { + let ok = vec![("A".to_string(), Zeroizing::new(b"x\ny".to_vec()))]; + assert_eq!(env_pairs(&ok).unwrap().len(), 1); + let bad = vec![("A".to_string(), Zeroizing::new(b"x\0y".to_vec()))]; + assert!(env_pairs(&bad).unwrap_err().contains("NUL")); + } + + #[test] + fn write_secret_file_refuses_symlink() { + let dir = tdir("symlink"); + // A persistent-disk target that must never receive the plaintext. + let real_target = dir.join("real-target"); + fs::write(&real_target, b"untouched").unwrap(); + // Attacker-planted symlink at the path write_secret_file will target. + let link_path = dir.join("KEY"); + std::os::unix::fs::symlink(&real_target, &link_path).unwrap(); + + let result = write_secret_file(&dir, "KEY", b"attacker-controlled-plaintext"); + + assert!( + result.is_err(), + "write_secret_file must refuse to follow a symlink at the target path" + ); + assert_eq!( + fs::read(&real_target).unwrap(), + b"untouched", + "the symlink's target file must not be written to" + ); + } + + #[test] + fn prune_stale_removes_unconfigured_files() { + let dir = tdir("prune"); + // Simulate a previous launch that wrote KEY_A and KEY_B (the + // sentinel marks the dir as postmaster-managed — A19). + fs::write(dir.join("KEY_A"), b"old-a").unwrap(); + fs::write(dir.join("KEY_B"), b"old-b").unwrap(); + fs::write(dir.join(MANAGED_SENTINEL), b"").unwrap(); + + // New config only keeps KEY_A; KEY_B should be pruned. + prune_stale(&dir, &["KEY_A".to_string()]).unwrap(); + + assert!(dir.join("KEY_A").exists(), "KEY_A should survive prune"); + assert!(!dir.join("KEY_B").exists(), "KEY_B should be pruned"); + assert!( + dir.join(MANAGED_SENTINEL).exists(), + "sentinel is never pruned" + ); + } + + #[test] + fn prune_stale_refuses_unmanaged_dir() { + // audit 2026-08-02 A19: a non-empty dir without the sentinel was + // never written by postmaster; bulk deletes could hit foreign + // files. + let dir = tdir("prune-unmanaged"); + fs::write(dir.join("FOREIGN"), b"not-ours").unwrap(); + + let err = prune_stale(&dir, &[]).unwrap_err(); + + assert!(err.contains("sentinel"), "{err}"); + assert!(dir.join("FOREIGN").exists(), "nothing may be deleted"); + } + + #[test] + fn prune_stale_empty_dir_needs_no_sentinel() { + // First launch: the secrets dir exists but is empty — nothing to + // prune, no sentinel required. + let dir = tdir("prune-empty"); + prune_stale(&dir, &[]).unwrap(); + } + + #[test] + fn prune_stale_skips_non_files_and_missing_dir() { + let dir = tdir("prune-nonfile"); + // A subdirectory should be skipped, not unlinked. + fs::create_dir(dir.join("subdir")).unwrap(); + // A file that is kept should survive. + fs::write(dir.join("KEEP_ME"), b"data").unwrap(); + fs::write(dir.join(MANAGED_SENTINEL), b"").unwrap(); + + prune_stale(&dir, &["KEEP_ME".to_string()]).unwrap(); + assert!(dir.join("KEEP_ME").exists()); + assert!(dir.join("subdir").is_dir(), "subdir should not be removed"); + + // Non-existent directory: no error, nothing to prune. + let ghost = dir.join("does-not-exist"); + assert!(prune_stale(&ghost, &["X".to_string()]).is_ok()); + } + + #[test] + fn cleanup_written_unlinks_files() { + let dir = tdir("cleanup"); + let f1 = dir.join("A"); + let f2 = dir.join("B"); + fs::write(&f1, b"secret-a").unwrap(); + fs::write(&f2, b"secret-b").unwrap(); + + cleanup_written(&[f1.clone(), f2.clone()]); + + assert!(!f1.exists(), "cleanup should unlink f1"); + assert!(!f2.exists(), "cleanup should unlink f2"); + } +} diff --git a/src/server.rs b/src/server.rs index 93e9f4b..f30ab8f 100644 --- a/src/server.rs +++ b/src/server.rs @@ -3,8 +3,6 @@ //! This module contains the bulk of the runtime behavior while keeping //! main.rs thin. -#![allow(missing_docs, missing_debug_implementations)] - use std::fs; use std::io::{Read, Write}; use std::net::Shutdown; @@ -31,11 +29,24 @@ const SD_LISTEN_FDS_START: RawFd = 3; // stderr IS the daemon's log transport (journald on Linux, launchd // StandardErrorPath on darwin) — this is the one sanctioned print site. +/// Log a message to stderr (journald on Linux, launchd on macOS). #[allow(clippy::print_stderr)] pub fn log(msg: &str) { eprintln!("postmaster: {msg}"); } +/// Serve a single credential entry on a Unix socket. Handles one peer +/// at a time (thread-per-socket); each peer must be PID 1 or an allowed +/// service user. +/// +/// Connection limiting (audit 2026-08-02 A25, documented decision): the +/// loop is serialized — one connection at a time, each accepted stream +/// closed at the end of its iteration, writes bounded by WRITE_TIMEOUT — +/// so per-connection FDs/threads never accumulate and pending connects +/// are bounded by the kernel backlog. A trusted peer (root or the +/// configured peer_user) can starve the listener with slow connections; +/// that is the authorized consumer of this socket, so no rate limiting +/// is implemented. pub fn serve( listener: UnixListener, path: PathBuf, @@ -86,16 +97,40 @@ pub fn serve( } } -/// Connect, read one credential to EOF. Zero bytes means the server -/// refused to serve — fail closed, exactly like LoadCredential failing. +/// Maximum bytes accepted for any single secret, bundle, or config +/// read. These payloads are small; the cap keeps a hostile or broken +/// peer (or a swapped-in special file) from forcing unbounded heap +/// allocation (audit 2026-08-02 A6). 16 MiB is far above any legitimate +/// payload. +const MAX_READ_BYTES: u64 = 16 * 1024 * 1024; + +/// Read `reader` to EOF with a hard size cap (audit 2026-08-02 A6). +/// Fails rather than truncates when the stream exceeds the cap — a +/// truncated secret must never be served as if complete. +pub(crate) fn read_capped(reader: R, path: &Path) -> Result, String> { + let mut limited = reader.take(MAX_READ_BYTES + 1); + let mut buf = Vec::new(); + limited + .read_to_end(&mut buf) + .map_err(|e| format!("{}: read: {e}", path.display()))?; + if buf.len() as u64 > MAX_READ_BYTES { + return Err(format!( + "{}: exceeds the {}-byte size cap", + path.display(), + MAX_READ_BYTES + )); + } + Ok(buf) +} + +/// Connect, read one credential to EOF (hard-capped by `read_capped`). +/// Zero bytes means the server refused to serve — fail closed, exactly +/// like LoadCredential failing. pub fn fetch_bytes(path: &Path) -> Result>, String> { - let mut stream = + let stream = UnixStream::connect(path).map_err(|e| format!("{}: connect: {e}", path.display()))?; let _ = stream.set_read_timeout(Some(WRITE_TIMEOUT)); - let mut buf = Zeroizing::new(Vec::new()); - stream - .read_to_end(&mut buf) - .map_err(|e| format!("{}: read: {e}", path.display()))?; + let buf = Zeroizing::new(read_capped(stream, path)?); if buf.is_empty() { return Err(format!( "{}: server sent zero bytes (refused to serve); failing closed", @@ -157,35 +192,64 @@ fn peer_euid(stream: &UnixStream) -> std::io::Result { Ok(euid) } +/// Apply process-level hardening: disable core dumps, prevent ptrace +/// attachment, and pin memory (Linux only). Called once at startup. #[cfg(target_os = "linux")] pub fn harden_process() { - // No core dumps, no ptrace from non-privileged peers. - let _ = rustix::process::set_dumpable_behavior(rustix::process::DumpableBehavior::NotDumpable); + // No core dumps, no ptrace from non-privileged peers. Best-effort by + // policy, but a failure is security-relevant — log it (audit + // 2026-08-02 A10). + if let Err(e) = + rustix::process::set_dumpable_behavior(rustix::process::DumpableBehavior::NotDumpable) + { + log(&format!( + "hardening: set_dumpable(NotDumpable) failed: {e} — core dumps/ptrace not disabled" + )); + } // Best effort: keep key material off swap even without the unit-level - // MemorySwapMax=0 belt (may fail under RLIMIT_MEMLOCK; that's fine). - let _ = rustix::mm::mlockall( - rustix::mm::MlockAllFlags::CURRENT | rustix::mm::MlockAllFlags::FUTURE, - ); + // MemorySwapMax=0 belt (may fail under RLIMIT_MEMLOCK; that's fine — + // but say so). + if let Err(e) = + rustix::mm::mlockall(rustix::mm::MlockAllFlags::CURRENT | rustix::mm::MlockAllFlags::FUTURE) + { + log(&format!( + "hardening: mlockall failed: {e} — decrypted secrets may swap to disk (check RLIMIT_MEMLOCK)" + )); + } } +/// Apply process-level hardening: disable core dumps and prevent ptrace +/// attachment (macOS only). Called once at startup. #[cfg(target_os = "macos")] pub fn harden_process() { // Closest analog to PR_SET_DUMPABLE for dumps: no core files, ever. - let _ = rustix::process::setrlimit( + // Best-effort by policy, but failures are security-relevant — log + // them (audit 2026-08-02 A10). + if let Err(e) = rustix::process::setrlimit( rustix::process::Resource::Core, rustix::process::Rlimit { current: Some(0), maximum: Some(0), }, - ); + ) { + log(&format!( + "hardening: setrlimit(Core, 0) failed: {e} — core dumps not disabled" + )); + } // macOS has no mlockall(2); its swap is encrypted by default, so pages // that do swap out are ciphertext at rest. Deny debugger attach in // release builds (the ptrace-from-peers half of PR_SET_DUMPABLE). #[cfg(not(debug_assertions))] - // SAFETY: PT_DENY_ATTACH takes no pointer arguments; null addr and zero - // data are the documented invocation. - unsafe { - libc::ptrace(libc::PT_DENY_ATTACH, 0, std::ptr::null_mut(), 0); + { + // SAFETY: PT_DENY_ATTACH takes no pointer arguments; null addr and + // zero data are the documented invocation. + let rc = unsafe { libc::ptrace(libc::PT_DENY_ATTACH, 0, std::ptr::null_mut(), 0) }; + if rc != 0 { + let err = std::io::Error::last_os_error(); + log(&format!( + "hardening: PT_DENY_ATTACH failed: {err} — debugger attach not denied" + )); + } } } @@ -195,6 +259,12 @@ pub fn uid_of(name: &str) -> Result { const ID: &str = "/usr/bin/id"; #[cfg(not(target_os = "macos"))] const ID: &str = "id"; + // Trust boundary (audit 2026-08-02 O2): a compromised `id` returning + // a wrong uid would defeat the socket peer-uid ACL. Verify before + // invoking where we invoke by absolute path under SIP (macOS); on + // Linux the lookup is PATH-relative config trust with no signing root. + #[cfg(target_os = "macos")] + crate::keys::verify_external_binary(Path::new(ID))?; let out = std::process::Command::new(ID) .args(["-u", name]) .output() @@ -208,9 +278,16 @@ pub fn uid_of(name: &str) -> Result { .map_err(|_| format!("peer_user {name:?}: `id -u` output not a uid")) } +/// Resolve the keys file path from a `KeysSource` configuration. pub fn keys_path(source: &KeysSource) -> Result { match source { KeysSource::Credential(name) => { + // Same discipline as the exec-config credential source + // (audit 2026-08-02 A8): the name must be a single relative + // path component — otherwise "../../…" would escape + // $CREDENTIALS_DIRECTORY and read an arbitrary root-readable + // file as key material. + crate::exec_config::validate_credential_source_name(name)?; let dir = std::env::var_os("CREDENTIALS_DIRECTORY").ok_or( "keys.credential configured but $CREDENTIALS_DIRECTORY is unset \ (is LoadCredential wired on the postmaster unit?)", @@ -229,6 +306,8 @@ pub fn keys_path(source: &KeysSource) -> Result { } } +/// Bind and listen on all configured credential sockets. Returns +/// a vector of `(UnixListener, path, entry)` triples ready for serving. pub fn acquire_listeners( cfg: &Config, bind: bool, @@ -247,20 +326,27 @@ pub fn acquire_listeners( // only that user (and root) can even reach the socket. Only // meaningful when we run privileged; dev runs skip it. if am_root && let Some(uid) = expected { - rustix::fs::chown(parent, Some(rustix::fs::Uid::from_raw(uid)), None) - .map_err(|e| format!("{}: chown: {e}", parent.display()))?; - // Audit finding #6: use fchmod on the directory fd - // instead of set_permissions on the path to eliminate a - // TOCTOU between chown and chmod. Open the directory - // read-only with O_DIRECTORY, fchmod the fd, close. + // Open the directory and operate on the fd throughout: + // O_NOFOLLOW rejects a symlink at the final component + // (audit 2026-08-02 A1/A2), and fchown/fchmod on the fd + // act on the pinned inode, immune to path swaps + // (audit finding #6). let dir_fd = rustix::fs::open( parent, rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::DIRECTORY + | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC, rustix::fs::Mode::empty(), ) - .map_err(|e| format!("{}: open dir: {e}", parent.display()))?; + .map_err(|e| { + format!( + "{}: open dir: {e} (refusing to follow a symlink)", + parent.display() + ) + })?; + rustix::fs::fchown(&dir_fd, Some(rustix::fs::Uid::from_raw(uid)), None) + .map_err(|e| format!("{}: fchown: {e}", parent.display()))?; rustix::fs::fchmod(&dir_fd, rustix::fs::Mode::from_bits_truncate(0o500)) .map_err(|e| format!("{}: fchmod: {e}", parent.display()))?; } @@ -339,8 +425,13 @@ pub fn acquire_listeners( } } +/// Run the credential daemon: harden the process, load keys, bind +/// sockets, and serve credential requests. Returns on socket error +/// or after all connections are drained (if not socket-activated). pub fn run(args: &Args) -> Result<(), String> { - let raw = fs::read(&args.config).map_err(|e| format!("{}: {e}", args.config.display()))?; + let file = + fs::File::open(&args.config).map_err(|e| format!("{}: {e}", args.config.display()))?; + let raw = read_capped(file, &args.config)?; let cfg: Config = serde_json::from_slice(&raw).map_err(|e| format!("{}: {e}", args.config.display()))?; if cfg.credentials.is_empty() { @@ -372,7 +463,18 @@ pub fn run(args: &Args) -> Result<(), String> { let listeners = acquire_listeners(&cfg, args.bind, &peer_uids)?; let mut handles = Vec::new(); for (listener, path) in listeners { - let entry = cfg.credentials.get(&path).expect("validated above").clone(); + let entry = match cfg.credentials.get(&path) { + Some(e) => e.clone(), + // Unreachable (listeners derive from cfg.credentials), but a + // clear error beats an abort under panic=abort (audit + // 2026-08-02 A22). + None => { + return Err(format!( + "{}: internal: listener path missing from config", + path.display() + )); + } + }; let peer_uid = peer_uids.get(&path).copied().flatten(); let ring = Arc::clone(&ring); let allow = args.allow_nonroot; diff --git a/tests/exec_check.rs b/tests/exec_check.rs index f85be0f..5b9c6e8 100644 --- a/tests/exec_check.rs +++ b/tests/exec_check.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; -use postmaster::config::ExecConfig; +use postmaster::exec_config::ExecConfig; fn repo_root() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf() diff --git a/tests/exec_conformance.rs b/tests/exec_conformance.rs index f71886e..e9935c1 100644 --- a/tests/exec_conformance.rs +++ b/tests/exec_conformance.rs @@ -660,3 +660,74 @@ fn verify_keys_aborts_on_stale_keys_with_strict_false() { "expected '--verify-keys failed' in stderr, got: {stderr}" ); } + +#[test] +fn verify_keys_aborts_on_partial_failure_with_strict_false() { + // Audit 2026-08-02 A3: with strict:false, resolution silently skips + // undecryptable values. When SOME values still decrypt, the resolved + // set is non-empty and the old freshness check passed — the child + // launched with a partial secret set. --verify-keys must now abort + // on any recorded skip. + let d = common::tmpdir("verifykeys-partial"); + let other_sk_hex = "33".repeat(32); + let other_sk_bytes = hex::decode(&other_sk_hex).unwrap(); + let other_sk = ecies::SecretKey::parse_slice(&other_sk_bytes).unwrap(); + let other_pk = ecies::PublicKey::from_secret_key(&other_sk); + let stale_ct = ecies::encrypt(&other_pk.serialize_compressed(), b"stale-secret").unwrap(); + let stale_b64 = { + use base64::Engine; + base64::engine::general_purpose::STANDARD.encode(stale_ct) + }; + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + // Decrypts with the keyring's key — the resolved set is + // non-empty, which is what fooled the old check. + format!("SECRET_GOOD=\"{}\"", common::enc("good-secret")), + // Encrypted to a key NOT in the keyring — skipped under + // strict:false. This is the partial-rotation case. + format!("SECRET_STALE=\"encrypted:{stale_b64}\""), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"strict":false}}"#, + keys.display(), + env.display() + ), + ); + // Without --verify-keys the partial set launches silently: + // SECRET_GOOD is served, SECRET_STALE is dropped. + let out_no_verify = run_exec(&cfg, "test \"$SECRET_GOOD\" = good-secret", &[]); + assert!( + out_no_verify.status.success(), + "without --verify-keys, strict:false should silently serve the partial set: {}", + String::from_utf8_lossy(&out_no_verify.stderr) + ); + + // With --verify-keys, the recorded skip must abort the launch. + let mut c = Command::new(env!("CARGO_BIN_EXE_postmaster")); + c.args(["exec", "--config"]) + .arg(&cfg) + .args(["--verify-keys", "--", "true"]) + .env_remove("SECRET_GOOD") + .env_remove("SECRET_STALE"); + let out = c.output().unwrap(); + assert!( + !out.status.success(), + "--verify-keys should abort on a partial decryption failure" + ); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("--verify-keys failed"), + "expected '--verify-keys failed' in stderr, got: {stderr}" + ); + assert!( + stderr.contains("SECRET_STALE"), + "expected the skipped key name in stderr, got: {stderr}" + ); +} From 90df6fbef22aeb54c382ea2b68f82c0f64e70fb6 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Wed, 5 Aug 2026 03:00:50 -0500 Subject: [PATCH 02/47] nix: fill cargoLock.outputHashes for the git-pinned ecies dep Fetch hash of the aad-support fork at rev 81e1b84, determined via the fake-hash trick on a nix-equipped machine. Replaces the placeholder fill-in instructions in package.nix and nixpkgs-package.nix. --- nixpkgs-package.nix | 8 ++++---- package.nix | 10 ++++------ 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/nixpkgs-package.nix b/nixpkgs-package.nix index 2456a91..fd699c4 100644 --- a/nixpkgs-package.nix +++ b/nixpkgs-package.nix @@ -38,10 +38,10 @@ rustPlatform.buildRustPackage rec { cargoLock = { lockFile = src + "/postmaster/Cargo.lock"; - # While ecies is git-pinned via [patch.crates-io] (audit 2026-08-02 A7), - # this also needs: outputHashes."ecies-0.2.11" = "sha256-…"; (fill via - # the fake-hash trick). Unneeded again once the upstream ecies PR ships - # on crates.io and the patch section is dropped. + # While ecies is git-pinned via [patch.crates-io] (audit 2026-08-02 A7): + # the git dep's fetch hash. Drop once the upstream ecies PR (ecies/rs#159) + # ships on crates.io and the patch section is removed. + outputHashes."ecies-0.2.11" = "sha256-FOKSWQNJ9dZbQZdLI49o1OzeFoS3isQKchylQT/FaFk="; }; meta = { diff --git a/package.nix b/package.nix index b5ef214..2787fd9 100644 --- a/package.nix +++ b/package.nix @@ -26,12 +26,10 @@ rustPlatform.buildRustPackage { }; cargoLock.lockFile = ./Cargo.lock; # Cargo.lock currently pins ecies to a git rev (see [patch.crates-io] in - # Cargo.toml, audit 2026-08-02 A7), so importCargoLock additionally needs: - # cargoLock.outputHashes."ecies-0.2.11" = "sha256-…"; - # Fill it in on a machine with nix using the fake-hash trick: set a dummy - # (sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=), run `just - # flake-check`, and copy the "got:" hash from the error. Drop this again - # when the upstream ecies PR ships on crates.io and the patch is removed. + # Cargo.toml, audit 2026-08-02 A7), so importCargoLock needs the git dep's + # fetch hash. Drop this again when the upstream ecies PR (ecies/rs#159) + # ships on crates.io and the patch section is removed. + cargoLock.outputHashes."ecies-0.2.11" = "sha256-FOKSWQNJ9dZbQZdLI49o1OzeFoS3isQKchylQT/FaFk="; meta = { description = cargoToml.package.description; From 659e54832d5e2bcb53f9e29ace989df94345fa6d Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Wed, 5 Aug 2026 03:32:12 -0500 Subject: [PATCH 03/47] docs: sweep for statements made stale by the 2026-08-02 audit remediation - keychain reads described as "via security(1)" -> Security.framework API (README, architecture/postmaster.md, getting-started/key-provisioning.md) [A17] - launcher-contract key_var_for: lossy suffix mapping -> hard error for anything outside [A-Za-z0-9_] (no aliasing) [A20] - threat-model fd-closure: drop the "5 sites" count; dotenvy no longer opens its own fds (from_read_iter on postmaster-opened fds) [A13] - dependency policy: 8 -> 10 direct deps, add security-framework (macOS) and a note on the ecies fork git+rev pin (ecies/rs#159) - materialization-abi conformance list: drop the cryptographically unbound "or profile" leg of the replay case - cleanup: document the .postmaster-managed sentinel guard in the cleanup rustdoc, HELP_CLEANUP, Invocation::Cleanup, and cli.md [A19] - ramdisk.rs: drop the obsolete /usr/bin/security analogy mdbook build, fmt, clippy, full locked test suite green. --- README.md | 2 +- docs/src/architecture/materialization-abi.md | 2 +- docs/src/architecture/postmaster.md | 8 ++++++-- docs/src/architecture/threat-model.md | 14 +++++++------- docs/src/getting-started/key-provisioning.md | 3 ++- docs/src/reference/cli.md | 6 ++++++ docs/src/reference/launcher-contract.md | 7 ++++--- src/config.rs | 6 +++++- src/key_provisioning.rs | 6 ++++-- src/ramdisk.rs | 2 +- 10 files changed, 37 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 84d5281..c77981a 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ fetches from remote systems: - **Files** — a `.env.keys`-format file on local disk (not in the Nix store) - **macOS Keychain** — key material stored as generic-password items, - read natively by postmaster via `security(1)` + read natively by postmaster via the Security.framework API - **Environment** — `DOTENV_PRIVATE_KEY*` variables in the process environment (set by the service manager) diff --git a/docs/src/architecture/materialization-abi.md b/docs/src/architecture/materialization-abi.md index 42a1bc3..32b38db 100644 --- a/docs/src/architecture/materialization-abi.md +++ b/docs/src/architecture/materialization-abi.md @@ -203,7 +203,7 @@ The implementation ships with conformance vectors for: - unknown version - tampered authenticated metadata - wrong local private key -- replayed ciphertext under a different entry name or profile +- replayed ciphertext under a different entry name ## Key sources diff --git a/docs/src/architecture/postmaster.md b/docs/src/architecture/postmaster.md index df27dbe..a2c3045 100644 --- a/docs/src/architecture/postmaster.md +++ b/docs/src/architecture/postmaster.md @@ -180,7 +180,7 @@ How key material reaches postmaster at runtime. - **Files** — a `.env.keys`-format file on local disk (not in the Nix store) - **macOS Keychain** — key material stored as generic-password items, - read natively by postmaster via `security(1)` + read natively by postmaster via the Security.framework API - **Environment** — `DOTENV_PRIVATE_KEY*` variables in the process environment (set by the service manager) @@ -243,7 +243,7 @@ and per-mode injection rules are the cross-binding contract at ## Dependency policy -Postmaster has 8 dependencies: +Postmaster has 10 direct dependencies (8 portable, 2 macOS-only): - `ecies` — crypto (secp256k1 + AES-256-GCM) - `dotenvy` — `.env` file parser @@ -252,8 +252,12 @@ Postmaster has 8 dependencies: - `hex` — key parsing - `rustix` — syscalls (no libc FFI on Linux) - `libc` — macOS only (for `getpeereid` and `PT_DENY_ATTACH`) +- `security-framework` — macOS only (Security.framework keychain reads) - `zeroize` — secret memory wiping +(`ecies` is currently a git+rev pin of the author's fork via +`[patch.crates-io]`, pending upstream PR ecies/rs#159.) + No CLI parsing library (clap, etc.). No async runtime. No OpenSSL. No network client. No plugin system. The dependency set is intentionally minimal: smaller binary, smaller attack surface, diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index 744416a..54b890b 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -461,13 +461,13 @@ as the ramdisk. ### fd closure before execvp — Mitigated -`OFlags::CLOEXEC` is set on all `rustix::fs::open` calls (5 sites) — -the kernel automatically closes these on execvp, preventing the child -from inheriting postmaster's open file descriptors. Third-party code -(e.g., dotenvy) may open fds without `CLOEXEC`; a `pre_exec` hook to -close those was considered but not implemented because it requires -unsafe code or a new cross-platform dependency. Postmaster's own fds -are fully covered. +`OFlags::CLOEXEC` is set on every file descriptor postmaster opens (all +`rustix::fs::open`/`openat` sites) — the kernel automatically closes +these on execvp, preventing the child from inheriting postmaster's open +file descriptors. Third-party parsers never open their own fds in +postmaster's paths: dotenvy is only invoked as `dotenvy::from_read_iter` +on fds postmaster itself opened (`O_NOFOLLOW | CLOEXEC`). Postmaster's +own fds are fully covered. ### Secrets directory path exposure — Mitigated diff --git a/docs/src/getting-started/key-provisioning.md b/docs/src/getting-started/key-provisioning.md index 8d96dd4..85942a1 100644 --- a/docs/src/getting-started/key-provisioning.md +++ b/docs/src/getting-started/key-provisioning.md @@ -93,7 +93,8 @@ $ security add-generic-password -a DOTENV_PRIVATE_KEY_PRODUCTION \ ``` No file on disk — keys live as generic-password items in the System -keychain. Postmaster reads them natively via `security(1)`. +keychain. Postmaster reads them natively via the Security.framework +API (`security-framework` crate). ## Rotation diff --git a/docs/src/reference/cli.md b/docs/src/reference/cli.md index 86b52a2..5a329b4 100644 --- a/docs/src/reference/cli.md +++ b/docs/src/reference/cli.md @@ -114,6 +114,12 @@ $ postmaster cleanup --config | --- | --- | | `--config ` | Path to `exec.json` (reads `secrets_dir` from config) | +Safety guard: cleanup refuses to bulk-delete a **non-empty** directory +that lacks the `.postmaster-managed` sentinel file (dropped by postmaster +when it writes there) — a misconfigured `secrets_dir` can never wipe a +directory postmaster doesn't manage. Empty or missing directories are +fine. + Wired to `ExecStopPost` in systemd by the Nix module. On macOS, the ramdisk destruction handles cleanup automatically when the launchd job stops. diff --git a/docs/src/reference/launcher-contract.md b/docs/src/reference/launcher-contract.md index 5ec24d6..af82739 100644 --- a/docs/src/reference/launcher-contract.md +++ b/docs/src/reference/launcher-contract.md @@ -272,9 +272,10 @@ is exercised directly in `tests/exec_conformance.rs` `key_var_for` maps an env-file name to the private-key variable it needs: `.env` → `DOTENV_PRIVATE_KEY`; `.env.production` → -`DOTENV_PRIVATE_KEY_PRODUCTION`; non-alphanumeric characters in the -environment suffix become `_` and the whole suffix is upper-cased. A file -name that doesn't start with `.env` is a hard parse error. +`DOTENV_PRIVATE_KEY_PRODUCTION`. The environment suffix must be non-empty +and contain only `[A-Za-z0-9_]` after upper-casing — anything else is a +hard parse error (no lossy mapping: `.env..x` and `.env._x` must never +alias). A file name that doesn't start with `.env` is a hard parse error. ## Per-mode injected variables diff --git a/src/config.rs b/src/config.rs index 7657afa..a9143e1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -102,7 +102,9 @@ pub enum Invocation { /// from the secrets_dir configured in the exec config. Intended for /// `ExecStopPost` in systemd or equivalent lifecycle hooks in other /// service managers. Does not decrypt — only removes files that - /// postmaster would have written. + /// postmaster would have written. Bulk removal is refused for a + /// non-empty directory lacking the `.postmaster-managed` sentinel + /// (audit 2026-08-02 A19). Cleanup { /// Path to the exec config JSON. config: PathBuf, @@ -195,6 +197,8 @@ Reads the exec config, extracts secrets_dir, and removes all regular files\n\ in that directory. Intended for ExecStopPost in systemd or equivalent\n\ lifecycle hooks in other service managers.\n\n\ Does not decrypt — only removes files that postmaster would have written.\n\ +Safety guard: a NON-EMPTY directory without a .postmaster-managed sentinel\n\ +file is left untouched (postmaster only bulk-deletes directories it manages).\n\ Safe to run even if the directory is already empty or does not exist.\n\n\ OPTIONS:\n \ --config Exec config JSON (required)\n"; diff --git a/src/key_provisioning.rs b/src/key_provisioning.rs index 888d541..8bec9a5 100644 --- a/src/key_provisioning.rs +++ b/src/key_provisioning.rs @@ -460,8 +460,10 @@ pub fn setup( /// `postmaster cleanup`: remove all secret files from the secrets_dir /// configured in the exec config. Intended for `ExecStopPost` in systemd /// or equivalent lifecycle hooks. Does not decrypt — only removes files -/// that postmaster would have written. Safe to run even if the directory -/// is empty or does not exist. +/// that postmaster would have written. Bulk removal is guarded by the +/// `.postmaster-managed` sentinel: a non-empty directory lacking it is +/// refused (postmaster only bulk-deletes directories it manages). Safe +/// to run even if the directory is empty or does not exist. pub fn cleanup(config_path: &Path) -> Result<(), String> { let cfg = crate::launcher::parse_exec_config(config_path)?; let dir = cfg diff --git a/src/ramdisk.rs b/src/ramdisk.rs index 7d89e2a..568103d 100644 --- a/src/ramdisk.rs +++ b/src/ramdisk.rs @@ -83,7 +83,7 @@ pub fn verify_ramdisk(mount_point: &Path, secrets_dir: &Path) -> Result<(), Stri // Trust boundary (audit 2026-08-02 O2): a compromised /sbin/mount or // hdiutil could report persistent disk as the RAM-backed postmaster // ramdisk and let plaintext land on persistent storage. Verify both - // helpers before invoking, same as /usr/bin/security. + // helpers before invoking. crate::keys::verify_external_binary(Path::new("/sbin/mount"))?; crate::keys::verify_external_binary(Path::new("/usr/bin/hdiutil"))?; let out = std::process::Command::new("/sbin/mount") From 6fdb5af6858134ae462f1f4f6511eaa9b6450cb4 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Wed, 5 Aug 2026 03:41:50 -0500 Subject: [PATCH 04/47] docs: remove stale mdbook-build-issue.md scratch note Investigation note left over from the 2026-08-02 audit session. The issue it describes (SUMMARY.md referencing a missing changelog.md) is resolved by the just docs recipe, which copies the root CHANGELOG.md into docs/src before mdbook build and removes it after. --- docs/mdbook-build-issue.md | 84 -------------------------------------- 1 file changed, 84 deletions(-) delete mode 100644 docs/mdbook-build-issue.md diff --git a/docs/mdbook-build-issue.md b/docs/mdbook-build-issue.md deleted file mode 100644 index 8d4621b..0000000 --- a/docs/mdbook-build-issue.md +++ /dev/null @@ -1,84 +0,0 @@ -# mdbook build is broken: SUMMARY.md references a missing `changelog.md` - -> **Status:** Pre-existing — not introduced by any recent documentation -> edits. It blocks `mdbook build docs`, so the rendered site under -> `docs/book/` is stale and cannot be regenerated until resolved. - -## Summary - -`docs/src/SUMMARY.md` declares a `Changelog` chapter pointing at -`./changelog.md`, which resolves to `docs/src/changelog.md` — a file that -does not exist. The project's changelog actually lives at the repository -root (`CHANGELOG.md`). mdbook fails fast on the missing chapter and emits -no rendered output. - -## Reproduction - -```console -$ mdbook build docs -ERROR failed to read chapter `./changelog.md` - Caused by: No such file or directory (os error 2) -``` - -## Evidence - -- `docs/src/SUMMARY.md:24` → `- [Changelog](./changelog.md)` -- `docs/src/changelog.md` → **missing** (`No such file or directory`) -- `CHANGELOG.md` (repo root) → present (~2.8 KB) -- `docs/book/` is `.gitignore`d (generated output), so this affects only - local/CI rendering, not committed source. - -## Impact - -- `mdbook build docs` and `mdbook serve docs` fail; no rendered book is - produced. -- Edits to the markdown source under `docs/src/` (e.g. `getting-started/`) - do **not** propagate to the rendered HTML until this is fixed. -- The gitignored `docs/book/` is frozen at whatever was last successfully - built. - -## Fix options (in order of preference) - -### 1. Include the root changelog via mdbook `{{#include}}` (recommended) - -Create `docs/src/changelog.md` as a thin page that pulls in the root file, -keeping a single source of truth. `SUMMARY.md` stays as-is (`./changelog.md` -now exists): - -```markdown -# Changelog - -{{#include ../../CHANGELOG.md}} -``` - -mdbook resolves the include at build time; the root `CHANGELOG.md` remains -authoritative and there is no duplicated content to drift. - -### 2. Repoint SUMMARY.md at the root file - -Change `docs/src/SUMMARY.md:24` to: - -```markdown -- [Changelog](../../CHANGELOG.md) -``` - -Caveat: verify mdbook accepts a chapter path outside `src/` (it generally -does, but worth confirming on your mdbook version). - -### 3. Symlink - -`docs/src/changelog.md` → `../../CHANGELOG.md`. Single source of truth, but -symlinks can be awkward across platforms/git checkouts, and mdbook's -handling of symlinked chapters should be confirmed. - -### 4. Copy via a pre-build step - -Have the `Justfile` copy `CHANGELOG.md` → `docs/src/changelog.md` before -`mdbook build`. Simple, but introduces a duplicate that can drift unless -the copy is automated and enforced. - -## Recommendation - -**Option 1 (`{{#include}}`)** — idiomatic mdbook, no duplication, root -`CHANGELOG.md` stays the single source of truth, and `SUMMARY.md` needs no -change. From 5aee321060f7a2bac9751bb5bc3e40d5d9634261 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Wed, 5 Aug 2026 03:53:46 -0500 Subject: [PATCH 05/47] =?UTF-8?q?deps:=20fold=20open=20dependabot=20PRs=20?= =?UTF-8?q?=E2=80=94=20base64=200.23=20+=20minor-patch=20group?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - base64 0.22 -> 0.23 (supersedes PR #5; the lock resolves 0.23.1) - cargo update for the minor/patch set: libc 0.2.189, serde family 1.0.229, serde_json 1.0.151, syn 2.0.119 + 3.0.3, plus other semver-compatible bumps (supersedes PR #4) - PRs #1-#3 are moot on this branch: actions/checkout is pinned by sha to exactly v7's commit; actions/cache and DeterminateSystems/nix-installer-action were removed in the workflow rewrite (nix is installed via the official nixos.org script) Verified: fmt, clippy (macOS + x86_64-linux-gnu + release, -D warnings), full locked test suite, cargo deny, cargo audit. --- Cargo.lock | 83 +++++++++++++++++++++++++++++++----------------------- Cargo.toml | 2 +- 2 files changed, 48 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e62c504..454b39f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -45,15 +45,15 @@ checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" [[package]] name = "base64" -version = "0.22.1" +version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" [[package]] name = "bitflags" -version = "2.13.0" +version = "2.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" [[package]] name = "block-buffer" @@ -238,21 +238,21 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.32" +version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" +checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7" [[package]] name = "futures-task" -version = "0.3.32" +version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" +checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109" [[package]] name = "futures-util" -version = "0.3.32" +version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa" dependencies = [ "futures-core", "futures-task", @@ -368,9 +368,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.186" +version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" [[package]] name = "linux-raw-sys" @@ -389,9 +389,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.8.2" +version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "once_cell" @@ -452,9 +452,9 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.13.1" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" +checksum = "3d20d5497ef88037a52ff98267d066e7f11fcc5e99bbfbd58a42336193aacec3" [[package]] name = "postmaster" @@ -474,18 +474,18 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.106" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.46" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -523,9 +523,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" [[package]] name = "scopeguard" @@ -571,9 +571,9 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", "serde_derive", @@ -581,29 +581,29 @@ dependencies = [ [[package]] name = "serde_core" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.3", ] [[package]] name = "serde_json" -version = "1.0.150" +version = "1.0.151" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" dependencies = [ "itoa", "memchr", @@ -643,9 +643,20 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "2.0.118" +version = "2.0.119" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" dependencies = [ "proc-macro2", "quote", @@ -718,7 +729,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 2.0.119", "wasm-bindgen-shared", ] @@ -754,6 +765,6 @@ checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" [[package]] name = "zmij" -version = "1.0.21" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index 2ab3515..c6c7afb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -95,7 +95,7 @@ ecies = { version = "0.2.11", default-features = false, features = ["pure", "sec dotenvy = "0.15" serde = { version = "1", features = ["derive"] } serde_json = "1" -base64 = "0.22" +base64 = "0.23" hex = "0.4" zeroize = "1" # Syscall layer: rustix's default linux_raw backend issues raw syscalls from From 3004c8baccb0b8e1b4650cd7151311e6876857b3 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Wed, 5 Aug 2026 05:33:31 -0500 Subject: [PATCH 06/47] ci: conform automation to the repo doctrine (just = single source of truth) Removes doctrine violations introduced during the 2026-08-02 audit remediation: - new in-repo composite .github/actions/setup-nix: downloads the version-pinned official Nix installer (2.34.7), verifies it against a committed sha256 BEFORE executing (fails closed on mismatch), enables flakes, and appends nix to GITHUB_PATH for later steps (the latter fixes a latent bug: a re-enabled job would have failed with "nix: command not found") - nix.yml and docs.yml drop the inline unpinned curl|sh install and consume the composite - Justfile gains flake-check-eval-all; nix.yml's eval-all-systems step now runs the just recipe instead of a raw nix command No third-party actions anywhere; the only action used remains actions/checkout, pinned by sha. Verified: checksum logic both ways, YAML lint on all automation files, just parses both flake recipes. --- .github/actions/setup-nix/action.yml | 55 ++++++++++++++++++++++++++++ .github/workflows/docs.yml | 14 +------ .github/workflows/nix.yml | 16 +------- Justfile | 4 ++ 4 files changed, 62 insertions(+), 27 deletions(-) create mode 100644 .github/actions/setup-nix/action.yml diff --git a/.github/actions/setup-nix/action.yml b/.github/actions/setup-nix/action.yml new file mode 100644 index 0000000..af39a66 --- /dev/null +++ b/.github/actions/setup-nix/action.yml @@ -0,0 +1,55 @@ +name: Setup Nix +description: >- + Install Nix via the official installer, integrity-verified against a + pinned sha256 before execution, enable flakes, and put nix on PATH for + later steps. In-repo composite: no third-party actions, no unverified + remote code. + +inputs: + installer-version: + description: Nix release version to install. + required: false + default: "2.34.7" + installer-sha256: + description: sha256 of the official install script for installer-version. + required: false + default: "e9d447ce3d2ff62d7ff9cb6ef401de6fa8acb148839dd00f7271945d7b638b14" + +runs: + using: composite + steps: + - name: Install Nix (integrity-verified) + shell: bash + env: + NIX_VERSION: ${{ inputs.installer-version }} + INSTALLER_SHA256: ${{ inputs.installer-sha256 }} + run: | + set -euo pipefail + if command -v nix >/dev/null 2>&1; then + echo "nix already available: $(command -v nix) -> $(nix --version)" + else + url="https://releases.nixos.org/nix/nix-${NIX_VERSION}/install" + tmp="$(mktemp -t nix-install)" + # Verify the pinned digest BEFORE executing: a substituted or + # corrupted installer fails closed here, never runs. + curl -sSfL "$url" -o "$tmp" + if command -v sha256sum >/dev/null 2>&1; then + echo "${INSTALLER_SHA256} ${tmp}" | sha256sum -c - + else + echo "${INSTALLER_SHA256} ${tmp}" | shasum -a 256 -c - + fi + sh "$tmp" install --no-confirm + fi + # The installer does not put nix on PATH for subsequent GHA steps. + if [[ -n "${GITHUB_PATH:-}" ]]; then + echo "/nix/var/nix/profiles/default/bin" >> "$GITHUB_PATH" + fi + + - name: Enable nix-command and flakes + shell: bash + run: | + set -euo pipefail + mkdir -p "$HOME/.config/nix" + if ! grep -q 'experimental-features' "$HOME/.config/nix/nix.conf" 2>/dev/null; then + echo 'experimental-features = nix-command flakes' >> "$HOME/.config/nix/nix.conf" + fi diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index e4c0410..2dc71a0 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -34,19 +34,7 @@ jobs: persist-credentials: false - name: Install Nix - shell: bash - run: | - if ! command -v nix >/dev/null 2>&1; then - curl -sSf -L https://nixos.org/nix/install | sh -s -- install --no-confirm - fi - - - name: Enable nix-command and flakes - shell: bash - run: | - mkdir -p "$HOME/.config/nix" - if ! grep -q 'experimental-features' "$HOME/.config/nix/nix.conf" 2>/dev/null; then - echo 'experimental-features = nix-command flakes' >> "$HOME/.config/nix/nix.conf" - fi + uses: ./.github/actions/setup-nix - name: Install just uses: ./.github/actions/setup-rust diff --git a/.github/workflows/nix.yml b/.github/workflows/nix.yml index e6bd8cc..df9566e 100644 --- a/.github/workflows/nix.yml +++ b/.github/workflows/nix.yml @@ -34,19 +34,7 @@ jobs: persist-credentials: false - name: Install Nix - shell: bash - run: | - if ! command -v nix >/dev/null 2>&1; then - curl -sSf -L https://nixos.org/nix/install | sh -s -- install --no-confirm - fi - - - name: Enable nix-command and flakes - shell: bash - run: | - mkdir -p "$HOME/.config/nix" - if ! grep -q 'experimental-features' "$HOME/.config/nix/nix.conf" 2>/dev/null; then - echo 'experimental-features = nix-command flakes' >> "$HOME/.config/nix/nix.conf" - fi + uses: ./.github/actions/setup-nix - name: Install just uses: ./.github/actions/setup-rust @@ -58,4 +46,4 @@ jobs: run: just flake-check - name: nix flake check (eval-only, all systems) - run: nix flake check --all-systems --no-build + run: just flake-check-eval-all diff --git a/Justfile b/Justfile index d7a8a6a..4d17727 100644 --- a/Justfile +++ b/Justfile @@ -31,6 +31,10 @@ test: flake-check: nix flake check +# Eval-only flake check across all supported systems (no builds) +flake-check-eval-all: + nix flake check --all-systems --no-build + # ============================================================================= # Docs # ============================================================================= From 5e24638d533077e2e6524ad716db62f809bde7a4 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Wed, 5 Aug 2026 06:42:49 -0500 Subject: [PATCH 07/47] refactor: split over-limit files and group modules by domain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pure code motion per the file-size convention (500 soft / 750 danger / 1000 hard); zero behavior change. - keys.rs (902) -> keys/{mod,load,env,keychain,verify}.rs; KeyRing's single inherent impl stays in keys/mod.rs (clippy::multiple_inherent_impl is deny crate-wide) with bodies delegating to pub(super) free fns - key_source.rs -> keys/source.rs; key_provisioning.rs (659) -> keys/provisioning/{mod,setup,cleanup}.rs - config.rs (581) -> cli/{mod,help}.rs - adapter.rs -> adapter/mod.rs; bundle.rs -> adapter/bundle.rs - tests/exec_conformance.rs (733) -> tests/exec_conformance/{main, env_mode,files_mode,keys_verify,bundle}.rs (single test target, same target name, same 16 tests) - Path stability: lib.rs re-exports (pub use cli as config; pub use keys::{source as key_source, provisioning as key_provisioning}; pub use adapter::bundle) — zero call-site changes in launcher/server/etc. - docs: file-path references updated (launcher-contract.md, cli.md) Verified: fmt, clippy (macOS + x86_64-linux-gnu + release, -D warnings), identical test totals (75 lib + 7 exec_check + 16 exec_conformance), cargo deny, cargo audit, mdbook build. --- docs/src/reference/cli.md | 2 +- docs/src/reference/launcher-contract.md | 8 +- src/{ => adapter}/bundle.rs | 0 src/{adapter.rs => adapter/mod.rs} | 2 + src/cli/help.rs | 86 ++ src/{config.rs => cli/mod.rs} | 91 +-- src/keys/env.rs | 107 +++ src/keys/keychain.rs | 35 + src/keys/load.rs | 154 ++++ src/{keys.rs => keys/mod.rs} | 382 +-------- src/keys/provisioning/cleanup.rs | 207 +++++ .../provisioning/mod.rs} | 281 +------ src/keys/provisioning/setup.rs | 80 ++ src/{key_source.rs => keys/source.rs} | 0 src/keys/verify.rs | 127 +++ src/lib.rs | 19 +- tests/exec_conformance.rs | 733 ------------------ tests/exec_conformance/bundle.rs | 5 + tests/exec_conformance/env_mode.rs | 244 ++++++ tests/exec_conformance/files_mode.rs | 147 ++++ tests/exec_conformance/keys_verify.rs | 268 +++++++ tests/exec_conformance/main.rs | 89 +++ 22 files changed, 1605 insertions(+), 1462 deletions(-) rename src/{ => adapter}/bundle.rs (100%) rename src/{adapter.rs => adapter/mod.rs} (99%) create mode 100644 src/cli/help.rs rename src/{config.rs => cli/mod.rs} (78%) create mode 100644 src/keys/env.rs create mode 100644 src/keys/keychain.rs create mode 100644 src/keys/load.rs rename src/{keys.rs => keys/mod.rs} (56%) create mode 100644 src/keys/provisioning/cleanup.rs rename src/{key_provisioning.rs => keys/provisioning/mod.rs} (61%) create mode 100644 src/keys/provisioning/setup.rs rename src/{key_source.rs => keys/source.rs} (100%) create mode 100644 src/keys/verify.rs delete mode 100644 tests/exec_conformance.rs create mode 100644 tests/exec_conformance/bundle.rs create mode 100644 tests/exec_conformance/env_mode.rs create mode 100644 tests/exec_conformance/files_mode.rs create mode 100644 tests/exec_conformance/keys_verify.rs create mode 100644 tests/exec_conformance/main.rs diff --git a/docs/src/reference/cli.md b/docs/src/reference/cli.md index 5a329b4..19e39b3 100644 --- a/docs/src/reference/cli.md +++ b/docs/src/reference/cli.md @@ -2,7 +2,7 @@ All postmaster commands, flags, and exit codes. The CLI is hand-rolled with no external parsing library — every flag below is the complete -set, directly from the argument parser in `config.rs`. +set, directly from the argument parser in `cli/mod.rs`. ## Synopsis diff --git a/docs/src/reference/launcher-contract.md b/docs/src/reference/launcher-contract.md index af82739..42ceddc 100644 --- a/docs/src/reference/launcher-contract.md +++ b/docs/src/reference/launcher-contract.md @@ -49,7 +49,7 @@ binding to emit `exec.json`; it is not privileged over any other binding. described by this document and passes the conformance suite.** Nothing here documents intent or a roadmap; every claim below is true of the committed parser and launcher (`src/exec_config.rs`, -`src/launcher.rs`, `src/keys.rs`) as of this writing. +`src/launcher.rs`, `src/keys/mod.rs`) as of this writing. ### Config to launch flow @@ -214,7 +214,7 @@ decryption happens in that mode; see below. ## Precedence contract -This is the contract `resolve_all` (`src/keys.rs`) implements, +This is the contract `resolve_all` (`src/keys/mod.rs`) implements, verbatim: - **Within one file, the last assignment wins** — ordinary dotenv @@ -267,7 +267,7 @@ ASCII whitespace (spaces, tabs, newlines, carriage returns). If any is present, it is stripped before decoding, so a value that has been line-wrapped decodes identically to the same value on one line. This matches the wire-compatible behavior for line-wrapped encrypted values and -is exercised directly in `tests/exec_conformance.rs` +is exercised directly in `tests/exec_conformance/main.rs` (`wrapped_base64_ciphertext_decrypts`). `key_var_for` maps an env-file name to the private-key variable it needs: @@ -420,7 +420,7 @@ with external secret-management tooling that materializes a ## Conformance -`tests/exec_conformance.rs` is the executable form of this document: +`tests/exec_conformance/main.rs` is the executable form of this document: metacharacter-laden values stay inert across all three modes, process-env-wins-without-overload and overload-reverses-it, rotation with a bogus first key, strict failure refuses to exec, `0600` pointer files diff --git a/src/bundle.rs b/src/adapter/bundle.rs similarity index 100% rename from src/bundle.rs rename to src/adapter/bundle.rs diff --git a/src/adapter.rs b/src/adapter/mod.rs similarity index 99% rename from src/adapter.rs rename to src/adapter/mod.rs index cf8b8a2..ffbca24 100644 --- a/src/adapter.rs +++ b/src/adapter/mod.rs @@ -11,6 +11,8 @@ //! every adapter at compile time — adding a variant is a deliberate act //! that forces all code paths to acknowledge it. +pub mod bundle; + use std::path::Path; /// The key-naming convention for a secret input adapter. diff --git a/src/cli/help.rs b/src/cli/help.rs new file mode 100644 index 0000000..8311799 --- /dev/null +++ b/src/cli/help.rs @@ -0,0 +1,86 @@ +//! Help text constants for the postmaster CLI. + +/// Top-level help text shown by `postmaster --help` or `postmaster help`. +pub const HELP_TOP: &str = "postmaster — standalone secret materialization engine\n\n\ +USAGE:\n \ +postmaster --config [--bind] [--allow-nonroot]\n \ +postmaster fetch \n \ +postmaster exec --config [--check] [--verify-keys] -- [args…]\n \ +postmaster setup --config [--recheck] [--unattended] [--force] [--keys-dir ]\n \ +postmaster help [subcommand]\n \ +postmaster --version\n\n\ +SUBCOMMANDS:\n \ +exec Decrypt secrets and exec a child process with them injected\n \ +fetch Fetch a single secret from a postmaster daemon socket\n \ +setup Verify environment, create keys directory, seed keychain (idempotent)\n \ +help Show help for a subcommand or this message\n\n\ +OPTIONS:\n \ +--config Configuration file (required for serve, exec, setup)\n \ +--bind (serve) Bind listener sockets even if not socket-activated\n \ +--allow-nonroot (serve) Allow non-root connections (dangerous)\n \ +--check (exec) Validate config shape only, no decryption or exec\n \ +--verify-keys (exec) Preflight key freshness check before exec\n \ +--recheck (setup) Verification only, no creation or modification\n \ +--unattended (setup) Non-interactive mode for automation (fail closed)\n \ +--force (setup) Re-create or re-seed even if already correct\n \ +--keys-dir

(setup) Override default keys directory path\n \ +--version, -V Print version and exit\n \ +--help, -h Show this help message\n"; + +/// Help text for the `exec` subcommand. +pub const HELP_EXEC: &str = "postmaster exec — decrypt secrets and exec a child process\n\n\ +USAGE:\n \ +postmaster exec --config [--check] [--verify-keys] -- [args…]\n\n\ +Decrypts the configured env files and/or bundle files using the loaded key\n\ +ring, injects the resolved values into the child environment (or writes them\n\ +as files / credential pointers depending on mode), and execs the command.\n\n\ +OPTIONS:\n \ +--config Exec config JSON (required)\n \ +--check Validate config shape only, no decryption, no exec\n \ +--verify-keys Preflight: test-decrypt one value per env file before exec\n \ +-- Everything after `--` is the child argv (required unless --check)\n\n\ +The config must specify mode (env/files/credentials), key sources, and\n\ +artifact paths. See docs/src/launcher-contract.md for the full contract.\n"; + +/// Help text for the `fetch` subcommand. +pub const HELP_FETCH: &str = "postmaster fetch — fetch a secret from a daemon socket\n\n\ +USAGE:\n \ +postmaster fetch \n\n\ +Connects to a running postmaster daemon's AF_UNIX socket, requests the\n\ +default secret, and writes the decrypted bytes to stdout. Used internally\n\ +by the credentials-mode launcher on macOS (launchd) to pull secrets from\n\ +the daemon into the RAM disk.\n\n\ +The socket path must be a single relative or absolute path to the AF_UNIX\n\ +socket created by `postmaster --config `.\n"; + +/// Help text for the `setup` subcommand. +pub const HELP_SETUP: &str = "postmaster setup — verify environment and create key material\n\n\ +USAGE:\n \ +postmaster setup --config [--recheck] [--unattended] [--force] [--keys-dir ]\n\n\ +Verifies platform prerequisites, creates the keys directory with 0700\n\ +permissions, verifies or creates keys files with 0600, optionally seeds\n\ +keychain items (macOS, interactive), and validates the environment.\n\n\ +Idempotent — each step checks whether the target state is already present\n\ +and correct, and skips if it is. Safe to run on every converge cycle.\n\n\ +OPTIONS:\n \ +--config Exec config JSON (required)\n \ +--recheck Verification only — no creation or modification\n \ +--unattended Non-interactive mode for automation (fail closed, no prompts)\n \ +--force Re-create or re-seed even if already correct\n \ +--keys-dir Override the default keys directory\n\n\ +Default keys directory: /var/lib/postmaster (Linux),\n\ +~/Library/Application Support/postmaster (macOS).\n"; + +/// Help text for the `cleanup` subcommand. +pub const HELP_CLEANUP: &str = "postmaster cleanup — remove secret files from secrets_dir\n\n\ +USAGE:\n \ +postmaster cleanup --config \n\n\ +Reads the exec config, extracts secrets_dir, and removes all regular files\n\ +in that directory. Intended for ExecStopPost in systemd or equivalent\n\ +lifecycle hooks in other service managers.\n\n\ +Does not decrypt — only removes files that postmaster would have written.\n\ +Safety guard: a NON-EMPTY directory without a .postmaster-managed sentinel\n\ +file is left untouched (postmaster only bulk-deletes directories it manages).\n\ +Safe to run even if the directory is already empty or does not exist.\n\n\ +OPTIONS:\n \ +--config Exec config JSON (required)\n"; diff --git a/src/config.rs b/src/cli/mod.rs similarity index 78% rename from src/config.rs rename to src/cli/mod.rs index a9143e1..48d6d84 100644 --- a/src/config.rs +++ b/src/cli/mod.rs @@ -8,6 +8,12 @@ use std::path::PathBuf; use serde::Deserialize; +mod help; + +/// Help text constants, re-exported so `crate::config::HELP_*` keeps +/// resolving via the `cli as config` re-export in `lib.rs`. +pub use help::{HELP_CLEANUP, HELP_EXEC, HELP_FETCH, HELP_SETUP, HELP_TOP}; + /// Full configuration loaded from the JSON file produced by the Nix module. /// Unknown fields are rejected (audit 2026-08-02 A21) — same strictness /// as the exec config. @@ -118,91 +124,6 @@ pub enum Invocation { /// Crate version, resolved at compile time from `CARGO_PKG_VERSION`. pub const VERSION: &str = env!("CARGO_PKG_VERSION"); -/// Top-level help text shown by `postmaster --help` or `postmaster help`. -pub const HELP_TOP: &str = "postmaster — standalone secret materialization engine\n\n\ -USAGE:\n \ -postmaster --config [--bind] [--allow-nonroot]\n \ -postmaster fetch \n \ -postmaster exec --config [--check] [--verify-keys] -- [args…]\n \ -postmaster setup --config [--recheck] [--unattended] [--force] [--keys-dir ]\n \ -postmaster help [subcommand]\n \ -postmaster --version\n\n\ -SUBCOMMANDS:\n \ -exec Decrypt secrets and exec a child process with them injected\n \ -fetch Fetch a single secret from a postmaster daemon socket\n \ -setup Verify environment, create keys directory, seed keychain (idempotent)\n \ -help Show help for a subcommand or this message\n\n\ -OPTIONS:\n \ ---config Configuration file (required for serve, exec, setup)\n \ ---bind (serve) Bind listener sockets even if not socket-activated\n \ ---allow-nonroot (serve) Allow non-root connections (dangerous)\n \ ---check (exec) Validate config shape only, no decryption or exec\n \ ---verify-keys (exec) Preflight key freshness check before exec\n \ ---recheck (setup) Verification only, no creation or modification\n \ ---unattended (setup) Non-interactive mode for automation (fail closed)\n \ ---force (setup) Re-create or re-seed even if already correct\n \ ---keys-dir

(setup) Override default keys directory path\n \ ---version, -V Print version and exit\n \ ---help, -h Show this help message\n"; - -/// Help text for the `exec` subcommand. -pub const HELP_EXEC: &str = "postmaster exec — decrypt secrets and exec a child process\n\n\ -USAGE:\n \ -postmaster exec --config [--check] [--verify-keys] -- [args…]\n\n\ -Decrypts the configured env files and/or bundle files using the loaded key\n\ -ring, injects the resolved values into the child environment (or writes them\n\ -as files / credential pointers depending on mode), and execs the command.\n\n\ -OPTIONS:\n \ ---config Exec config JSON (required)\n \ ---check Validate config shape only, no decryption, no exec\n \ ---verify-keys Preflight: test-decrypt one value per env file before exec\n \ --- Everything after `--` is the child argv (required unless --check)\n\n\ -The config must specify mode (env/files/credentials), key sources, and\n\ -artifact paths. See docs/src/launcher-contract.md for the full contract.\n"; - -/// Help text for the `fetch` subcommand. -pub const HELP_FETCH: &str = "postmaster fetch — fetch a secret from a daemon socket\n\n\ -USAGE:\n \ -postmaster fetch \n\n\ -Connects to a running postmaster daemon's AF_UNIX socket, requests the\n\ -default secret, and writes the decrypted bytes to stdout. Used internally\n\ -by the credentials-mode launcher on macOS (launchd) to pull secrets from\n\ -the daemon into the RAM disk.\n\n\ -The socket path must be a single relative or absolute path to the AF_UNIX\n\ -socket created by `postmaster --config `.\n"; - -/// Help text for the `setup` subcommand. -pub const HELP_SETUP: &str = "postmaster setup — verify environment and create key material\n\n\ -USAGE:\n \ -postmaster setup --config [--recheck] [--unattended] [--force] [--keys-dir ]\n\n\ -Verifies platform prerequisites, creates the keys directory with 0700\n\ -permissions, verifies or creates keys files with 0600, optionally seeds\n\ -keychain items (macOS, interactive), and validates the environment.\n\n\ -Idempotent — each step checks whether the target state is already present\n\ -and correct, and skips if it is. Safe to run on every converge cycle.\n\n\ -OPTIONS:\n \ ---config Exec config JSON (required)\n \ ---recheck Verification only — no creation or modification\n \ ---unattended Non-interactive mode for automation (fail closed, no prompts)\n \ ---force Re-create or re-seed even if already correct\n \ ---keys-dir Override the default keys directory\n\n\ -Default keys directory: /var/lib/postmaster (Linux),\n\ -~/Library/Application Support/postmaster (macOS).\n"; - -/// Help text for the `cleanup` subcommand. -pub const HELP_CLEANUP: &str = "postmaster cleanup — remove secret files from secrets_dir\n\n\ -USAGE:\n \ -postmaster cleanup --config \n\n\ -Reads the exec config, extracts secrets_dir, and removes all regular files\n\ -in that directory. Intended for ExecStopPost in systemd or equivalent\n\ -lifecycle hooks in other service managers.\n\n\ -Does not decrypt — only removes files that postmaster would have written.\n\ -Safety guard: a NON-EMPTY directory without a .postmaster-managed sentinel\n\ -file is left untouched (postmaster only bulk-deletes directories it manages).\n\ -Safe to run even if the directory is already empty or does not exist.\n\n\ -OPTIONS:\n \ ---config Exec config JSON (required)\n"; - /// Short usage string for error messages. pub const USAGE: &str = "usage: postmaster --config [--bind] [--allow-nonroot]\n postmaster fetch \n postmaster exec --config [--check] [--verify-keys]\n postmaster exec --config [--verify-keys] -- [args…]\n postmaster setup --config [--recheck] [--unattended] [--force] [--keys-dir ]\n postmaster cleanup --config "; diff --git a/src/keys/env.rs b/src/keys/env.rs new file mode 100644 index 0000000..2604eea --- /dev/null +++ b/src/keys/env.rs @@ -0,0 +1,107 @@ +//! Process-environment key source (external provisioning). + +use zeroize::Zeroizing; + +use super::KeyRing; +use crate::adapter::KeyNaming; + +/// True for exactly `PREFIX` or `PREFIX_`. A bare +/// prefix match would slurp unrelated variables like +/// `DOTENV_PRIVATE_KEYFOO` as key material (audit 2026-08-02 A16). +fn is_key_var_name(prefix: &str, name: &str) -> bool { + name == prefix + || name + .strip_prefix(prefix) + .is_some_and(|rest| rest.len() > 1 && rest.starts_with('_')) +} + +/// Implementation of [`KeyRing::from_env`]; the contract is documented on +/// the method. +pub(super) fn from_env(naming: KeyNaming) -> Result { + let prefix = naming.key_prefix(); + KeyRing::from_pairs( + std::env::vars() + .filter(|(k, _)| is_key_var_name(prefix, k)) + .map(|(k, v)| (k, Zeroizing::new(v))), + naming, + ) + .map_err(|e| format!("environment: {e}")) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic, unused_qualifications)] +mod tests { + use super::*; + + #[test] + fn is_key_var_name_rules() { + // audit 2026-08-02 A16: only `PREFIX` or `PREFIX_` match; + // prefix-substring collisions are rejected. + let p = "DOTENV_PRIVATE_KEY"; + assert!(is_key_var_name(p, "DOTENV_PRIVATE_KEY")); + assert!(is_key_var_name(p, "DOTENV_PRIVATE_KEY_PRODUCTION")); + assert!(!is_key_var_name(p, "DOTENV_PRIVATE_KEYFOO")); + assert!(!is_key_var_name(p, "DOTENV_PRIVATE_KEY_")); // empty suffix + assert!(!is_key_var_name(p, "DOTENV_PRIVATE_KE")); + assert!(!is_key_var_name(p, "XDOTENV_PRIVATE_KEY")); + } + + #[test] + fn from_env_loads_and_fails_closed() { + // from_env reads ALL DOTENV_PRIVATE_KEY* vars from the process + // environment and delegates to from_pairs. This is a single test + // (not two) because env mutation is global and tests run in + // parallel — two tests mutating DOTENV_PRIVATE_KEY* simultaneously + // would race. Using a unique suffix to avoid collision with any + // ambient vars in the test runner. + let var_name = "DOTENV_PRIVATE_KEY_TESTFROMENV"; + let key_hex = "aa".repeat(32); + + // Positive path: set a valid key, from_env succeeds. + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). This test does not spawn threads and the var name + // is unique, so no concurrent test mutates the same var. + unsafe { + std::env::set_var(var_name, &key_hex); + } + let ring = KeyRing::from_env(KeyNaming::Env); + unsafe { + std::env::remove_var(var_name); + } + let ring = ring.expect("from_env should succeed with a valid key set"); + let candidates = ring + .0 + .get(var_name) + .expect("ring should contain the key we set"); + assert_eq!(candidates.len(), 1, "exactly one candidate expected"); + assert_eq!(&candidates[0][..], &[0xaa; 32]); + + // Negative path: set an invalid hex value, from_env fails closed + // with an "environment:" prefixed error. + unsafe { + std::env::set_var(var_name, "not-valid-hex-at-all"); + } + let err = KeyRing::from_env(KeyNaming::Env); + unsafe { + std::env::remove_var(var_name); + } + let err = err.expect_err("from_env should fail on invalid hex"); + assert!( + err.starts_with("environment:"), + "expected 'environment:' prefix, got: {err}" + ); + + // Also verify the from_pairs empty-error path directly: no + // DOTENV_PRIVATE_KEY* entries at all should be an error. + assert!( + KeyRing::from_pairs( + [( + "NOT_A_DOTENV_KEY".to_string(), + Zeroizing::new("x".to_string()) + )], + KeyNaming::Env, + ) + .is_err() + ); + } +} diff --git a/src/keys/keychain.rs b/src/keys/keychain.rs new file mode 100644 index 0000000..048408e --- /dev/null +++ b/src/keys/keychain.rs @@ -0,0 +1,35 @@ +//! macOS System keychain key source. + +use zeroize::Zeroizing; + +use super::KeyRing; +use crate::adapter::KeyNaming; + +/// Implementation of [`KeyRing::from_keychain`]; the contract is +/// documented on the method. +#[cfg(target_os = "macos")] +pub(super) fn from_keychain( + service: &str, + vars: &[String], + naming: KeyNaming, +) -> Result { + // Reads go through the Security.framework API, not the + // /usr/bin/security CLI (F1 direction): no subprocess, no argv, + // and no stdout buffer holding key material — the UTF-8-failure + // path validates from a borrow so the error never carries the + // bytes (audit 2026-08-02 A17). + let mut pairs = Vec::new(); + for var in vars { + let bytes = Zeroizing::new( + security_framework::passwords::get_generic_password(service, var).map_err(|_| { + format!("keychain {service}: no item for account {var} (fail closed)") + })?, + ); + let s = std::str::from_utf8(&bytes[..]) + .map_err(|_| format!("keychain {service}/{var}: not UTF-8"))?; + // from_pairs trims each comma-separated candidate itself, so + // no separate trim is needed here. + pairs.push((var.clone(), Zeroizing::new(s.to_string()))); + } + KeyRing::from_pairs(pairs, naming).map_err(|e| format!("keychain {service}: {e}")) +} diff --git a/src/keys/load.rs b/src/keys/load.rs new file mode 100644 index 0000000..9a59893 --- /dev/null +++ b/src/keys/load.rs @@ -0,0 +1,154 @@ +//! `.env.keys` file loading with on-fd stat hardening (no TOCTOU window). + +use std::path::Path; + +use zeroize::Zeroizing; + +use super::KeyRing; +use crate::adapter::KeyNaming; + +/// Implementation of [`KeyRing::load`]; the contract is documented on the +/// method. +pub(super) fn load(path: &Path, naming: KeyNaming) -> Result { + let oflags = + rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC; + let fd = rustix::fs::open(path, oflags, rustix::fs::Mode::empty()).map_err(|e| { + format!( + "keys file {}: {e} (refusing to follow a symlink)", + path.display() + ) + })?; + let stat = + rustix::fs::fstat(&fd).map_err(|e| format!("keys file {}: fstat: {e}", path.display()))?; + let mode = rustix::fs::Mode::from_bits_truncate(stat.st_mode); + // Reject group or world accessibility. 0o077 masks both RWXG and RWXO. + if mode.intersects(rustix::fs::Mode::RWXG | rustix::fs::Mode::RWXO) { + return Err(format!( + "keys file {}: permissions {:#o} are group/world accessible; expected 0400 or 0600 (fail closed)", + path.display(), + stat.st_mode + )); + } + let euid = rustix::process::geteuid().as_raw(); + if stat.st_uid != euid { + return Err(format!( + "keys file {}: owned by uid {} but postmaster euid is {euid} (fail closed)", + path.display(), + stat.st_uid + )); + } + let file = std::fs::File::from(fd); + let iter = dotenvy::from_read_iter(file); + let mut pairs = Vec::new(); + for item in iter { + let (k, v) = item.map_err(|e| format!("keys file {}: {e}", path.display()))?; + pairs.push((k, Zeroizing::new(v))); + } + KeyRing::from_pairs(pairs, naming).map_err(|e| format!("keys file {}: {e}", path.display())) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic, unused_qualifications)] +mod tests { + use super::*; + use crate::keys::tests::{tdir, with_temp_keys}; + use std::io::Write; + + #[test] + fn load_rejects_bad_hex() { + let content = "DOTENV_PRIVATE_KEY=not-hex\n"; + with_temp_keys(content, |p| match KeyRing::load(p, KeyNaming::Env) { + Err(e) if e.contains("not valid hex") => {} + other => panic!("expected bad hex error, got {other:?}"), + }); + } + + #[test] + fn load_rejects_world_readable_keys_file() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir(); + let path = dir.join(format!( + "postmaster-test-keys-worldread-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + { + let mut f = std::fs::File::create(&path).unwrap(); + writeln!(f, "DOTENV_PRIVATE_KEY={}", "11".repeat(32)).unwrap(); + } + // 0644: world-readable — must be rejected. + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + match KeyRing::load(&path, KeyNaming::Env) { + Err(e) if e.contains("group/world accessible") => {} + other => panic!("expected group/world permission error, got {other:?}"), + } + let _ = std::fs::remove_file(&path); + } + + #[test] + fn load_rejects_group_readable_keys_file() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir(); + let path = dir.join(format!( + "postmaster-test-keys-groupread-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + { + let mut f = std::fs::File::create(&path).unwrap(); + writeln!(f, "DOTENV_PRIVATE_KEY={}", "11".repeat(32)).unwrap(); + } + // 0640: group-readable — must be rejected. + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap(); + match KeyRing::load(&path, KeyNaming::Env) { + Err(e) if e.contains("group/world accessible") => {} + other => panic!("expected group permission error, got {other:?}"), + } + let _ = std::fs::remove_file(&path); + } + + #[test] + fn load_rejects_symlink_keys_file() { + let dir = tdir("symlink-keys"); + let real = dir.join("real-keys"); + std::fs::write(&real, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o600)).unwrap(); + let link = dir.join(".env.keys"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + match KeyRing::load(&link, KeyNaming::Env) { + Err(e) if e.contains("symlink") => {} + other => panic!("expected symlink rejection error, got {other:?}"), + } + } + + #[test] + fn load_accepts_0600_keys_file() { + // Sanity: a properly locked-down keys file (0600, owned by euid) + // loads normally. This guards against false positives from the + // permission and ownership checks. + let content = format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32)); + with_temp_keys(&content, |p| { + KeyRing::load(p, KeyNaming::Env).expect("0600 keys file owned by euid should load"); + }); + } + + #[test] + fn load_accepts_0400_keys_file() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir(); + let path = dir.join(format!( + "postmaster-test-keys-0400-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + { + let mut f = std::fs::File::create(&path).unwrap(); + writeln!(f, "DOTENV_PRIVATE_KEY={}", "11".repeat(32)).unwrap(); + } + // 0400: read-only by owner — stricter than 0600, must pass. + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400)).unwrap(); + KeyRing::load(&path, KeyNaming::Env).expect("0400 keys file owned by euid should load"); + let _ = std::fs::remove_file(&path); + } +} diff --git a/src/keys.rs b/src/keys/mod.rs similarity index 56% rename from src/keys.rs rename to src/keys/mod.rs index a7abc02..b5e6660 100644 --- a/src/keys.rs +++ b/src/keys/mod.rs @@ -4,7 +4,7 @@ //! Plaintext values (from `dotenvx set --plain`) are passed through. //! //! Key-naming conventions are abstracted via the `KeyNaming` trait -//! (see `adapter.rs`), so the core logic is adapter-neutral. The `.env` +//! (see `adapter/mod.rs`), so the core logic is adapter-neutral. The `.env` //! adapter's `KeyNaming::Env` is the first implementation. use std::collections::HashMap; @@ -17,28 +17,30 @@ use zeroize::{Zeroize, Zeroizing}; use crate::adapter::KeyNaming; use crate::config::Entry; +mod env; +#[cfg(target_os = "macos")] +mod keychain; +mod load; +pub mod provisioning; +pub mod source; +mod verify; + +/// Re-exported so `crate::keys::verify_external_binary` keeps resolving. +pub use verify::verify_external_binary; + /// Full variable name (adapter-specific, e.g. DOTENV_PRIVATE_KEY[_]) /// → candidate secret keys. Multiple candidates per name come from /// comma-separated rotation convention; decryption tries each in order. #[derive(Debug)] pub struct KeyRing(HashMap>>); -/// True for exactly `PREFIX` or `PREFIX_`. A bare -/// prefix match would slurp unrelated variables like -/// `DOTENV_PRIVATE_KEYFOO` as key material (audit 2026-08-02 A16). -fn is_key_var_name(prefix: &str, name: &str) -> bool { - name == prefix - || name - .strip_prefix(prefix) - .is_some_and(|rest| rest.len() > 1 && rest.starts_with('_')) -} - impl KeyRing { /// Look up candidate keys for a given key variable name. /// Returns `None` if the variable has no candidates in the ring. pub fn candidates(&self, var: &str) -> Option<&[Zeroizing<[u8; 32]>]> { self.0.get(var).map(|v| v.as_slice()) } + /// Load a `.env.keys` file from `path` and build a key ring. /// /// Security invariants enforced on the opened file (all checked on the @@ -50,41 +52,7 @@ impl KeyRing { /// process on the host; fail closed instead. /// - `st_uid == euid`: the file must be owned by the service user. pub fn load(path: &Path, naming: KeyNaming) -> Result { - let oflags = - rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC; - let fd = rustix::fs::open(path, oflags, rustix::fs::Mode::empty()).map_err(|e| { - format!( - "keys file {}: {e} (refusing to follow a symlink)", - path.display() - ) - })?; - let stat = rustix::fs::fstat(&fd) - .map_err(|e| format!("keys file {}: fstat: {e}", path.display()))?; - let mode = rustix::fs::Mode::from_bits_truncate(stat.st_mode); - // Reject group or world accessibility. 0o077 masks both RWXG and RWXO. - if mode.intersects(rustix::fs::Mode::RWXG | rustix::fs::Mode::RWXO) { - return Err(format!( - "keys file {}: permissions {:#o} are group/world accessible; expected 0400 or 0600 (fail closed)", - path.display(), - stat.st_mode - )); - } - let euid = rustix::process::geteuid().as_raw(); - if stat.st_uid != euid { - return Err(format!( - "keys file {}: owned by uid {} but postmaster euid is {euid} (fail closed)", - path.display(), - stat.st_uid - )); - } - let file = std::fs::File::from(fd); - let iter = dotenvy::from_read_iter(file); - let mut pairs = Vec::new(); - for item in iter { - let (k, v) = item.map_err(|e| format!("keys file {}: {e}", path.display()))?; - pairs.push((k, Zeroizing::new(v))); - } - Self::from_pairs(pairs, naming).map_err(|e| format!("keys file {}: {e}", path.display())) + load::load(path, naming) } /// Core parser shared by every key source: keep keys matching the @@ -137,14 +105,7 @@ impl KeyRing { /// provisioning; `key.file = null` in the module). Reads all /// variables matching the adapter's key prefix. pub fn from_env(naming: KeyNaming) -> Result { - let prefix = naming.key_prefix(); - Self::from_pairs( - std::env::vars() - .filter(|(k, _)| is_key_var_name(prefix, k)) - .map(|(k, v)| (k, Zeroizing::new(v))), - naming, - ) - .map_err(|e| format!("environment: {e}")) + env::from_env(naming) } /// macOS System keychain: one generic-password item per variable, @@ -157,95 +118,8 @@ impl KeyRing { vars: &[String], naming: KeyNaming, ) -> Result { - // Reads go through the Security.framework API, not the - // /usr/bin/security CLI (F1 direction): no subprocess, no argv, - // and no stdout buffer holding key material — the UTF-8-failure - // path validates from a borrow so the error never carries the - // bytes (audit 2026-08-02 A17). - let mut pairs = Vec::new(); - for var in vars { - let bytes = Zeroizing::new( - security_framework::passwords::get_generic_password(service, var).map_err( - |_| format!("keychain {service}: no item for account {var} (fail closed)"), - )?, - ); - let s = std::str::from_utf8(&bytes[..]) - .map_err(|_| format!("keychain {service}/{var}: not UTF-8"))?; - // from_pairs trims each comma-separated candidate itself, so - // no separate trim is needed here. - pairs.push((var.clone(), Zeroizing::new(s.to_string()))); - } - Self::from_pairs(pairs, naming).map_err(|e| format!("keychain {service}: {e}")) - } -} - -/// Verify the integrity of an external binary before invoking it as part -/// of a secret-handling path. This is a defense-in-depth trust boundary -/// check (audit finding #3): the binary path is a trust root, and we -/// verify it has not been tampered with before exec. -/// -/// On macOS: `codesign -v ` verifies the code signature. The binary -/// is additionally SIP-protected, so this catches a hypothetical SIP -/// bypass or a misconfigured environment. -/// -/// On Linux: verify the file is a regular file, owned by root (uid 0), -/// and not world-writable. There is no universal code-signing mechanism -/// on Linux, so ownership and permission checks are the practical -/// defense-in-depth boundary. -/// -/// Bootstrap limitation (audit 2026-08-02 O2): on macOS the verifier -/// itself invokes `/usr/bin/codesign`. Self-verifying codesign with -/// codesign is circular — a compromised codesign would vouch for -/// itself — so codesign is trusted via SIP alone. Moving verification -/// onto the Security.framework StaticCode API (the `security-framework` -/// crate route already chosen for keychain access) would remove this -/// residual trust gap. -pub fn verify_external_binary(path: &Path) -> Result<(), String> { - #[cfg(target_os = "macos")] - { - let out = std::process::Command::new("/usr/bin/codesign") - .args(["-v", path.to_str().unwrap_or("")]) - .output() - .map_err(|e| format!("{}: codesign verification failed: {e}", path.display()))?; - if !out.status.success() { - return Err(format!( - "{}: code signature verification failed (audit finding #3 trust boundary)", - path.display() - )); - } + keychain::from_keychain(service, vars, naming) } - #[cfg(not(target_os = "macos"))] - { - use std::os::unix::fs::MetadataExt; - let md = std::fs::symlink_metadata(path) - .map_err(|e| format!("{}: cannot stat external binary: {e}", path.display()))?; - if md.file_type().is_symlink() { - return Err(format!( - "{}: external binary is a symlink; refusing to trust a symlinked binary", - path.display() - )); - } - if !md.is_file() { - return Err(format!( - "{}: external binary is not a regular file", - path.display() - )); - } - if md.uid() != 0 { - return Err(format!( - "{}: external binary owned by uid {} (expected root/0); refusing to trust", - path.display(), - md.uid() - )); - } - if md.mode() & 0o002 != 0 { - return Err(format!( - "{}: external binary is world-writable; refusing to trust", - path.display() - )); - } - } - Ok(()) } /// Shell-identifier check shared with the Nix module's eval-time isIdent. @@ -478,7 +352,8 @@ pub mod tests { use std::io::Write; use std::path::Path; - fn with_temp_keys(content: &str, f: impl FnOnce(&Path)) { + /// Shared with the `load` submodule's tests. + pub fn with_temp_keys(content: &str, f: impl FnOnce(&Path)) { use std::os::unix::fs::PermissionsExt; let dir = std::env::temp_dir(); let path = dir.join(format!( @@ -497,7 +372,8 @@ pub mod tests { let _ = std::fs::remove_file(&path); } - fn tdir(tag: &str) -> std::path::PathBuf { + /// Shared with the `load` submodule's tests. + pub fn tdir(tag: &str) -> std::path::PathBuf { let d = std::env::temp_dir().join(format!("pm-keys-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); @@ -581,171 +457,12 @@ pub mod tests { ); } - #[test] - fn load_rejects_bad_hex() { - let content = "DOTENV_PRIVATE_KEY=not-hex\n"; - with_temp_keys(content, |p| match KeyRing::load(p, KeyNaming::Env) { - Err(e) if e.contains("not valid hex") => {} - other => panic!("expected bad hex error, got {other:?}"), - }); - } - - #[test] - fn load_rejects_world_readable_keys_file() { - use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir(); - let path = dir.join(format!( - "postmaster-test-keys-worldread-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - { - let mut f = std::fs::File::create(&path).unwrap(); - writeln!(f, "DOTENV_PRIVATE_KEY={}", "11".repeat(32)).unwrap(); - } - // 0644: world-readable — must be rejected. - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); - match KeyRing::load(&path, KeyNaming::Env) { - Err(e) if e.contains("group/world accessible") => {} - other => panic!("expected group/world permission error, got {other:?}"), - } - let _ = std::fs::remove_file(&path); - } - - #[test] - fn load_rejects_group_readable_keys_file() { - use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir(); - let path = dir.join(format!( - "postmaster-test-keys-groupread-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - { - let mut f = std::fs::File::create(&path).unwrap(); - writeln!(f, "DOTENV_PRIVATE_KEY={}", "11".repeat(32)).unwrap(); - } - // 0640: group-readable — must be rejected. - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap(); - match KeyRing::load(&path, KeyNaming::Env) { - Err(e) if e.contains("group/world accessible") => {} - other => panic!("expected group permission error, got {other:?}"), - } - let _ = std::fs::remove_file(&path); - } - - #[test] - fn load_rejects_symlink_keys_file() { - let dir = tdir("symlink-keys"); - let real = dir.join("real-keys"); - std::fs::write(&real, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o600)).unwrap(); - let link = dir.join(".env.keys"); - std::os::unix::fs::symlink(&real, &link).unwrap(); - match KeyRing::load(&link, KeyNaming::Env) { - Err(e) if e.contains("symlink") => {} - other => panic!("expected symlink rejection error, got {other:?}"), - } - } - - #[test] - fn load_accepts_0600_keys_file() { - // Sanity: a properly locked-down keys file (0600, owned by euid) - // loads normally. This guards against false positives from the - // permission and ownership checks. - let content = format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32)); - with_temp_keys(&content, |p| { - KeyRing::load(p, KeyNaming::Env).expect("0600 keys file owned by euid should load"); - }); - } - - #[test] - fn load_accepts_0400_keys_file() { - use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir(); - let path = dir.join(format!( - "postmaster-test-keys-0400-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - { - let mut f = std::fs::File::create(&path).unwrap(); - writeln!(f, "DOTENV_PRIVATE_KEY={}", "11".repeat(32)).unwrap(); - } - // 0400: read-only by owner — stricter than 0600, must pass. - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400)).unwrap(); - KeyRing::load(&path, KeyNaming::Env).expect("0400 keys file owned by euid should load"); - let _ = std::fs::remove_file(&path); - } - - #[test] - #[cfg(target_os = "macos")] - fn verify_external_binary_accepts_codesigned_binary() { - // /usr/bin/security is Apple-signed and SIP-protected; the codesign - // verification must pass. This guards against a hypothetical SIP - // bypass or a misconfigured environment where the binary has been - // replaced. - verify_external_binary(std::path::Path::new("/usr/bin/security")) - .expect("codesigned system binary should pass verification"); - } - - #[test] - #[cfg(target_os = "macos")] - fn verify_external_binary_rejects_unsigned_file() { - // A temp file with no code signature must be rejected by codesign -v. - let dir = std::env::temp_dir(); - let path = dir.join(format!( - "postmaster-test-unsigned-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - std::fs::write(&path, b"not a signed binary").unwrap(); - let result = verify_external_binary(&path); - let _ = std::fs::remove_file(&path); - assert!( - result.is_err(), - "unsigned file should fail code signature verification" - ); - } - - #[test] - #[cfg(not(target_os = "macos"))] - fn verify_external_binary_rejects_non_root_owned() { - // On Linux, a non-root-owned binary in /tmp must be rejected. - let dir = std::env::temp_dir(); - let path = dir.join(format!( - "postmaster-test-binary-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - std::fs::write(&path, b"fake binary").unwrap(); - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); - let result = verify_external_binary(&path); - let _ = std::fs::remove_file(&path); - assert!(result.is_err(), "non-root-owned binary should be rejected"); - } - #[test] fn is_ident_rules() { assert!(is_ident("DATABASE_URL") && is_ident("_x9")); assert!(!is_ident("9x") && !is_ident("a-b") && !is_ident("") && !is_ident("a b")); } - #[test] - fn is_key_var_name_rules() { - // audit 2026-08-02 A16: only `PREFIX` or `PREFIX_` match; - // prefix-substring collisions are rejected. - let p = "DOTENV_PRIVATE_KEY"; - assert!(is_key_var_name(p, "DOTENV_PRIVATE_KEY")); - assert!(is_key_var_name(p, "DOTENV_PRIVATE_KEY_PRODUCTION")); - assert!(!is_key_var_name(p, "DOTENV_PRIVATE_KEYFOO")); - assert!(!is_key_var_name(p, "DOTENV_PRIVATE_KEY_")); // empty suffix - assert!(!is_key_var_name(p, "DOTENV_PRIVATE_KE")); - assert!(!is_key_var_name(p, "XDOTENV_PRIVATE_KEY")); - } - #[test] fn resolve_all_precedence() { let d = tdir("prec"); @@ -840,63 +557,4 @@ pub mod tests { assert_eq!(out.failed.len(), 1); assert_eq!(out.failed[0].0, "A"); } - - #[test] - fn from_env_loads_and_fails_closed() { - // from_env reads ALL DOTENV_PRIVATE_KEY* vars from the process - // environment and delegates to from_pairs. This is a single test - // (not two) because env mutation is global and tests run in - // parallel — two tests mutating DOTENV_PRIVATE_KEY* simultaneously - // would race. Using a unique suffix to avoid collision with any - // ambient vars in the test runner. - let var_name = "DOTENV_PRIVATE_KEY_TESTFROMENV"; - let key_hex = "aa".repeat(32); - - // Positive path: set a valid key, from_env succeeds. - // SAFETY: set_var/remove_var are unsafe on edition 2024 (not - // thread-safe). This test does not spawn threads and the var name - // is unique, so no concurrent test mutates the same var. - unsafe { - std::env::set_var(var_name, &key_hex); - } - let ring = KeyRing::from_env(KeyNaming::Env); - unsafe { - std::env::remove_var(var_name); - } - let ring = ring.expect("from_env should succeed with a valid key set"); - let candidates = ring - .0 - .get(var_name) - .expect("ring should contain the key we set"); - assert_eq!(candidates.len(), 1, "exactly one candidate expected"); - assert_eq!(&candidates[0][..], &[0xaa; 32]); - - // Negative path: set an invalid hex value, from_env fails closed - // with an "environment:" prefixed error. - unsafe { - std::env::set_var(var_name, "not-valid-hex-at-all"); - } - let err = KeyRing::from_env(KeyNaming::Env); - unsafe { - std::env::remove_var(var_name); - } - let err = err.expect_err("from_env should fail on invalid hex"); - assert!( - err.starts_with("environment:"), - "expected 'environment:' prefix, got: {err}" - ); - - // Also verify the from_pairs empty-error path directly: no - // DOTENV_PRIVATE_KEY* entries at all should be an error. - assert!( - KeyRing::from_pairs( - [( - "NOT_A_DOTENV_KEY".to_string(), - Zeroizing::new("x".to_string()) - )], - KeyNaming::Env, - ) - .is_err() - ); - } } diff --git a/src/keys/provisioning/cleanup.rs b/src/keys/provisioning/cleanup.rs new file mode 100644 index 0000000..e0b1d02 --- /dev/null +++ b/src/keys/provisioning/cleanup.rs @@ -0,0 +1,207 @@ +//! `postmaster cleanup` command path. + +use std::fs; +use std::path::Path; + +use crate::server::log; + +/// `postmaster cleanup`: remove all secret files from the secrets_dir +/// configured in the exec config. Intended for `ExecStopPost` in systemd +/// or equivalent lifecycle hooks. Does not decrypt — only removes files +/// that postmaster would have written. Bulk removal is guarded by the +/// `.postmaster-managed` sentinel: a non-empty directory lacking it is +/// refused (postmaster only bulk-deletes directories it manages). Safe +/// to run even if the directory is empty or does not exist. +pub fn cleanup(config_path: &Path) -> Result<(), String> { + let cfg = crate::launcher::parse_exec_config(config_path)?; + let dir = cfg + .secrets_dir + .as_deref() + .ok_or("cleanup: config has no secrets_dir — nothing to clean up")?; + // Refuse to bulk-delete in a directory that isn't clearly + // postmaster-managed (audit 2026-08-02 A19): in a symlinked or + // group/world-accessible dir these deletes could hit foreign files. + let md = match fs::symlink_metadata(dir) { + Ok(md) => md, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + log(&format!( + "cleanup: {} does not exist; nothing to clean up", + dir.display() + )); + return Ok(()); + } + Err(e) => return Err(format!("{}: cleanup: {e}", dir.display())), + }; + if md.file_type().is_symlink() || !md.is_dir() { + return Err(format!( + "{}: cleanup: refusing a symlinked or non-directory secrets dir", + dir.display() + )); + } + let entries = match fs::read_dir(dir) { + Ok(e) => e, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + log(&format!( + "cleanup: {} does not exist; nothing to clean up", + dir.display() + )); + return Ok(()); + } + Err(e) => return Err(format!("{}: cleanup: {e}", dir.display())), + }; + let entries: Vec> = entries.collect(); + if entries.is_empty() { + log(&format!( + "cleanup: {} is empty; nothing to clean up", + dir.display() + )); + return Ok(()); + } + // Managed-dir guard (audit 2026-08-02 A19): non-empty and no + // sentinel means postmaster never wrote here — bulk deletes could + // hit foreign files. Refuse. + match fs::symlink_metadata(dir.join(crate::secret_files::MANAGED_SENTINEL)) { + Ok(smd) if smd.is_file() => {} + _ => { + return Err(format!( + "{}: cleanup: no {} sentinel; refusing to bulk-delete in a directory postmaster did not write to", + dir.display(), + crate::secret_files::MANAGED_SENTINEL + )); + } + } + let mut removed = 0_usize; + for entry in entries { + let entry = match entry { + Ok(e) => e, + Err(e) => { + log(&format!( + "{}: cleanup: skip unreadable entry: {e}", + dir.display() + )); + continue; + } + }; + let path = entry.path(); + // The sentinel is infrastructure, not a secret — skipped here + // and removed last, so an interrupted cleanup can be re-run. + if entry.file_name().to_str() == Some(crate::secret_files::MANAGED_SENTINEL) { + continue; + } + match fs::symlink_metadata(&path) { + Ok(md) if md.is_file() => { + if let Err(e) = fs::remove_file(&path) { + log(&format!("{}: cleanup: {e}", path.display())); + } else { + removed += 1; + } + } + Ok(md) => { + log(&format!( + "{}: cleanup: skipping non-file (type {:?})", + path.display(), + md.file_type() + )); + } + Err(e) => { + log(&format!("{}: cleanup: stat: {e}", path.display())); + } + } + } + // Remove the sentinel last (see above). + let sentinel = dir.join(crate::secret_files::MANAGED_SENTINEL); + if let Err(e) = fs::remove_file(&sentinel) + && e.kind() != std::io::ErrorKind::NotFound + { + log(&format!("{}: cleanup: {e}", sentinel.display())); + } + log(&format!( + "cleanup: removed {removed} file(s) from {}", + dir.display() + )); + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic)] +mod tests { + use super::*; + + #[test] + fn cleanup_removes_all_files_from_secrets_dir() { + let dir = std::env::temp_dir().join(format!("pm-keyprov-cleanup-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + // cleanup requires a postmaster-managed (owner-only) dir + // (audit 2026-08-02 A19); match real deployments. + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); + fs::write(dir.join("KEY_A"), b"secret-a").unwrap(); + fs::write(dir.join("KEY_B"), b"secret-b").unwrap(); + fs::create_dir(dir.join("subdir")).unwrap(); + fs::write(dir.join(crate::secret_files::MANAGED_SENTINEL), b"").unwrap(); + + let cfg_path = dir.join("exec.json"); + fs::write( + &cfg_path, + format!( + r#"{{"mode":"files","keys":["environment"],"env_files":["/nonexistent"],"secrets_dir":"{}"}}"#, + dir.display() + ), + ) + .unwrap(); + + cleanup(&cfg_path).unwrap(); + + assert!(!dir.join("KEY_A").exists(), "KEY_A should be removed"); + assert!(!dir.join("KEY_B").exists(), "KEY_B should be removed"); + assert!(dir.join("subdir").exists(), "subdir should be preserved"); + assert!( + !dir.join(crate::secret_files::MANAGED_SENTINEL).exists(), + "sentinel is removed last" + ); + } + + #[test] + fn cleanup_refuses_unmanaged_dir() { + // audit 2026-08-02 A19: a non-empty dir without the sentinel was + // never written by postmaster; cleanup must refuse to bulk-delete + // there (foreign files could be present). + let dir = std::env::temp_dir().join(format!("pm-keyprov-unmanaged-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("FOREIGN"), b"not-ours").unwrap(); + let cfg_path = dir.join("exec.json"); + fs::write( + &cfg_path, + format!( + r#"{{"mode":"files","keys":["environment"],"env_files":["/nonexistent"],"secrets_dir":"{}"}}"#, + dir.display() + ), + ) + .unwrap(); + + let err = cleanup(&cfg_path).unwrap_err(); + + assert!(err.contains("sentinel"), "{err}"); + assert!(dir.join("FOREIGN").exists(), "nothing may be deleted"); + } + + #[test] + fn cleanup_nonexistent_dir_is_ok() { + let dir = std::env::temp_dir().join(format!("pm-keyprov-missing-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let cfg_path = dir.join("exec.json"); + fs::write( + &cfg_path, + format!( + r#"{{"mode":"files","keys":["environment"],"env_files":["/nonexistent"],"secrets_dir":"{}/no-such-dir"}}"#, + dir.display() + ), + ) + .unwrap(); + + assert!(cleanup(&cfg_path).is_ok()); + } +} diff --git a/src/key_provisioning.rs b/src/keys/provisioning/mod.rs similarity index 61% rename from src/key_provisioning.rs rename to src/keys/provisioning/mod.rs index 8bec9a5..1eb3723 100644 --- a/src/key_provisioning.rs +++ b/src/keys/provisioning/mod.rs @@ -12,6 +12,16 @@ use crate::adapter::KeyNaming; use crate::exec_config::{ExecConfig, KeySourceSpec}; use crate::server::log; +mod cleanup; +mod setup; + +/// The `postmaster cleanup` command, re-exported so +/// `crate::key_provisioning::cleanup` keeps resolving. +pub use cleanup::cleanup; +/// The `postmaster setup` command, re-exported so +/// `crate::key_provisioning::setup` keeps resolving. +pub use setup::setup; + /// Default keys directory path: `/var/lib/postmaster` on Linux, /// `~/Library/Application Support/postmaster` on macOS. fn default_keys_dir() -> PathBuf { @@ -386,274 +396,3 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> )); Ok(()) } - -/// `postmaster setup`: verify platform prerequisites, create keys -/// directory with correct permissions, optionally seed keychain items, -/// and validate the environment. Idempotent — skips steps that are -/// already correct. -/// -/// `--recheck`: re-run verification checks only, without creating or -/// modifying anything. -/// -/// `--unattended`: non-interactive mode for automation. Uses defaults -/// or env vars instead of prompting. Fail closed on any missing -/// prerequisite. -/// -/// `--force`: re-seed or re-create even if the target state is already -/// present. -/// -/// `--keys-dir `: override the keys directory path. -pub fn setup( - config_path: &Path, - recheck: bool, - unattended: bool, - force: bool, - keys_dir_override: Option, -) -> Result<(), String> { - let cfg = crate::launcher::parse_exec_config(config_path)?; - cfg.validate_shape()?; - - // Build the wanted key variable list from both env and bundle files - let mut wanted: Vec = Vec::new(); - for f in &cfg.env_files { - wanted.push(KeyNaming::Env.key_var_for(f)?); - } - for f in &cfg.bundle_files { - wanted.push(KeyNaming::Bundle.key_var_for(f)?); - } - - if recheck { - // --recheck: verification only, no creation or modification - return verify_key_sources(&cfg, &wanted); - } - - // Step 1: Create or verify keys directory - let keys_dir = keys_dir_override.unwrap_or_else(default_keys_dir); - ensure_keys_dir(&keys_dir, force)?; - - // Step 2: Verify or create key files for file-source keys - for spec in &cfg.keys { - if let KeySourceSpec::File(path) = spec { - ensure_keys_file(path, force, unattended)?; - } - } - - // Step 3: Verify or seed keychain items (macOS only) - #[cfg(target_os = "macos")] - for spec in &cfg.keys { - if let KeySourceSpec::Keychain(service) = spec { - ensure_keychain_items(service, &wanted, force, unattended)?; - } - } - - // Step 4: Verify the full environment (same as --recheck) - verify_key_sources(&cfg, &wanted)?; - - log(&format!( - "setup: complete — keys dir {}, {} key source(s) verified", - keys_dir.display(), - cfg.keys.len() - )); - Ok(()) -} - -/// `postmaster cleanup`: remove all secret files from the secrets_dir -/// configured in the exec config. Intended for `ExecStopPost` in systemd -/// or equivalent lifecycle hooks. Does not decrypt — only removes files -/// that postmaster would have written. Bulk removal is guarded by the -/// `.postmaster-managed` sentinel: a non-empty directory lacking it is -/// refused (postmaster only bulk-deletes directories it manages). Safe -/// to run even if the directory is empty or does not exist. -pub fn cleanup(config_path: &Path) -> Result<(), String> { - let cfg = crate::launcher::parse_exec_config(config_path)?; - let dir = cfg - .secrets_dir - .as_deref() - .ok_or("cleanup: config has no secrets_dir — nothing to clean up")?; - // Refuse to bulk-delete in a directory that isn't clearly - // postmaster-managed (audit 2026-08-02 A19): in a symlinked or - // group/world-accessible dir these deletes could hit foreign files. - let md = match fs::symlink_metadata(dir) { - Ok(md) => md, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - log(&format!( - "cleanup: {} does not exist; nothing to clean up", - dir.display() - )); - return Ok(()); - } - Err(e) => return Err(format!("{}: cleanup: {e}", dir.display())), - }; - if md.file_type().is_symlink() || !md.is_dir() { - return Err(format!( - "{}: cleanup: refusing a symlinked or non-directory secrets dir", - dir.display() - )); - } - let entries = match fs::read_dir(dir) { - Ok(e) => e, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - log(&format!( - "cleanup: {} does not exist; nothing to clean up", - dir.display() - )); - return Ok(()); - } - Err(e) => return Err(format!("{}: cleanup: {e}", dir.display())), - }; - let entries: Vec> = entries.collect(); - if entries.is_empty() { - log(&format!( - "cleanup: {} is empty; nothing to clean up", - dir.display() - )); - return Ok(()); - } - // Managed-dir guard (audit 2026-08-02 A19): non-empty and no - // sentinel means postmaster never wrote here — bulk deletes could - // hit foreign files. Refuse. - match fs::symlink_metadata(dir.join(crate::secret_files::MANAGED_SENTINEL)) { - Ok(smd) if smd.is_file() => {} - _ => { - return Err(format!( - "{}: cleanup: no {} sentinel; refusing to bulk-delete in a directory postmaster did not write to", - dir.display(), - crate::secret_files::MANAGED_SENTINEL - )); - } - } - let mut removed = 0_usize; - for entry in entries { - let entry = match entry { - Ok(e) => e, - Err(e) => { - log(&format!( - "{}: cleanup: skip unreadable entry: {e}", - dir.display() - )); - continue; - } - }; - let path = entry.path(); - // The sentinel is infrastructure, not a secret — skipped here - // and removed last, so an interrupted cleanup can be re-run. - if entry.file_name().to_str() == Some(crate::secret_files::MANAGED_SENTINEL) { - continue; - } - match fs::symlink_metadata(&path) { - Ok(md) if md.is_file() => { - if let Err(e) = fs::remove_file(&path) { - log(&format!("{}: cleanup: {e}", path.display())); - } else { - removed += 1; - } - } - Ok(md) => { - log(&format!( - "{}: cleanup: skipping non-file (type {:?})", - path.display(), - md.file_type() - )); - } - Err(e) => { - log(&format!("{}: cleanup: stat: {e}", path.display())); - } - } - } - // Remove the sentinel last (see above). - let sentinel = dir.join(crate::secret_files::MANAGED_SENTINEL); - if let Err(e) = fs::remove_file(&sentinel) - && e.kind() != std::io::ErrorKind::NotFound - { - log(&format!("{}: cleanup: {e}", sentinel.display())); - } - log(&format!( - "cleanup: removed {removed} file(s) from {}", - dir.display() - )); - Ok(()) -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::panic)] -mod tests { - use super::*; - - #[test] - fn cleanup_removes_all_files_from_secrets_dir() { - let dir = std::env::temp_dir().join(format!("pm-keyprov-cleanup-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - // cleanup requires a postmaster-managed (owner-only) dir - // (audit 2026-08-02 A19); match real deployments. - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); - fs::write(dir.join("KEY_A"), b"secret-a").unwrap(); - fs::write(dir.join("KEY_B"), b"secret-b").unwrap(); - fs::create_dir(dir.join("subdir")).unwrap(); - fs::write(dir.join(crate::secret_files::MANAGED_SENTINEL), b"").unwrap(); - - let cfg_path = dir.join("exec.json"); - fs::write( - &cfg_path, - format!( - r#"{{"mode":"files","keys":["environment"],"env_files":["/nonexistent"],"secrets_dir":"{}"}}"#, - dir.display() - ), - ) - .unwrap(); - - cleanup(&cfg_path).unwrap(); - - assert!(!dir.join("KEY_A").exists(), "KEY_A should be removed"); - assert!(!dir.join("KEY_B").exists(), "KEY_B should be removed"); - assert!(dir.join("subdir").exists(), "subdir should be preserved"); - assert!( - !dir.join(crate::secret_files::MANAGED_SENTINEL).exists(), - "sentinel is removed last" - ); - } - - #[test] - fn cleanup_refuses_unmanaged_dir() { - // audit 2026-08-02 A19: a non-empty dir without the sentinel was - // never written by postmaster; cleanup must refuse to bulk-delete - // there (foreign files could be present). - let dir = std::env::temp_dir().join(format!("pm-keyprov-unmanaged-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - fs::write(dir.join("FOREIGN"), b"not-ours").unwrap(); - let cfg_path = dir.join("exec.json"); - fs::write( - &cfg_path, - format!( - r#"{{"mode":"files","keys":["environment"],"env_files":["/nonexistent"],"secrets_dir":"{}"}}"#, - dir.display() - ), - ) - .unwrap(); - - let err = cleanup(&cfg_path).unwrap_err(); - - assert!(err.contains("sentinel"), "{err}"); - assert!(dir.join("FOREIGN").exists(), "nothing may be deleted"); - } - - #[test] - fn cleanup_nonexistent_dir_is_ok() { - let dir = std::env::temp_dir().join(format!("pm-keyprov-missing-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - let cfg_path = dir.join("exec.json"); - fs::write( - &cfg_path, - format!( - r#"{{"mode":"files","keys":["environment"],"env_files":["/nonexistent"],"secrets_dir":"{}/no-such-dir"}}"#, - dir.display() - ), - ) - .unwrap(); - - assert!(cleanup(&cfg_path).is_ok()); - } -} diff --git a/src/keys/provisioning/setup.rs b/src/keys/provisioning/setup.rs new file mode 100644 index 0000000..957a6f1 --- /dev/null +++ b/src/keys/provisioning/setup.rs @@ -0,0 +1,80 @@ +//! `postmaster setup` command path. + +use std::path::{Path, PathBuf}; + +#[cfg(target_os = "macos")] +use super::ensure_keychain_items; +use super::{default_keys_dir, ensure_keys_dir, ensure_keys_file, verify_key_sources}; +use crate::adapter::KeyNaming; +use crate::exec_config::KeySourceSpec; +use crate::server::log; + +/// `postmaster setup`: verify platform prerequisites, create keys +/// directory with correct permissions, optionally seed keychain items, +/// and validate the environment. Idempotent — skips steps that are +/// already correct. +/// +/// `--recheck`: re-run verification checks only, without creating or +/// modifying anything. +/// +/// `--unattended`: non-interactive mode for automation. Uses defaults +/// or env vars instead of prompting. Fail closed on any missing +/// prerequisite. +/// +/// `--force`: re-seed or re-create even if the target state is already +/// present. +/// +/// `--keys-dir `: override the keys directory path. +pub fn setup( + config_path: &Path, + recheck: bool, + unattended: bool, + force: bool, + keys_dir_override: Option, +) -> Result<(), String> { + let cfg = crate::launcher::parse_exec_config(config_path)?; + cfg.validate_shape()?; + + // Build the wanted key variable list from both env and bundle files + let mut wanted: Vec = Vec::new(); + for f in &cfg.env_files { + wanted.push(KeyNaming::Env.key_var_for(f)?); + } + for f in &cfg.bundle_files { + wanted.push(KeyNaming::Bundle.key_var_for(f)?); + } + + if recheck { + // --recheck: verification only, no creation or modification + return verify_key_sources(&cfg, &wanted); + } + + // Step 1: Create or verify keys directory + let keys_dir = keys_dir_override.unwrap_or_else(default_keys_dir); + ensure_keys_dir(&keys_dir, force)?; + + // Step 2: Verify or create key files for file-source keys + for spec in &cfg.keys { + if let KeySourceSpec::File(path) = spec { + ensure_keys_file(path, force, unattended)?; + } + } + + // Step 3: Verify or seed keychain items (macOS only) + #[cfg(target_os = "macos")] + for spec in &cfg.keys { + if let KeySourceSpec::Keychain(service) = spec { + ensure_keychain_items(service, &wanted, force, unattended)?; + } + } + + // Step 4: Verify the full environment (same as --recheck) + verify_key_sources(&cfg, &wanted)?; + + log(&format!( + "setup: complete — keys dir {}, {} key source(s) verified", + keys_dir.display(), + cfg.keys.len() + )); + Ok(()) +} diff --git a/src/key_source.rs b/src/keys/source.rs similarity index 100% rename from src/key_source.rs rename to src/keys/source.rs diff --git a/src/keys/verify.rs b/src/keys/verify.rs new file mode 100644 index 0000000..99e86cb --- /dev/null +++ b/src/keys/verify.rs @@ -0,0 +1,127 @@ +//! Integrity verification of external binaries invoked on +//! secret-handling paths. + +use std::path::Path; + +/// Verify the integrity of an external binary before invoking it as part +/// of a secret-handling path. This is a defense-in-depth trust boundary +/// check (audit finding #3): the binary path is a trust root, and we +/// verify it has not been tampered with before exec. +/// +/// On macOS: `codesign -v ` verifies the code signature. The binary +/// is additionally SIP-protected, so this catches a hypothetical SIP +/// bypass or a misconfigured environment. +/// +/// On Linux: verify the file is a regular file, owned by root (uid 0), +/// and not world-writable. There is no universal code-signing mechanism +/// on Linux, so ownership and permission checks are the practical +/// defense-in-depth boundary. +/// +/// Bootstrap limitation (audit 2026-08-02 O2): on macOS the verifier +/// itself invokes `/usr/bin/codesign`. Self-verifying codesign with +/// codesign is circular — a compromised codesign would vouch for +/// itself — so codesign is trusted via SIP alone. Moving verification +/// onto the Security.framework StaticCode API (the `security-framework` +/// crate route already chosen for keychain access) would remove this +/// residual trust gap. +pub fn verify_external_binary(path: &Path) -> Result<(), String> { + #[cfg(target_os = "macos")] + { + let out = std::process::Command::new("/usr/bin/codesign") + .args(["-v", path.to_str().unwrap_or("")]) + .output() + .map_err(|e| format!("{}: codesign verification failed: {e}", path.display()))?; + if !out.status.success() { + return Err(format!( + "{}: code signature verification failed (audit finding #3 trust boundary)", + path.display() + )); + } + } + #[cfg(not(target_os = "macos"))] + { + use std::os::unix::fs::MetadataExt; + let md = std::fs::symlink_metadata(path) + .map_err(|e| format!("{}: cannot stat external binary: {e}", path.display()))?; + if md.file_type().is_symlink() { + return Err(format!( + "{}: external binary is a symlink; refusing to trust a symlinked binary", + path.display() + )); + } + if !md.is_file() { + return Err(format!( + "{}: external binary is not a regular file", + path.display() + )); + } + if md.uid() != 0 { + return Err(format!( + "{}: external binary owned by uid {} (expected root/0); refusing to trust", + path.display(), + md.uid() + )); + } + if md.mode() & 0o002 != 0 { + return Err(format!( + "{}: external binary is world-writable; refusing to trust", + path.display() + )); + } + } + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic, unused_qualifications)] +mod tests { + use super::*; + + #[test] + #[cfg(target_os = "macos")] + fn verify_external_binary_accepts_codesigned_binary() { + // /usr/bin/security is Apple-signed and SIP-protected; the codesign + // verification must pass. This guards against a hypothetical SIP + // bypass or a misconfigured environment where the binary has been + // replaced. + verify_external_binary(std::path::Path::new("/usr/bin/security")) + .expect("codesigned system binary should pass verification"); + } + + #[test] + #[cfg(target_os = "macos")] + fn verify_external_binary_rejects_unsigned_file() { + // A temp file with no code signature must be rejected by codesign -v. + let dir = std::env::temp_dir(); + let path = dir.join(format!( + "postmaster-test-unsigned-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::write(&path, b"not a signed binary").unwrap(); + let result = verify_external_binary(&path); + let _ = std::fs::remove_file(&path); + assert!( + result.is_err(), + "unsigned file should fail code signature verification" + ); + } + + #[test] + #[cfg(not(target_os = "macos"))] + fn verify_external_binary_rejects_non_root_owned() { + // On Linux, a non-root-owned binary in /tmp must be rejected. + let dir = std::env::temp_dir(); + let path = dir.join(format!( + "postmaster-test-binary-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::write(&path, b"fake binary").unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + let result = verify_external_binary(&path); + let _ = std::fs::remove_file(&path); + assert!(result.is_err(), "non-root-owned binary should be rejected"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 33beb00..5283799 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,19 +7,26 @@ //! Security and fail-closed semantics are preserved exactly. pub mod adapter; -pub mod bundle; -pub mod config; +pub mod cli; pub mod exec_config; -pub mod key_provisioning; -pub mod key_source; pub mod keys; pub mod launcher; pub mod ramdisk; pub mod secret_files; pub mod server; -pub use config::{Invocation, parse_args, parse_args_from}; -pub use key_provisioning::{cleanup, setup}; +/// The bundle adapter, re-exported so `crate::bundle` keeps resolving. +pub use adapter::bundle; +/// The CLI module under its former name, so `crate::config` keeps resolving. +pub use cli as config; +pub use cli::{Invocation, parse_args, parse_args_from}; +/// Key provisioning under its former name, so `crate::key_provisioning` +/// keeps resolving. +pub use keys::provisioning as key_provisioning; +pub use keys::provisioning::{cleanup, setup}; +/// Key-source selection under its former name, so `crate::key_source` +/// keeps resolving. +pub use keys::source as key_source; pub use server::{fetch, harden_process, run}; /// Re-exported for binary use. The real main is here so tests can call into it. diff --git a/tests/exec_conformance.rs b/tests/exec_conformance.rs deleted file mode 100644 index e9935c1..0000000 --- a/tests/exec_conformance.rs +++ /dev/null @@ -1,733 +0,0 @@ -#![allow(clippy::unwrap_used, clippy::panic, missing_docs)] - -mod common; - -use postmaster::adapter::KeyNaming; - -use std::os::unix::fs::PermissionsExt; -use std::path::Path; -use std::process::Command; - -#[test] -fn helper_ciphertext_decrypts_with_test_key() { - let v = common::enc("hello $(rm -rf /) `x` \"q\" \nline2"); - let b64 = v.strip_prefix("encrypted:").unwrap(); - let ct = { - use base64::Engine; - base64::engine::general_purpose::STANDARD - .decode(b64) - .unwrap() - }; - let sk = hex::decode(common::TEST_SK_HEX).unwrap(); - let pt = ecies::decrypt(&sk, &ct).unwrap(); - assert_eq!(pt, b"hello $(rm -rf /) `x` \"q\" \nline2"); -} - -#[test] -fn wrapped_base64_ciphertext_decrypts() { - // Test that decrypt_value tolerates ASCII whitespace in base64 payloads, - // matching dotenvx-rs's lenient decoding behavior. - let plaintext = "wrapped-value"; - let v = common::enc(plaintext); - let b64 = v.strip_prefix("encrypted:").unwrap(); - - // Wrap the base64 by inserting newlines every 20 chars - let mut wrapped = String::from("encrypted:"); - for (i, c) in b64.chars().enumerate() { - if i > 0 && i % 20 == 0 { - wrapped.push('\n'); - } - wrapped.push(c); - } - wrapped.push('\n'); - - // Create a temporary keys file with TEST_SK_HEX - let d = common::tmpdir("wrapped-base64"); - common::write_keys_file(&d, "", &[common::TEST_SK_HEX]); - let keys_path = d.join(".env.keys"); - - // Load the key ring - let ring = postmaster::keys::KeyRing::load(&keys_path, KeyNaming::Env).unwrap(); - - // Create a dummy env file path for error messages - let dummy_env = d.join(".env"); - - // decrypt_value should handle the wrapped (whitespace-containing) payload - let result = - postmaster::keys::decrypt_value(&dummy_env, "TEST_VAR", &wrapped, &ring, KeyNaming::Env); - - assert!(result.is_ok(), "wrapped base64 should decrypt successfully"); - let decrypted = result.unwrap(); - assert_eq!(decrypted.as_slice(), plaintext.as_bytes()); -} - -fn run_exec(config: &Path, sh: &str, envs: &[(&str, &str)]) -> std::process::Output { - let mut c = Command::new(env!("CARGO_BIN_EXE_postmaster")); - c.args(["exec", "--config"]) - .arg(config) - .args(["--", "/bin/sh", "-c", sh]) - // Hermeticity: an ambient SECRET/PLAIN/A in the test runner's own - // environment would flip the precedence-test outcomes below, since - // these are exactly the value-variable names the suite asserts on. - .env_remove("SECRET") - .env_remove("PLAIN") - .env_remove("A"); - for (k, v) in envs { - c.env(k, v); - } - c.output().unwrap() -} - -fn write_config(dir: &Path, json: &str) -> std::path::PathBuf { - let p = dir.join("exec.json"); - std::fs::write(&p, json).unwrap(); - p -} - -#[test] -fn env_mode_injects_decrypted_metacharacter_values_inert() { - let d = common::tmpdir("envmode"); - let val = "p@ss;|&`$(boom)\"'\nline2"; - let env = common::write_env_file( - &d, - ".env.production", - &[ - format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), - format!("SECRET=\"{}\"", common::enc(val)), - "PLAIN=just-plain".to_string(), - ], - ); - let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); - let cfg = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"]}}"#, - keys.display(), - env.display() - ), - ); - let sh = format!( - "printf %s \"$SECRET\" > '{d}'/secret.out && printf %s \"$PLAIN\" > '{d}'/plain.out && [ -z \"${{DOTENV_PUBLIC_KEY_PRODUCTION:-}}\" ]", - d = d.display() - ); - let out = run_exec(&cfg, &sh, &[]); - assert!( - out.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!(std::fs::read(d.join("secret.out")).unwrap(), val.as_bytes()); - assert_eq!(std::fs::read(d.join("plain.out")).unwrap(), b"just-plain"); -} - -#[test] -fn env_mode_process_env_wins_without_overload() { - let d = common::tmpdir("envwins"); - let val = "decrypted-value"; - let env = common::write_env_file( - &d, - ".env.production", - &[ - format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), - format!("SECRET=\"{}\"", common::enc(val)), - ], - ); - let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); - - let cfg_no_overload = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"overload":false}}"#, - keys.display(), - env.display() - ), - ); - let sh1 = format!("printf %s \"$SECRET\" > '{d}'/out1", d = d.display()); - let out1 = run_exec(&cfg_no_overload, &sh1, &[("SECRET", "preset")]); - assert!( - out1.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out1.stderr) - ); - assert_eq!(std::fs::read(d.join("out1")).unwrap(), b"preset"); - - let cfg_overload = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"overload":true}}"#, - keys.display(), - env.display() - ), - ); - let sh2 = format!("printf %s \"$SECRET\" > '{d}'/out2", d = d.display()); - let out2 = run_exec(&cfg_overload, &sh2, &[("SECRET", "preset")]); - assert!( - out2.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out2.stderr) - ); - assert_eq!(std::fs::read(d.join("out2")).unwrap(), val.as_bytes()); -} - -#[test] -fn rotation_second_key_decrypts() { - let d = common::tmpdir("rotation"); - let val = "rotated-secret"; - let env = common::write_env_file( - &d, - ".env.production", - &[ - format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), - format!("SECRET=\"{}\"", common::enc(val)), - ], - ); - let bogus = "22".repeat(32); - let keys = common::write_keys_file(&d, "PRODUCTION", &[&bogus, common::TEST_SK_HEX]); - let cfg = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"]}}"#, - keys.display(), - env.display() - ), - ); - let sh = format!("printf %s \"$SECRET\" > '{d}'/out", d = d.display()); - let out = run_exec(&cfg, &sh, &[]); - assert!( - out.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!(std::fs::read(d.join("out")).unwrap(), val.as_bytes()); -} - -#[test] -fn strict_failure_refuses_exec() { - let d = common::tmpdir("strictfail"); - // Encrypt with a DIFFERENT key than the one in our keyring, so - // decryption must fail even though the ciphertext is well-formed. - let other_sk_hex = "22".repeat(32); - let other_sk_bytes = hex::decode(&other_sk_hex).unwrap(); - let other_sk = ecies::SecretKey::parse_slice(&other_sk_bytes).unwrap(); - let other_pk = ecies::PublicKey::from_secret_key(&other_sk); - let ct = ecies::encrypt(&other_pk.serialize_compressed(), b"unreachable").unwrap(); - let b64 = { - use base64::Engine; - base64::engine::general_purpose::STANDARD.encode(ct) - }; - let env = common::write_env_file( - &d, - ".env.production", - &[ - format!( - "DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", - hex::encode(other_pk.serialize_compressed()) - ), - format!("SECRET=\"encrypted:{b64}\""), - ], - ); - let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); - let cfg = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"strict":true}}"#, - keys.display(), - env.display() - ), - ); - let sh = format!("printf %s \"$SECRET\" > '{d}'/out", d = d.display()); - let out = run_exec(&cfg, &sh, &[]); - assert!(!out.status.success()); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!(stderr.contains("no key under"), "stderr: {stderr}"); - assert!(!d.join("out").exists()); -} - -#[test] -fn files_mode_writes_0600_pointers_and_passthrough() { - let d = common::tmpdir("filesmode"); - let secrets_dir = d.join("secrets"); - std::fs::create_dir_all(&secrets_dir).unwrap(); - let val = "file-secret"; - let env = common::write_env_file( - &d, - ".env.production", - &[ - format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), - format!("SECRET=\"{}\"", common::enc(val)), - "PLAIN=passthrough-val".to_string(), - ], - ); - let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); - let cfg = write_config( - &d, - &format!( - r#"{{"mode":"files","keys":[{{"file":"{}"}}],"env_files":["{}"],"secrets_dir":"{}","passthrough":["PLAIN"]}}"#, - keys.display(), - env.display(), - secrets_dir.display() - ), - ); - let sh = format!( - r#"printf %s "$SECRET_FILE" > '{d}'/secret_file.out && \ - cat "$SECRET_FILE" > '{d}'/secret_contents.out && \ - printf %s "${{SECRET:-UNSET}}" > '{d}'/secret_var.out && \ - printf %s "$PLAIN" > '{d}'/plain.out && \ - printf %s "${{POSTMASTER_SECRETS_DIR:-UNSET}}" > '{d}'/secretsdir.out"#, - d = d.display() - ); - let out = run_exec(&cfg, &sh, &[]); - assert!( - out.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!( - std::fs::read_to_string(d.join("secret_file.out")).unwrap(), - secrets_dir.join("SECRET").display().to_string() - ); - assert_eq!( - std::fs::read(d.join("secret_contents.out")).unwrap(), - val.as_bytes() - ); - assert_eq!(std::fs::read(d.join("secret_var.out")).unwrap(), b"UNSET"); - assert_eq!( - std::fs::read(d.join("plain.out")).unwrap(), - b"passthrough-val" - ); - assert_eq!( - std::fs::read_to_string(d.join("secretsdir.out")).unwrap(), - "UNSET" - ); - - let md = std::fs::metadata(secrets_dir.join("SECRET")).unwrap(); - assert_eq!(md.permissions().mode() & 0o777, 0o600); -} - -#[test] -fn credentials_mode_systemd_pointers() { - let d = common::tmpdir("credsystemd"); - let creds_dir = d.join("creds"); - std::fs::create_dir_all(&creds_dir).unwrap(); - std::fs::write(creds_dir.join("DB_URL"), "abc").unwrap(); - let cfg = write_config(&d, r#"{"mode":"credentials","credential_keys":["DB_URL"]}"#); - let sh = format!( - "printf %s \"$DB_URL_FILE\" > '{d}'/dbfile.out && cat \"$DB_URL_FILE\" > '{d}'/dbcontents.out", - d = d.display() - ); - let out = run_exec( - &cfg, - &sh, - &[("CREDENTIALS_DIRECTORY", creds_dir.to_str().unwrap())], - ); - assert!( - out.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!( - std::fs::read_to_string(d.join("dbfile.out")).unwrap(), - creds_dir.join("DB_URL").display().to_string() - ); - assert_eq!(std::fs::read(d.join("dbcontents.out")).unwrap(), b"abc"); - - // Without CREDENTIALS_DIRECTORY, the systemd path has nothing to point - // at: fail closed. Explicitly remove from child to ensure hermeticity. - let mut c = Command::new(env!("CARGO_BIN_EXE_postmaster")); - c.args(["exec", "--config"]) - .arg(&cfg) - .args(["--", "/bin/sh", "-c", "true"]) - .env_remove("CREDENTIALS_DIRECTORY"); - let out2 = c.output().unwrap(); - assert!(!out2.status.success()); -} - -#[test] -fn credentials_mode_fetch_loop() { - let d = common::tmpdir("credfetch"); - let secrets_dir = d.join("secrets"); - std::fs::create_dir_all(&secrets_dir).unwrap(); - let sock = d.join("k.sock"); - let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap(); - let server = std::thread::spawn(move || { - if let Ok((mut s, _)) = listener.accept() { - use std::io::Write; - let _ = s.write_all(b"s3cret"); - let _ = s.shutdown(std::net::Shutdown::Both); - } - }); - let cfg = write_config( - &d, - &format!( - r#"{{"mode":"credentials","credential_keys":["K"],"sockets":{{"K":"{}"}},"secrets_dir":"{}"}}"#, - sock.display(), - secrets_dir.display() - ), - ); - let sh = format!( - "printf %s \"$CREDENTIALS_DIRECTORY\" > '{d}'/creddir.out && cat '{sd}'/K > '{d}'/kcontents.out", - d = d.display(), - sd = secrets_dir.display() - ); - let out = run_exec(&cfg, &sh, &[]); - server.join().unwrap(); - assert!( - out.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!( - std::fs::read_to_string(d.join("creddir.out")).unwrap(), - secrets_dir.display().to_string() - ); - assert_eq!(std::fs::read(d.join("kcontents.out")).unwrap(), b"s3cret"); - let md = std::fs::metadata(secrets_dir.join("K")).unwrap(); - assert_eq!(md.permissions().mode() & 0o777, 0o600); -} - -#[test] -fn multi_file_first_wins_and_overload_reverses() { - let d = common::tmpdir("multifile"); - let f1 = common::write_env_file(&d, ".env", &["A=first-file".to_string()]); - let f2 = common::write_env_file(&d, ".env.local", &["A=second-file".to_string()]); - let keys = common::write_keys_file(&d, "", &[common::TEST_SK_HEX]); - - let cfg_first = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}","{}"],"overload":false}}"#, - keys.display(), - f1.display(), - f2.display() - ), - ); - let sh1 = format!("printf %s \"$A\" > '{d}'/out1", d = d.display()); - let out1 = run_exec(&cfg_first, &sh1, &[]); - assert!( - out1.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out1.stderr) - ); - assert_eq!(std::fs::read(d.join("out1")).unwrap(), b"first-file"); - - let cfg_overload = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}","{}"],"overload":true}}"#, - keys.display(), - f1.display(), - f2.display() - ), - ); - let sh2 = format!("printf %s \"$A\" > '{d}'/out2", d = d.display()); - let out2 = run_exec(&cfg_overload, &sh2, &[]); - assert!( - out2.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out2.stderr) - ); - assert_eq!(std::fs::read(d.join("out2")).unwrap(), b"second-file"); -} - -#[test] -fn same_file_last_assignment_wins() { - let d = common::tmpdir("samelastwin"); - let first_val = "first-value"; - let second_val = "second-value"; - let env = common::write_env_file( - &d, - ".env.production", - &[ - format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), - format!("SECRET=\"{}\"", common::enc(first_val)), - format!("SECRET=\"{}\"", common::enc(second_val)), - ], - ); - let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); - let cfg = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"]}}"#, - keys.display(), - env.display() - ), - ); - let sh = format!("printf %s \"$SECRET\" > '{d}'/secret.out", d = d.display()); - let out = run_exec(&cfg, &sh, &[]); - assert!( - out.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!( - std::fs::read(d.join("secret.out")).unwrap(), - second_val.as_bytes() - ); -} - -#[test] -fn nul_in_env_value_fails_closed() { - let d = common::tmpdir("nulval"); - let val = "before\0after"; - let env = common::write_env_file( - &d, - ".env.production", - &[ - format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), - format!("SECRET=\"{}\"", common::enc(val)), - ], - ); - let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); - - // env mode: fails closed with a message about NUL. - let cfg_env = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"]}}"#, - keys.display(), - env.display() - ), - ); - let out = run_exec(&cfg_env, "true", &[]); - assert!(!out.status.success()); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!(stderr.contains("NUL"), "stderr: {stderr}"); - - // files mode: the exact bytes (including the NUL) reach the file. - let secrets_dir = d.join("secrets"); - std::fs::create_dir_all(&secrets_dir).unwrap(); - let cfg_files = write_config( - &d, - &format!( - r#"{{"mode":"files","keys":[{{"file":"{}"}}],"env_files":["{}"],"secrets_dir":"{}"}}"#, - keys.display(), - env.display(), - secrets_dir.display() - ), - ); - let sh = format!( - "cat '{sd}'/SECRET > '{d}'/out", - sd = secrets_dir.display(), - d = d.display() - ); - let out2 = run_exec(&cfg_files, &sh, &[]); - assert!( - out2.status.success(), - "stderr: {}", - String::from_utf8_lossy(&out2.stderr) - ); - assert_eq!(std::fs::read(d.join("out")).unwrap(), val.as_bytes()); -} - -#[test] -fn strict_false_skips_undecryptable_and_continues() { - let d = common::tmpdir("laxskip"); - // GOOD decrypts with TEST_SK_HEX; BAD uses a different key so it fails. - let other_sk_hex = "33".repeat(32); - let other_sk_bytes = hex::decode(&other_sk_hex).unwrap(); - let other_sk = ecies::SecretKey::parse_slice(&other_sk_bytes).unwrap(); - let other_pk = ecies::PublicKey::from_secret_key(&other_sk); - let bad_ct = ecies::encrypt(&other_pk.serialize_compressed(), b"unreachable").unwrap(); - let bad_b64 = { - use base64::Engine; - base64::engine::general_purpose::STANDARD.encode(bad_ct) - }; - - let env = common::write_env_file( - &d, - ".env.production", - &[ - format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), - format!("GOOD=\"{}\"", common::enc("lax-ok")), - format!("BAD=\"encrypted:{bad_b64}\""), - ], - ); - let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); - // strict:false: BAD should be skipped (logged), GOOD should still reach the child. - let cfg = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"strict":false}}"#, - keys.display(), - env.display() - ), - ); - let sh = format!( - "printf %s \"${{GOOD:-UNSET}}\" > '{d}'/good.out && printf %s \"${{BAD:-UNSET}}\" > '{d}'/bad.out", - d = d.display() - ); - let out = run_exec(&cfg, &sh, &[]); - assert!( - out.status.success(), - "strict:false should continue past undecryptable value and launch the child\nstderr: {}", - String::from_utf8_lossy(&out.stderr) - ); - assert_eq!(std::fs::read(d.join("good.out")).unwrap(), b"lax-ok"); - // BAD was skipped: the child sees no BAD env var. - assert_eq!(std::fs::read(d.join("bad.out")).unwrap(), b"UNSET"); - // The stderr should mention the skip. - let stderr = String::from_utf8_lossy(&out.stderr); - assert!( - stderr.contains("non-strict: skipping BAD"), - "expected skip log in stderr, got: {stderr}" - ); -} - -#[test] -fn exec_rejects_non_identifier_key_at_exec_boundary() { - let d = common::tmpdir("badkey"); - // A dotted key like BAD.KEY parses fine as dotenv but is_ident rejects it. - let env = common::write_env_file(&d, ".env", &["BAD.KEY=oops".to_string()]); - let keys = common::write_keys_file(&d, "", &[common::TEST_SK_HEX]); - let cfg = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"]}}"#, - keys.display(), - env.display() - ), - ); - let out = run_exec(&cfg, "true", &[]); - assert!(!out.status.success()); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!( - stderr.contains("non-identifier"), - "expected 'non-identifier' in stderr, got: {stderr}" - ); -} - -#[test] -fn verify_keys_aborts_on_stale_keys_with_strict_false() { - // Audit finding #4: --verify-keys should catch stale keys even when - // strict is false. Encrypt with a different key than the one in the - // keyring, set strict:false, and pass --verify-keys. The exec must - // abort with a --verify-keys error rather than launching the child - // with no secrets. - let d = common::tmpdir("verifykeys"); - let other_sk_hex = "33".repeat(32); - let other_sk_bytes = hex::decode(&other_sk_hex).unwrap(); - let other_sk = ecies::SecretKey::parse_slice(&other_sk_bytes).unwrap(); - let other_pk = ecies::PublicKey::from_secret_key(&other_sk); - let ct = ecies::encrypt(&other_pk.serialize_compressed(), b"stale-secret").unwrap(); - let b64 = { - use base64::Engine; - base64::engine::general_purpose::STANDARD.encode(ct) - }; - let env = common::write_env_file( - &d, - ".env.production", - &[ - format!( - "DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", - hex::encode(other_pk.serialize_compressed()) - ), - format!("SECRET=\"encrypted:{b64}\""), - ], - ); - // Keyring has the TEST_SK_HEX key, NOT the other key — keys are stale. - let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); - let cfg = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"strict":false}}"#, - keys.display(), - env.display() - ), - ); - // Without --verify-keys, strict:false would silently skip and succeed. - let sh = "true".to_string(); - let out_no_verify = run_exec(&cfg, &sh, &[]); - assert!( - out_no_verify.status.success(), - "without --verify-keys, strict:false should silently skip: {}", - String::from_utf8_lossy(&out_no_verify.stderr) - ); - - // With --verify-keys, the stale keys must be caught. - let mut c = Command::new(env!("CARGO_BIN_EXE_postmaster")); - c.args(["exec", "--config"]) - .arg(&cfg) - .args(["--verify-keys", "--", "true"]) - .env_remove("SECRET"); - let out = c.output().unwrap(); - assert!( - !out.status.success(), - "--verify-keys should abort on stale keys" - ); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!( - stderr.contains("--verify-keys failed"), - "expected '--verify-keys failed' in stderr, got: {stderr}" - ); -} - -#[test] -fn verify_keys_aborts_on_partial_failure_with_strict_false() { - // Audit 2026-08-02 A3: with strict:false, resolution silently skips - // undecryptable values. When SOME values still decrypt, the resolved - // set is non-empty and the old freshness check passed — the child - // launched with a partial secret set. --verify-keys must now abort - // on any recorded skip. - let d = common::tmpdir("verifykeys-partial"); - let other_sk_hex = "33".repeat(32); - let other_sk_bytes = hex::decode(&other_sk_hex).unwrap(); - let other_sk = ecies::SecretKey::parse_slice(&other_sk_bytes).unwrap(); - let other_pk = ecies::PublicKey::from_secret_key(&other_sk); - let stale_ct = ecies::encrypt(&other_pk.serialize_compressed(), b"stale-secret").unwrap(); - let stale_b64 = { - use base64::Engine; - base64::engine::general_purpose::STANDARD.encode(stale_ct) - }; - let env = common::write_env_file( - &d, - ".env.production", - &[ - format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), - // Decrypts with the keyring's key — the resolved set is - // non-empty, which is what fooled the old check. - format!("SECRET_GOOD=\"{}\"", common::enc("good-secret")), - // Encrypted to a key NOT in the keyring — skipped under - // strict:false. This is the partial-rotation case. - format!("SECRET_STALE=\"encrypted:{stale_b64}\""), - ], - ); - let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); - let cfg = write_config( - &d, - &format!( - r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"strict":false}}"#, - keys.display(), - env.display() - ), - ); - // Without --verify-keys the partial set launches silently: - // SECRET_GOOD is served, SECRET_STALE is dropped. - let out_no_verify = run_exec(&cfg, "test \"$SECRET_GOOD\" = good-secret", &[]); - assert!( - out_no_verify.status.success(), - "without --verify-keys, strict:false should silently serve the partial set: {}", - String::from_utf8_lossy(&out_no_verify.stderr) - ); - - // With --verify-keys, the recorded skip must abort the launch. - let mut c = Command::new(env!("CARGO_BIN_EXE_postmaster")); - c.args(["exec", "--config"]) - .arg(&cfg) - .args(["--verify-keys", "--", "true"]) - .env_remove("SECRET_GOOD") - .env_remove("SECRET_STALE"); - let out = c.output().unwrap(); - assert!( - !out.status.success(), - "--verify-keys should abort on a partial decryption failure" - ); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!( - stderr.contains("--verify-keys failed"), - "expected '--verify-keys failed' in stderr, got: {stderr}" - ); - assert!( - stderr.contains("SECRET_STALE"), - "expected the skipped key name in stderr, got: {stderr}" - ); -} diff --git a/tests/exec_conformance/bundle.rs b/tests/exec_conformance/bundle.rs new file mode 100644 index 0000000..a9e427d --- /dev/null +++ b/tests/exec_conformance/bundle.rs @@ -0,0 +1,5 @@ +//! Bundle conformance tests. +//! +//! The bundle adapter's conformance surface is currently covered by the +//! unit tests in `src/adapter/bundle.rs`; this module is the designated +//! home for end-to-end bundle exec conformance tests. diff --git a/tests/exec_conformance/env_mode.rs b/tests/exec_conformance/env_mode.rs new file mode 100644 index 0000000..9172b29 --- /dev/null +++ b/tests/exec_conformance/env_mode.rs @@ -0,0 +1,244 @@ +use crate::common; +use crate::{run_exec, write_config}; + +#[test] +fn env_mode_injects_decrypted_metacharacter_values_inert() { + let d = common::tmpdir("envmode"); + let val = "p@ss;|&`$(boom)\"'\nline2"; + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + format!("SECRET=\"{}\"", common::enc(val)), + "PLAIN=just-plain".to_string(), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"]}}"#, + keys.display(), + env.display() + ), + ); + let sh = format!( + "printf %s \"$SECRET\" > '{d}'/secret.out && printf %s \"$PLAIN\" > '{d}'/plain.out && [ -z \"${{DOTENV_PUBLIC_KEY_PRODUCTION:-}}\" ]", + d = d.display() + ); + let out = run_exec(&cfg, &sh, &[]); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(std::fs::read(d.join("secret.out")).unwrap(), val.as_bytes()); + assert_eq!(std::fs::read(d.join("plain.out")).unwrap(), b"just-plain"); +} + +#[test] +fn env_mode_process_env_wins_without_overload() { + let d = common::tmpdir("envwins"); + let val = "decrypted-value"; + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + format!("SECRET=\"{}\"", common::enc(val)), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + + let cfg_no_overload = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"overload":false}}"#, + keys.display(), + env.display() + ), + ); + let sh1 = format!("printf %s \"$SECRET\" > '{d}'/out1", d = d.display()); + let out1 = run_exec(&cfg_no_overload, &sh1, &[("SECRET", "preset")]); + assert!( + out1.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out1.stderr) + ); + assert_eq!(std::fs::read(d.join("out1")).unwrap(), b"preset"); + + let cfg_overload = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"overload":true}}"#, + keys.display(), + env.display() + ), + ); + let sh2 = format!("printf %s \"$SECRET\" > '{d}'/out2", d = d.display()); + let out2 = run_exec(&cfg_overload, &sh2, &[("SECRET", "preset")]); + assert!( + out2.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out2.stderr) + ); + assert_eq!(std::fs::read(d.join("out2")).unwrap(), val.as_bytes()); +} + +#[test] +fn multi_file_first_wins_and_overload_reverses() { + let d = common::tmpdir("multifile"); + let f1 = common::write_env_file(&d, ".env", &["A=first-file".to_string()]); + let f2 = common::write_env_file(&d, ".env.local", &["A=second-file".to_string()]); + let keys = common::write_keys_file(&d, "", &[common::TEST_SK_HEX]); + + let cfg_first = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}","{}"],"overload":false}}"#, + keys.display(), + f1.display(), + f2.display() + ), + ); + let sh1 = format!("printf %s \"$A\" > '{d}'/out1", d = d.display()); + let out1 = run_exec(&cfg_first, &sh1, &[]); + assert!( + out1.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out1.stderr) + ); + assert_eq!(std::fs::read(d.join("out1")).unwrap(), b"first-file"); + + let cfg_overload = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}","{}"],"overload":true}}"#, + keys.display(), + f1.display(), + f2.display() + ), + ); + let sh2 = format!("printf %s \"$A\" > '{d}'/out2", d = d.display()); + let out2 = run_exec(&cfg_overload, &sh2, &[]); + assert!( + out2.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out2.stderr) + ); + assert_eq!(std::fs::read(d.join("out2")).unwrap(), b"second-file"); +} + +#[test] +fn same_file_last_assignment_wins() { + let d = common::tmpdir("samelastwin"); + let first_val = "first-value"; + let second_val = "second-value"; + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + format!("SECRET=\"{}\"", common::enc(first_val)), + format!("SECRET=\"{}\"", common::enc(second_val)), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"]}}"#, + keys.display(), + env.display() + ), + ); + let sh = format!("printf %s \"$SECRET\" > '{d}'/secret.out", d = d.display()); + let out = run_exec(&cfg, &sh, &[]); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!( + std::fs::read(d.join("secret.out")).unwrap(), + second_val.as_bytes() + ); +} + +#[test] +fn nul_in_env_value_fails_closed() { + let d = common::tmpdir("nulval"); + let val = "before\0after"; + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + format!("SECRET=\"{}\"", common::enc(val)), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + + // env mode: fails closed with a message about NUL. + let cfg_env = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"]}}"#, + keys.display(), + env.display() + ), + ); + let out = run_exec(&cfg_env, "true", &[]); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("NUL"), "stderr: {stderr}"); + + // files mode: the exact bytes (including the NUL) reach the file. + let secrets_dir = d.join("secrets"); + std::fs::create_dir_all(&secrets_dir).unwrap(); + let cfg_files = write_config( + &d, + &format!( + r#"{{"mode":"files","keys":[{{"file":"{}"}}],"env_files":["{}"],"secrets_dir":"{}"}}"#, + keys.display(), + env.display(), + secrets_dir.display() + ), + ); + let sh = format!( + "cat '{sd}'/SECRET > '{d}'/out", + sd = secrets_dir.display(), + d = d.display() + ); + let out2 = run_exec(&cfg_files, &sh, &[]); + assert!( + out2.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out2.stderr) + ); + assert_eq!(std::fs::read(d.join("out")).unwrap(), val.as_bytes()); +} + +#[test] +fn exec_rejects_non_identifier_key_at_exec_boundary() { + let d = common::tmpdir("badkey"); + // A dotted key like BAD.KEY parses fine as dotenv but is_ident rejects it. + let env = common::write_env_file(&d, ".env", &["BAD.KEY=oops".to_string()]); + let keys = common::write_keys_file(&d, "", &[common::TEST_SK_HEX]); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"]}}"#, + keys.display(), + env.display() + ), + ); + let out = run_exec(&cfg, "true", &[]); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("non-identifier"), + "expected 'non-identifier' in stderr, got: {stderr}" + ); +} diff --git a/tests/exec_conformance/files_mode.rs b/tests/exec_conformance/files_mode.rs new file mode 100644 index 0000000..f9773aa --- /dev/null +++ b/tests/exec_conformance/files_mode.rs @@ -0,0 +1,147 @@ +use std::os::unix::fs::PermissionsExt; +use std::process::Command; + +use crate::common; +use crate::{run_exec, write_config}; + +#[test] +fn files_mode_writes_0600_pointers_and_passthrough() { + let d = common::tmpdir("filesmode"); + let secrets_dir = d.join("secrets"); + std::fs::create_dir_all(&secrets_dir).unwrap(); + let val = "file-secret"; + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + format!("SECRET=\"{}\"", common::enc(val)), + "PLAIN=passthrough-val".to_string(), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"files","keys":[{{"file":"{}"}}],"env_files":["{}"],"secrets_dir":"{}","passthrough":["PLAIN"]}}"#, + keys.display(), + env.display(), + secrets_dir.display() + ), + ); + let sh = format!( + r#"printf %s "$SECRET_FILE" > '{d}'/secret_file.out && \ + cat "$SECRET_FILE" > '{d}'/secret_contents.out && \ + printf %s "${{SECRET:-UNSET}}" > '{d}'/secret_var.out && \ + printf %s "$PLAIN" > '{d}'/plain.out && \ + printf %s "${{POSTMASTER_SECRETS_DIR:-UNSET}}" > '{d}'/secretsdir.out"#, + d = d.display() + ); + let out = run_exec(&cfg, &sh, &[]); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!( + std::fs::read_to_string(d.join("secret_file.out")).unwrap(), + secrets_dir.join("SECRET").display().to_string() + ); + assert_eq!( + std::fs::read(d.join("secret_contents.out")).unwrap(), + val.as_bytes() + ); + assert_eq!(std::fs::read(d.join("secret_var.out")).unwrap(), b"UNSET"); + assert_eq!( + std::fs::read(d.join("plain.out")).unwrap(), + b"passthrough-val" + ); + assert_eq!( + std::fs::read_to_string(d.join("secretsdir.out")).unwrap(), + "UNSET" + ); + + let md = std::fs::metadata(secrets_dir.join("SECRET")).unwrap(); + assert_eq!(md.permissions().mode() & 0o777, 0o600); +} + +#[test] +fn credentials_mode_systemd_pointers() { + let d = common::tmpdir("credsystemd"); + let creds_dir = d.join("creds"); + std::fs::create_dir_all(&creds_dir).unwrap(); + std::fs::write(creds_dir.join("DB_URL"), "abc").unwrap(); + let cfg = write_config(&d, r#"{"mode":"credentials","credential_keys":["DB_URL"]}"#); + let sh = format!( + "printf %s \"$DB_URL_FILE\" > '{d}'/dbfile.out && cat \"$DB_URL_FILE\" > '{d}'/dbcontents.out", + d = d.display() + ); + let out = run_exec( + &cfg, + &sh, + &[("CREDENTIALS_DIRECTORY", creds_dir.to_str().unwrap())], + ); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!( + std::fs::read_to_string(d.join("dbfile.out")).unwrap(), + creds_dir.join("DB_URL").display().to_string() + ); + assert_eq!(std::fs::read(d.join("dbcontents.out")).unwrap(), b"abc"); + + // Without CREDENTIALS_DIRECTORY, the systemd path has nothing to point + // at: fail closed. Explicitly remove from child to ensure hermeticity. + let mut c = Command::new(env!("CARGO_BIN_EXE_postmaster")); + c.args(["exec", "--config"]) + .arg(&cfg) + .args(["--", "/bin/sh", "-c", "true"]) + .env_remove("CREDENTIALS_DIRECTORY"); + let out2 = c.output().unwrap(); + assert!(!out2.status.success()); +} + +#[test] +fn credentials_mode_fetch_loop() { + let d = common::tmpdir("credfetch"); + let secrets_dir = d.join("secrets"); + std::fs::create_dir_all(&secrets_dir).unwrap(); + let sock = d.join("k.sock"); + let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap(); + let server = std::thread::spawn(move || { + if let Ok((mut s, _)) = listener.accept() { + use std::io::Write; + let _ = s.write_all(b"s3cret"); + let _ = s.shutdown(std::net::Shutdown::Both); + } + }); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"credentials","credential_keys":["K"],"sockets":{{"K":"{}"}},"secrets_dir":"{}"}}"#, + sock.display(), + secrets_dir.display() + ), + ); + let sh = format!( + "printf %s \"$CREDENTIALS_DIRECTORY\" > '{d}'/creddir.out && cat '{sd}'/K > '{d}'/kcontents.out", + d = d.display(), + sd = secrets_dir.display() + ); + let out = run_exec(&cfg, &sh, &[]); + server.join().unwrap(); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!( + std::fs::read_to_string(d.join("creddir.out")).unwrap(), + secrets_dir.display().to_string() + ); + assert_eq!(std::fs::read(d.join("kcontents.out")).unwrap(), b"s3cret"); + let md = std::fs::metadata(secrets_dir.join("K")).unwrap(); + assert_eq!(md.permissions().mode() & 0o777, 0o600); +} diff --git a/tests/exec_conformance/keys_verify.rs b/tests/exec_conformance/keys_verify.rs new file mode 100644 index 0000000..fc43921 --- /dev/null +++ b/tests/exec_conformance/keys_verify.rs @@ -0,0 +1,268 @@ +use std::process::Command; + +use crate::common; +use crate::{run_exec, write_config}; + +#[test] +fn rotation_second_key_decrypts() { + let d = common::tmpdir("rotation"); + let val = "rotated-secret"; + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + format!("SECRET=\"{}\"", common::enc(val)), + ], + ); + let bogus = "22".repeat(32); + let keys = common::write_keys_file(&d, "PRODUCTION", &[&bogus, common::TEST_SK_HEX]); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"]}}"#, + keys.display(), + env.display() + ), + ); + let sh = format!("printf %s \"$SECRET\" > '{d}'/out", d = d.display()); + let out = run_exec(&cfg, &sh, &[]); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(std::fs::read(d.join("out")).unwrap(), val.as_bytes()); +} + +#[test] +fn strict_failure_refuses_exec() { + let d = common::tmpdir("strictfail"); + // Encrypt with a DIFFERENT key than the one in our keyring, so + // decryption must fail even though the ciphertext is well-formed. + let other_sk_hex = "22".repeat(32); + let other_sk_bytes = hex::decode(&other_sk_hex).unwrap(); + let other_sk = ecies::SecretKey::parse_slice(&other_sk_bytes).unwrap(); + let other_pk = ecies::PublicKey::from_secret_key(&other_sk); + let ct = ecies::encrypt(&other_pk.serialize_compressed(), b"unreachable").unwrap(); + let b64 = { + use base64::Engine; + base64::engine::general_purpose::STANDARD.encode(ct) + }; + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!( + "DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", + hex::encode(other_pk.serialize_compressed()) + ), + format!("SECRET=\"encrypted:{b64}\""), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"strict":true}}"#, + keys.display(), + env.display() + ), + ); + let sh = format!("printf %s \"$SECRET\" > '{d}'/out", d = d.display()); + let out = run_exec(&cfg, &sh, &[]); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("no key under"), "stderr: {stderr}"); + assert!(!d.join("out").exists()); +} + +#[test] +fn strict_false_skips_undecryptable_and_continues() { + let d = common::tmpdir("laxskip"); + // GOOD decrypts with TEST_SK_HEX; BAD uses a different key so it fails. + let other_sk_hex = "33".repeat(32); + let other_sk_bytes = hex::decode(&other_sk_hex).unwrap(); + let other_sk = ecies::SecretKey::parse_slice(&other_sk_bytes).unwrap(); + let other_pk = ecies::PublicKey::from_secret_key(&other_sk); + let bad_ct = ecies::encrypt(&other_pk.serialize_compressed(), b"unreachable").unwrap(); + let bad_b64 = { + use base64::Engine; + base64::engine::general_purpose::STANDARD.encode(bad_ct) + }; + + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + format!("GOOD=\"{}\"", common::enc("lax-ok")), + format!("BAD=\"encrypted:{bad_b64}\""), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + // strict:false: BAD should be skipped (logged), GOOD should still reach the child. + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"strict":false}}"#, + keys.display(), + env.display() + ), + ); + let sh = format!( + "printf %s \"${{GOOD:-UNSET}}\" > '{d}'/good.out && printf %s \"${{BAD:-UNSET}}\" > '{d}'/bad.out", + d = d.display() + ); + let out = run_exec(&cfg, &sh, &[]); + assert!( + out.status.success(), + "strict:false should continue past undecryptable value and launch the child\nstderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(std::fs::read(d.join("good.out")).unwrap(), b"lax-ok"); + // BAD was skipped: the child sees no BAD env var. + assert_eq!(std::fs::read(d.join("bad.out")).unwrap(), b"UNSET"); + // The stderr should mention the skip. + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("non-strict: skipping BAD"), + "expected skip log in stderr, got: {stderr}" + ); +} + +#[test] +fn verify_keys_aborts_on_stale_keys_with_strict_false() { + // Audit finding #4: --verify-keys should catch stale keys even when + // strict is false. Encrypt with a different key than the one in the + // keyring, set strict:false, and pass --verify-keys. The exec must + // abort with a --verify-keys error rather than launching the child + // with no secrets. + let d = common::tmpdir("verifykeys"); + let other_sk_hex = "33".repeat(32); + let other_sk_bytes = hex::decode(&other_sk_hex).unwrap(); + let other_sk = ecies::SecretKey::parse_slice(&other_sk_bytes).unwrap(); + let other_pk = ecies::PublicKey::from_secret_key(&other_sk); + let ct = ecies::encrypt(&other_pk.serialize_compressed(), b"stale-secret").unwrap(); + let b64 = { + use base64::Engine; + base64::engine::general_purpose::STANDARD.encode(ct) + }; + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!( + "DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", + hex::encode(other_pk.serialize_compressed()) + ), + format!("SECRET=\"encrypted:{b64}\""), + ], + ); + // Keyring has the TEST_SK_HEX key, NOT the other key — keys are stale. + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"strict":false}}"#, + keys.display(), + env.display() + ), + ); + // Without --verify-keys, strict:false would silently skip and succeed. + let sh = "true".to_string(); + let out_no_verify = run_exec(&cfg, &sh, &[]); + assert!( + out_no_verify.status.success(), + "without --verify-keys, strict:false should silently skip: {}", + String::from_utf8_lossy(&out_no_verify.stderr) + ); + + // With --verify-keys, the stale keys must be caught. + let mut c = Command::new(env!("CARGO_BIN_EXE_postmaster")); + c.args(["exec", "--config"]) + .arg(&cfg) + .args(["--verify-keys", "--", "true"]) + .env_remove("SECRET"); + let out = c.output().unwrap(); + assert!( + !out.status.success(), + "--verify-keys should abort on stale keys" + ); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("--verify-keys failed"), + "expected '--verify-keys failed' in stderr, got: {stderr}" + ); +} + +#[test] +fn verify_keys_aborts_on_partial_failure_with_strict_false() { + // Audit 2026-08-02 A3: with strict:false, resolution silently skips + // undecryptable values. When SOME values still decrypt, the resolved + // set is non-empty and the old freshness check passed — the child + // launched with a partial secret set. --verify-keys must now abort + // on any recorded skip. + let d = common::tmpdir("verifykeys-partial"); + let other_sk_hex = "33".repeat(32); + let other_sk_bytes = hex::decode(&other_sk_hex).unwrap(); + let other_sk = ecies::SecretKey::parse_slice(&other_sk_bytes).unwrap(); + let other_pk = ecies::PublicKey::from_secret_key(&other_sk); + let stale_ct = ecies::encrypt(&other_pk.serialize_compressed(), b"stale-secret").unwrap(); + let stale_b64 = { + use base64::Engine; + base64::engine::general_purpose::STANDARD.encode(stale_ct) + }; + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + // Decrypts with the keyring's key — the resolved set is + // non-empty, which is what fooled the old check. + format!("SECRET_GOOD=\"{}\"", common::enc("good-secret")), + // Encrypted to a key NOT in the keyring — skipped under + // strict:false. This is the partial-rotation case. + format!("SECRET_STALE=\"encrypted:{stale_b64}\""), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"strict":false}}"#, + keys.display(), + env.display() + ), + ); + // Without --verify-keys the partial set launches silently: + // SECRET_GOOD is served, SECRET_STALE is dropped. + let out_no_verify = run_exec(&cfg, "test \"$SECRET_GOOD\" = good-secret", &[]); + assert!( + out_no_verify.status.success(), + "without --verify-keys, strict:false should silently serve the partial set: {}", + String::from_utf8_lossy(&out_no_verify.stderr) + ); + + // With --verify-keys, the recorded skip must abort the launch. + let mut c = Command::new(env!("CARGO_BIN_EXE_postmaster")); + c.args(["exec", "--config"]) + .arg(&cfg) + .args(["--verify-keys", "--", "true"]) + .env_remove("SECRET_GOOD") + .env_remove("SECRET_STALE"); + let out = c.output().unwrap(); + assert!( + !out.status.success(), + "--verify-keys should abort on a partial decryption failure" + ); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("--verify-keys failed"), + "expected '--verify-keys failed' in stderr, got: {stderr}" + ); + assert!( + stderr.contains("SECRET_STALE"), + "expected the skipped key name in stderr, got: {stderr}" + ); +} diff --git a/tests/exec_conformance/main.rs b/tests/exec_conformance/main.rs new file mode 100644 index 0000000..ef3c5d9 --- /dev/null +++ b/tests/exec_conformance/main.rs @@ -0,0 +1,89 @@ +#![allow(clippy::unwrap_used, clippy::panic, missing_docs)] + +mod bundle; +#[path = "../common/mod.rs"] +mod common; +mod env_mode; +mod files_mode; +mod keys_verify; + +use postmaster::adapter::KeyNaming; + +use std::path::Path; +use std::process::Command; + +#[test] +fn helper_ciphertext_decrypts_with_test_key() { + let v = common::enc("hello $(rm -rf /) `x` \"q\" \nline2"); + let b64 = v.strip_prefix("encrypted:").unwrap(); + let ct = { + use base64::Engine; + base64::engine::general_purpose::STANDARD + .decode(b64) + .unwrap() + }; + let sk = hex::decode(common::TEST_SK_HEX).unwrap(); + let pt = ecies::decrypt(&sk, &ct).unwrap(); + assert_eq!(pt, b"hello $(rm -rf /) `x` \"q\" \nline2"); +} + +#[test] +fn wrapped_base64_ciphertext_decrypts() { + // Test that decrypt_value tolerates ASCII whitespace in base64 payloads, + // matching dotenvx-rs's lenient decoding behavior. + let plaintext = "wrapped-value"; + let v = common::enc(plaintext); + let b64 = v.strip_prefix("encrypted:").unwrap(); + + // Wrap the base64 by inserting newlines every 20 chars + let mut wrapped = String::from("encrypted:"); + for (i, c) in b64.chars().enumerate() { + if i > 0 && i % 20 == 0 { + wrapped.push('\n'); + } + wrapped.push(c); + } + wrapped.push('\n'); + + // Create a temporary keys file with TEST_SK_HEX + let d = common::tmpdir("wrapped-base64"); + common::write_keys_file(&d, "", &[common::TEST_SK_HEX]); + let keys_path = d.join(".env.keys"); + + // Load the key ring + let ring = postmaster::keys::KeyRing::load(&keys_path, KeyNaming::Env).unwrap(); + + // Create a dummy env file path for error messages + let dummy_env = d.join(".env"); + + // decrypt_value should handle the wrapped (whitespace-containing) payload + let result = + postmaster::keys::decrypt_value(&dummy_env, "TEST_VAR", &wrapped, &ring, KeyNaming::Env); + + assert!(result.is_ok(), "wrapped base64 should decrypt successfully"); + let decrypted = result.unwrap(); + assert_eq!(decrypted.as_slice(), plaintext.as_bytes()); +} + +fn run_exec(config: &Path, sh: &str, envs: &[(&str, &str)]) -> std::process::Output { + let mut c = Command::new(env!("CARGO_BIN_EXE_postmaster")); + c.args(["exec", "--config"]) + .arg(config) + .args(["--", "/bin/sh", "-c", sh]) + // Hermeticity: an ambient SECRET/PLAIN/A in the test runner's own + // environment would flip the precedence-test outcomes below, since + // these are exactly the value-variable names the suite asserts on. + .env_remove("SECRET") + .env_remove("PLAIN") + .env_remove("A"); + for (k, v) in envs { + c.env(k, v); + } + c.output().unwrap() +} + +fn write_config(dir: &Path, json: &str) -> std::path::PathBuf { + let p = dir.join("exec.json"); + std::fs::write(&p, json).unwrap(); + p +} From 0d9268940857852c2afc985fb0b56d40899f34db Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Wed, 5 Aug 2026 07:45:28 -0500 Subject: [PATCH 08/47] docs: add Unsafe Code section (policy + registry of every unsafe site) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Modeled on citadel's docs/src/unsafe-code/: an index with the exception policy and a registry table, plus one page per site group — - signal-deferral: TerminationGuard sigmask/pending/re-raise/Drop (macOS) - macos-libc-boundary: getpeereid(2) peer check + PT_DENY_ATTACH hardening - systemd-fd-ownership: UnixListener::from_raw_fd adoption (Linux) - test-env-mutation: set_var/remove_var on edition 2024, incl. the known per-module-lock gap (tracked separately) Also corrects the [lints.rust] unsafe comment in Cargo.toml: mlockall / setrlimit / set_dumpable are safe rustix wrappers, not unsafe; the actual macOS hardening unsafe is PT_DENY_ATTACH; the comment now points at the new docs section. mdbook build, fmt, clippy, full test suite green. --- Cargo.toml | 16 +++-- docs/src/SUMMARY.md | 8 +++ docs/src/unsafe-code/index.md | 43 +++++++++++++ docs/src/unsafe-code/macos-libc-boundary.md | 65 ++++++++++++++++++++ docs/src/unsafe-code/signal-deferral.md | 58 +++++++++++++++++ docs/src/unsafe-code/systemd-fd-ownership.md | 42 +++++++++++++ docs/src/unsafe-code/test-env-mutation.md | 41 ++++++++++++ 7 files changed, 267 insertions(+), 6 deletions(-) create mode 100644 docs/src/unsafe-code/index.md create mode 100644 docs/src/unsafe-code/macos-libc-boundary.md create mode 100644 docs/src/unsafe-code/signal-deferral.md create mode 100644 docs/src/unsafe-code/systemd-fd-ownership.md create mode 100644 docs/src/unsafe-code/test-env-mutation.md diff --git a/Cargo.toml b/Cargo.toml index c6c7afb..0fab6a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,12 +13,16 @@ repository = "https://github.com/beardedeagle/postmaster" # We use a fairly strict set of lints. One deliberate deviation: we allow # `unsafe_code` (some stricter projects deny it outright). postmaster is a -# syscall-level socket-activation daemon and needs a handful of justified -# `unsafe` blocks (getpeereid(2), best-effort mlock()-style hardening, -# signal-mask deferral around the plaintext-write window, and -# UnixListener::from_raw_fd on the one inherited systemd fd) — each site -# carries a SAFETY comment, so `unsafe_code` is left at rustc's -# default (allow) rather than denied or blanket-warned. +# syscall-boundary daemon and needs a handful of justified `unsafe` blocks: +# getpeereid(2) and PT_DENY_ATTACH on macOS (Darwin's stable kernel ABI is +# libc), signal-mask deferral around the plaintext-write window (macOS), +# UnixListener::from_raw_fd on the inherited systemd sockets (Linux), and +# test-only set_var/remove_var (unsafe on edition 2024). Each site carries +# a SAFETY comment and is documented in docs/src/unsafe-code/ (the mdbook +# "Unsafe Code" section). mlockall/setrlimit/set_dumpable hardening uses +# SAFE rustix wrappers and is not part of the unsafe inventory. So +# `unsafe_code` stays at rustc's default (allow) rather than denied or +# blanket-warned. [lints.rust] future_incompatible = { level = "deny", priority = -1 } rust_2018_idioms = { level = "warn", priority = -1 } diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 747c265..68df15e 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -14,6 +14,14 @@ - [Materialization ABI](./architecture/materialization-abi.md) - [Threat model](./architecture/threat-model.md) +# Unsafe Code + +- [Overview](./unsafe-code/index.md) +- [Signal deferral (macOS)](./unsafe-code/signal-deferral.md) +- [macOS libc boundary](./unsafe-code/macos-libc-boundary.md) +- [systemd fd ownership (Linux)](./unsafe-code/systemd-fd-ownership.md) +- [Test-only env mutation](./unsafe-code/test-env-mutation.md) + # Reference - [CLI reference](./reference/cli.md) diff --git a/docs/src/unsafe-code/index.md b/docs/src/unsafe-code/index.md new file mode 100644 index 0000000..0ca7241 --- /dev/null +++ b/docs/src/unsafe-code/index.md @@ -0,0 +1,43 @@ +# Unsafe Code + +Postmaster deliberately allows `unsafe` at the lint level (documented in +`[lints.rust]` in `Cargo.toml`) because it is a syscall-boundary daemon: +peer-credential checks, anti-debug hardening, signal-mask deferral, and +the systemd socket-activation contract cannot be expressed in safe Rust. +This section documents every approved site. + +## Policy + +Every `unsafe` block requires: + +1. A SAFETY comment at the site covering every UB vector +2. Minimal scope — the smallest possible unsafe block +3. Safe wrappers first — rustix (raw syscalls, no libc FFI) on Linux; + libc only where the platform's stable ABI *is* libc (Darwin) +4. Documentation in this section (registry entry + page) +5. Tests exercising the mitigation where the platform allows + +## Registry + +| Location | Platform | Purpose | Page | +|----------|----------|---------|------| +| `launcher.rs` (TerminationGuard: block/pending/die_by/Drop) | macOS | Defer termination signals across the plaintext-write window | [signal-deferral](./signal-deferral.md) | +| `server.rs` (`peer_euid`) | macOS | Peer credential check via `getpeereid(2)` | [macos-libc-boundary](./macos-libc-boundary.md) | +| `server.rs` (`harden_process`) | macOS, release only | `PT_DENY_ATTACH` anti-debug hardening | [macos-libc-boundary](./macos-libc-boundary.md) | +| `server.rs` (socket activation) | Linux | `UnixListener::from_raw_fd` on systemd-inherited sockets | [systemd-fd-ownership](./systemd-fd-ownership.md) | +| `keys/source.rs`, `keys/env.rs` (test modules) | all, test-only | `set_var`/`remove_var` (unsafe on edition 2024) | [test-env-mutation](./test-env-mutation.md) | + +Note what is NOT in the inventory: `mlockall`, `setrlimit(Core, 0)`, and +`set_dumpable(NotDumpable)` hardening all use **safe** rustix wrappers. + +## Adding Unsafe Code + +1. **Exhaust safe alternatives** — rustix first; is there a safe way at all? +2. **Justify in the platform note** — why this platform has no safe route +3. **Minimize scope** — smallest possible unsafe block +4. **Mitigate all UB vectors** — each one named in the SAFETY comment +5. **Add to this section** — registry entry + a page following this format +6. **Write tests** — verify the mitigations work (or document why untestable) +7. **Get review** — unsafe requires explicit approval + +The bar is intentionally high. Postmaster handles plaintext secrets. diff --git a/docs/src/unsafe-code/macos-libc-boundary.md b/docs/src/unsafe-code/macos-libc-boundary.md new file mode 100644 index 0000000..e6ad38b --- /dev/null +++ b/docs/src/unsafe-code/macos-libc-boundary.md @@ -0,0 +1,65 @@ +# macOS libc Boundary + +Two unrelated `unsafe` sites share one justification: on Darwin the +stable kernel ABI *is* libc, so these calls have no raw-syscall route +(contrast with Linux, where rustix's `linux_raw` backend avoids libc FFI +entirely). + +## getpeereid — peer credential check + +### Location + +``` +src/server.rs — fn peer_euid (macOS cfg only) +``` + +### Purpose + +The credential socket must only answer the service user. On Linux the +daemon reads peer credentials with `SO_PEERCRED` (safe rustix); Darwin +has no `SO_PEERCRED`, so the equivalent is `getpeereid(2)` via libc. + +### UB Vectors and Mitigations + +| Vector | Description | Mitigation | +|--------|-------------|------------| +| Out-param types | `getpeereid` writes a `uid_t` and a `gid_t` | Out-params are exactly `libc::uid_t`/`libc::gid_t` | +| fd validity | The socket fd must stay valid for the call | Borrowed from `stream` for the call's duration only | + +### Remaining Risks + +`getpeereid` establishes *same-euid*, not *same-process*: any process +running as the service user passes. That is an accepted residual of the +UID-based peer model (see the threat model), not a defect of this +wrapper. + +## PT_DENY_ATTACH — anti-debug hardening + +### Location + +``` +src/server.rs — fn harden_process (macOS cfg, release builds only) +``` + +### Purpose + +The ptrace-from-peers half of Linux's `PR_SET_DUMPABLE`: deny debugger +attachment to the daemon. Compiled only under `not(debug_assertions)`; +`[profile.release]` pins `debug-assertions = false` so a profile override +cannot silently compile it out (audit 2026-08-02 A23). Best-effort by +policy, but a failure is security-relevant and is logged (A10). + +### UB Vectors and Mitigations + +| Vector | Description | Mitigation | +|--------|-------------|------------| +| Bad arguments | `ptrace` is variadic-ish FFI | `PT_DENY_ATTACH` takes no pointer arguments: null addr, zero data — the documented invocation | +| Debug-build denial | Attaching a debugger in dev must stay possible | `#[cfg(not(debug_assertions))]` gate | + +## Tests + +The peer check is exercised wherever the daemon integration tests run on +macOS. `PT_DENY_ATTACH` cannot be meaningfully unit-tested (success +means a subsequent attach fails); its release-only gating is pinned by +`debug-assertions = false` in `[profile.release]` and verified by +release-profile clippy in the standard battery. diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md new file mode 100644 index 0000000..8448222 --- /dev/null +++ b/docs/src/unsafe-code/signal-deferral.md @@ -0,0 +1,58 @@ +# Signal Deferral (macOS) + +## Location + +``` +src/launcher.rs — struct TerminationGuard (macOS cfg only) +Blocks: block() (sigmask), pending() (sigpending), die_by() (re-raise), Drop (restore) +``` + +## Purpose + +Audit 2026-08-02 A11: on macOS, plaintext secret files persist on the +ramdisk until explicitly removed, so a SIGTERM landing *during* the +plaintext-write window would leave material on disk with no cleanup. +`TerminationGuard` blocks SIGTERM/SIGINT/SIGHUP/SIGQUIT from just after +config validation until just before `execvp`. Before `execvp`, the +launcher synchronously checks `sigpending`; if a termination signal +arrived during the window, it runs `cleanup_written` and then dies by +that signal (`die_by`). The saved mask is always restored before exec — +a child must never inherit blocked termination signals. + +Linux needs no equivalent: tmpfs does not persist across reboots, +systemd's `ExecStopPost` runs `postmaster cleanup`, and the next +launch's `prune_stale` removes residuals (documented decision, A11). + +## Why Unsafe + +Raw libc signal operations — `sigemptyset`/`sigaddset`, +`pthread_sigmask`, `sigpending`, `signal`, `raise`, `_exit` — are +invisible to Rust's type system: a wrong mask, an invalid `sigset_t`, or +a bad pointer is undefined behavior the compiler cannot reject. Darwin's +stable kernel ABI is libc, so there is no raw-syscall alternative. + +## UB Vectors and Mitigations + +| Vector | Description | Mitigation | +|--------|-------------|------------| +| Invalid `sigset_t` | Uninitialized set passed to libc | `zeroed()` (valid empty representation) then `sigemptyset` | +| Dangling pointers | set/old must outlive each call | Locals live for the full block; no pointers escape | +| Thread-model mismatch | `sigprocmask` is unspecified in multithreaded processes | `pthread_sigmask` form used throughout | +| Async-signal context | Work inside a handler would be unsound | **No handlers are ever installed** — deferral is mask-only; the pending check is synchronous | +| Mask leak to child | Child inheriting blocked termination signals | Mask restored before `execvp` on every path (explicit + `Drop` on early-Err) | +| Lost signal | Deferred signal swallowed | `die_by` resets `SIG_DFL`, restores the saved mask, re-raises; `libc::_exit(128 + sig)` if `raise` itself fails | + +## Remaining Risks + +| Risk | Likelihood | Impact | +|------|------------|--------| +| Kernel/libc signal quirks on future Darwin versions | Very low | Missed deferral (fail-open to pre-A11 behavior) | +| Operator sends SIGKILL | n/a | Unblockable by design; ramdisk contents persist until next boot — accepted residual | + +## Tests + +Exercised by the exec integration suites (`tests/exec_check.rs`, +`tests/exec_conformance/`) for the surrounding write/exec contract. The +guard's restore-before-exec is structural (consuming `Drop`); a direct +signal-race unit test would be timing-flaky by nature and is documented +as intentionally absent. diff --git a/docs/src/unsafe-code/systemd-fd-ownership.md b/docs/src/unsafe-code/systemd-fd-ownership.md new file mode 100644 index 0000000..85dd000 --- /dev/null +++ b/docs/src/unsafe-code/systemd-fd-ownership.md @@ -0,0 +1,42 @@ +# systemd fd Ownership (Linux) + +## Location + +``` +src/server.rs — socket-activation path (Linux cfg only) +``` + +## Purpose + +On Linux, postmaster is socket-activated: the `postmaster-credd.socket` +unit owns the per-(service, key) sockets and the daemon inherits them as +fds `[3, 3+n)`. Serving requires a `UnixListener`, so each inherited fd +is adopted with `UnixListener::from_raw_fd`. + +## Why Unsafe + +`from_raw_fd` asserts *ownership*: if the fd were invalid, duplicated +elsewhere, or owned by someone else, the result is double-close / +use-after-close — undefined behavior the compiler cannot check. + +## UB Vectors and Mitigations + +| Vector | Description | Mitigation | +|--------|-------------|------------| +| Wrong fd | Arbitrary fd adopted by mistake | The `sd_listen_fds(3)` protocol is validated first: `LISTEN_PID` names this process, so fds `[3, 3+n)` are exactly the sockets systemd created for us | +| Double ownership | Some other component also owns the fd | The protocol transfers ownership to this process; nothing else holds these fds | +| fd leak to child | Inherited socket leaking across execvp | `FD_CLOEXEC` is set on the listener immediately after adoption | +| Not-a-socket | Wrong unit passed non-socket fds | `getsockname(2)` mapping to the filesystem path fails closed immediately | + +## Remaining Risks + +| Risk | Likelihood | Impact | +|------|------------|--------| +| Misconfigured unit files (wrong `FileDescriptorName`/count) | Low | Fails closed at startup (path mapping), never serves a wrong socket | + +## Tests + +Not exercised on macOS dev hosts (the macOS leg uses `--bind`, which owns +its socket paths directly). The adoption is one line inside a path that +fails closed on every validation error; the daemon's fetch-loop +integration tests cover the serving behavior that follows it. diff --git a/docs/src/unsafe-code/test-env-mutation.md b/docs/src/unsafe-code/test-env-mutation.md new file mode 100644 index 0000000..2d61bca --- /dev/null +++ b/docs/src/unsafe-code/test-env-mutation.md @@ -0,0 +1,41 @@ +# Test-Only env Mutation + +## Location + +``` +src/keys/source.rs (test module) — 4 sites +src/keys/env.rs (test module) — 2 sites +``` + +## Purpose + +Edition 2024 marks `std::env::set_var`/`remove_var` `unsafe`: mutating +the process environment is a data race in a multithreaded process, and +the Rust test harness runs tests in parallel threads of one process. +Several key-source tests must set or clear `DOTENV_PRIVATE_KEY*` / +`CREDENTIALS_DIRECTORY` to exercise source selection. + +## UB Vectors and Mitigations + +| Vector | Description | Mitigation | +|--------|-------------|------------| +| Concurrent env access | Two tests mutating/reading env at once | Every call site holds a module-level `ENV_LOCK` mutex for the mutation's full scope | +| Lock-ordering | Multiple env-mutating tests in one binary | Single mutex per module; no nested acquisition | + +Each site carries a SAFETY comment naming the serialization discipline. + +## Known Gap (tracked) + +The discipline is currently **per-module, not per-process**: +`keys/source.rs` and `keys/env.rs` (and `keys/mod.rs`'s tests) use +*separate* `ENV_LOCK` statics, and +`keys::tests::from_env_loads_and_fails_closed` mutates env without +holding any lock. Two such tests can still race — the loser may poison a +mutex and fail unrelated tests (~1 in 5 baseline runs observed). The +fix is one shared lock for every env-mutating test; it is tracked on the +project board and deliberately not smuggled into unrelated changes. + +## Tests + +These sites exist *in* tests; the flaky-race card above doubles as their +correctness tracking. From dae7fa1643bccef2cc19538933bfb4ca954acaa9 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Wed, 5 Aug 2026 07:54:35 -0500 Subject: [PATCH 09/47] lints: adopt multiple_crate_versions (clippy) + deny.toml bans companion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per citadel's lint set. The clippy lint is warn-level in Cargo.toml; it fires on exactly one duplicate: syn 2 (pinned by wasm-bindgen, which is target-gated to wasm32-unknown-unknown inside the ecies dep and never compiled for postmaster's real targets) vs syn 3 (serde_derive). The lint has no per-package scoping and the case is uncontrollable until upstream wasm-bindgen moves to syn 3, so lib.rs and main.rs carry a documented crate-root allow, and deny.toml gains [bans] multiple-versions = "warn" with syn skipped — ongoing visibility for convergence and for any NEW duplicates. Verified: fmt, clippy (macOS + x86_64-linux-gnu + release, -D warnings), full test suite, cargo deny. --- Cargo.toml | 1 + deny.toml | 14 ++++++++++++++ src/lib.rs | 9 +++++++++ src/main.rs | 4 ++++ 4 files changed, 28 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 0fab6a0..bed5a14 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -77,6 +77,7 @@ fallible_impl_from = "warn" inefficient_to_string = "warn" macro_use_imports = "warn" match_same_arms = "warn" +multiple_crate_versions = "warn" no_effect_underscore_binding = "warn" panic = "warn" print_stderr = "warn" diff --git a/deny.toml b/deny.toml index f568047..769800f 100644 --- a/deny.toml +++ b/deny.toml @@ -45,3 +45,17 @@ ignore = true # sanctioned git source; drop this entry together with the patch section # once the upstream PR ships in a crates.io release. allow-git = ["https://github.com/beardedeagle/rs.git"] + +[bans] +# Warn on duplicate crate versions — companion to clippy's +# multiple_crate_versions (crate-level; allowed at the crate root for +# exactly the case skipped below, since that lint has no per-package +# scoping). New duplicates should fail review, not land quietly. +multiple-versions = "warn" + +# syn 2 + syn 3 coexist ONLY because wasm-bindgen (target-gated to +# wasm32-unknown-unknown inside the ecies dep, never compiled for +# postmaster's real targets) pins syn 2 while serde_derive uses syn 3 — +# uncontrollable until upstream wasm-bindgen moves. Remove this skip, and +# the crate-root allow in src/lib.rs, when the tree converges. +skip = [{ name = "syn" }] diff --git a/src/lib.rs b/src/lib.rs index 5283799..172589e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,15 @@ //! //! Security and fail-closed semantics are preserved exactly. +// `multiple_crate_versions` is warn-level in Cargo.toml; allowed here for +// exactly one uncontrollable case: syn 2 + syn 3 coexist only because +// wasm-bindgen (target-gated to wasm32-unknown-unknown inside the ecies +// dependency, never compiled for postmaster's real targets) pins syn 2 +// while serde_derive uses syn 3. cargo-deny `[bans].multiple-versions` +// (warn, with syn skipped) keeps watch for the tree converging and for any +// NEW duplicates — remove this allow when syn 2 leaves the tree. +#![allow(clippy::multiple_crate_versions)] + pub mod adapter; pub mod cli; pub mod exec_config; diff --git a/src/main.rs b/src/main.rs index 36379d6..54a89ee 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,10 @@ //! they can be unit-tested. See `lib.rs` and the submodule docs for the //! full security posture, fail-closed design, and invariants. +// See src/lib.rs for why this allow exists (wasm-bindgen's wasm32-gated +// syn 2 vs serde_derive's syn 3; uncontrollable, deny.toml keeps watch). +#![allow(clippy::multiple_crate_versions)] + fn main() -> std::process::ExitCode { postmaster::main() } From b011cdad4ab7dda41693c554c6c7274e186f5ce6 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Wed, 5 Aug 2026 09:16:41 -0500 Subject: [PATCH 10/47] =?UTF-8?q?review:=20address=20PR=20#6=20review=20?= =?UTF-8?q?=E2=80=94=2018=20fixes,=201=20rebuttal,=201=20documented=20resi?= =?UTF-8?q?dual?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Security code: - secret_files: post-open write errors unlink the target via the pinned dir fd; cleanup_written is fd-relative (dir fd + entry names, unlinkat); prune_stale pins the dir once and enumerates/stats/unlinks fd-relative (statat/unlinkat) — no path re-resolution anywhere - launcher: secrets dir opened once (O_DIRECTORY|O_NOFOLLOW|CLOEXEC), shared by write_secret_file and both cleanup paths - cleanup: same fd pinning; tracks failures and only removes the .postmaster-managed sentinel when every managed file was removed (retains it and errors otherwise, so retries aren't refused) - verify_key_sources reuses the runtime key-variable predicate (is_key_var_name) for both key prefixes - uid_of (Linux): id resolved only from verified absolute candidates (/usr/bin/id, /bin/id, /run/current-system/sw/bin/id) — fstat regular file, uid 0, no group/other write - bundle: encoding "utf8" validated at resolution (fail closed) - daemon Entry: deny_unknown_fields (nested, matches root) - HELP_EXEC + Invocation::Exec rustdoc describe the any-skip-aborts --verify-keys semantics Automation: - setup-nix: invoke the official installer correctly (--daemon --yes --no-modify-profile) - setup-rust: enforce the just version pin (install on mismatch) - Justfile: docs-serve uses EXIT trap + subshell; build-matrix applies target-cpu=native only for the native target (arm64|aarch64) and no override for explicit ARM targets; build-all actually builds all six targets; docs/src/changelog.md untracked + gitignored (generated by the docs recipe) Docs: - CHANGELOG gains an Unreleased section for this PR - unsafe-code/signal-deferral documents the pending-check/exec race as an accepted residual (irreducible below fork+exec or a handler+flag design; bounded worst case) Rebutted: the config-compat thread (the types named never lived in config.rs; pub use cli as config preserves every path; battery green). Verified: fmt, clippy (macOS + x86_64-linux-gnu + release, -D warnings), 82 lib + 7 exec_check + 16 exec_conformance tests, cargo deny, cargo audit, mdbook build. --- .github/actions/setup-nix/action.yml | 2 +- .github/actions/setup-rust/action.yml | 22 ++- .gitignore | 3 + CHANGELOG.md | 43 +++++ Justfile | 41 ++-- docs/src/changelog.md | 48 ----- docs/src/unsafe-code/signal-deferral.md | 1 + src/adapter/bundle.rs | 36 +++- src/cli/help.rs | 6 +- src/cli/mod.rs | 37 +++- src/keys/env.rs | 2 +- src/keys/mod.rs | 5 + src/keys/provisioning/cleanup.rs | 199 ++++++++++++++------ src/keys/provisioning/mod.rs | 73 +++++++- src/launcher.rs | 54 ++++-- src/secret_files.rs | 236 +++++++++++++++++------- src/server.rs | 109 ++++++++++- 17 files changed, 683 insertions(+), 234 deletions(-) delete mode 100644 docs/src/changelog.md diff --git a/.github/actions/setup-nix/action.yml b/.github/actions/setup-nix/action.yml index af39a66..8641457 100644 --- a/.github/actions/setup-nix/action.yml +++ b/.github/actions/setup-nix/action.yml @@ -38,7 +38,7 @@ runs: else echo "${INSTALLER_SHA256} ${tmp}" | shasum -a 256 -c - fi - sh "$tmp" install --no-confirm + sh "$tmp" --daemon --yes --no-modify-profile fi # The installer does not put nix on PATH for subsequent GHA steps. if [[ -n "${GITHUB_PATH:-}" ]]; then diff --git a/.github/actions/setup-rust/action.yml b/.github/actions/setup-rust/action.yml index a244074..5aa7b49 100644 --- a/.github/actions/setup-rust/action.yml +++ b/.github/actions/setup-rust/action.yml @@ -60,16 +60,28 @@ runs: # Probe by actually running `just`, not `command -v just`: a mise/asdf # shim on PATH satisfies `command -v` but fails at call time with # "No version is set for shim: just" when no version is pinned. If it - # does not run, install a pinned just and prepend ~/.cargo/bin so the - # real binary shadows any lingering shim for the rest of the job. - if just --version >/dev/null 2>&1; then - echo "just already available: $(command -v just) -> $(just --version)" - else + # does not run, or runs but reports a version other than the pin, install + # the pinned just and prepend ~/.cargo/bin so the real binary shadows + # any lingering shim for the rest of the job. + install_pinned_just() { cargo install just --version "$JUST_VERSION" --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" if [[ -n "${GITHUB_PATH:-}" ]]; then echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" fi "$HOME/.cargo/bin/just" --version + } + if found="$(just --version 2>/dev/null)"; then + # `just --version` reports "just X.Y.Z" + found_version="${found#just }" + if [[ "$found_version" == "$JUST_VERSION" ]]; then + echo "just already available at pinned version: $(command -v just) -> $found" + else + echo "just version mismatch: found '$found', pinned is 'just $JUST_VERSION'; installing pinned version" + install_pinned_just + fi + else + echo "no runnable just found; installing pinned just $JUST_VERSION" + install_pinned_just fi - name: Install cargo-deny diff --git a/.gitignore b/.gitignore index 2119da7..5f8189b 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,9 @@ result-* # mdBook build output (docs/) /docs/book/ +# generated by the docs recipe from /CHANGELOG.md +docs/src/changelog.md + # Additional ignores .omc/ target/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 33e43aa..e4d472f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,49 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Security + +- Remediated all 33 findings of the 2026-08-02 security audit (5 HIGH, + 11 MEDIUM, 17 LOW/INFO — 12 fixed, 4 documented as accepted). +- Bundle entries are now name-bound: a ciphertext decrypts only under its + own entry name (AES-GCM AAD); relocating it fails authentication. + Suite bumped to `ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad`; + pre-AAD bundles are rejected. AAD support comes from the additive + `encrypt_with_aad`/`decrypt_with_aad` on the ecies fork (upstream PR + ecies/rs#159), consumed via a git+rev `[patch.crates-io]` pin. +- Hardening: macOS termination-signal deferral across the plaintext-write + window; logged hardening failures; fd-pinned secret-file writes and + fd-relative prune/cleanup; `O_NOFOLLOW` ciphertext opens; + sentinel-guarded bulk cleanup (`.postmaster-managed`); keychain reads + via the Security.framework API (no `/usr/bin/security`); `--verify-keys` + fails on ANY undecryptable value, including under `strict:false`; + daemon config rejects unknown fields (root and nested); Linux `id` + resolved from verified absolute paths only; setup verification reuses + the runtime key-variable predicate; bundle `encoding: "utf8"` is + validated at resolution. + +### Changed + +- Module restructure per file-size limits (500/750/1000 LOC bands): + `keys/`, `cli/`, `adapter/` domains; conformance suite split under + `tests/exec_conformance/`. +- Dependencies: base64 0.23 plus the minor/patch set (libc 0.2.189, + serde family 1.0.229, serde_json 1.0.151, syn 3.0.3). +- CI automation conforms to the repo doctrine: in-repo composites only + (setup-rust, setup-nix — the latter verifies the pinned installer's + sha256 before executing), actions pinned by sha, workflows consume + just recipes. + +### Added + +- "Unsafe Code" documentation section: exception policy and a registry + of every unsafe site (signal deferral, macOS libc boundary, systemd fd + ownership, test-only env mutation). +- `multiple_crate_versions` clippy lint plus `[bans] multiple-versions` + in deny.toml (syn skipped for the wasm-gated duplicate). + ## [0.1.0] - 2026-07-28 ### Added diff --git a/Justfile b/Justfile index 4d17727..080dd80 100644 --- a/Justfile +++ b/Justfile @@ -51,8 +51,8 @@ docs-serve: #!/usr/bin/env bash set -euo pipefail cp CHANGELOG.md docs/src/changelog.md - cd docs && mdbook serve --open - rm -f docs/src/changelog.md + trap 'rm -f docs/src/changelog.md' EXIT + (cd docs && mdbook serve --open) # ============================================================================= # Dependency policy @@ -152,9 +152,17 @@ build-matrix level target="native": export CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 export CARGO_PROFILE_RELEASE_OPT_LEVEL=3 export CARGO_PROFILE_RELEASE_STRIP=symbols - # Use native CPU for ARM, x86-64-v3 for x86 targets - if [[ "$TARGET" == "macos-arm" ]] || [[ "$TARGET" == "linux-arm" ]] || [[ "$TARGET" == "native" && "$(uname -m)" == "arm64" ]]; then - export RUSTFLAGS="-C target-cpu=native" + # CPU targeting: `native` describes the build HOST, so only apply + # it when the target IS the host. Explicit ARM targets get no + # target-cpu override (toolchain baseline); x86 targets use + # x86-64-v3. + if [[ "$TARGET" == "native" ]]; then + case "$(uname -m)" in + arm64|aarch64) export RUSTFLAGS="-C target-cpu=native" ;; + *) export RUSTFLAGS="-C target-cpu=x86-64-v3" ;; + esac + elif [[ "$TARGET" == "linux-arm" || "$TARGET" == "macos-arm" ]]; then + : # cross-building: no target-cpu override, use toolchain baseline else export RUSTFLAGS="-C target-cpu=x86-64-v3" fi @@ -175,19 +183,16 @@ build-matrix level target="native": # Build all platforms at a given optimization level (requires cross-compilation setup) build-all level="release": - @echo "Building all platforms at '{{level}}' optimization level..." - @echo "Note: Cross-compilation requires 'cross' tool or appropriate toolchains" - @echo "" - just build-matrix {{level}} native - @echo "" - @echo "For cross-compilation to other platforms, install targets with:" - @echo " rustup target add x86_64-unknown-linux-gnu" - @echo " rustup target add x86_64-unknown-linux-musl" - @echo " rustup target add aarch64-unknown-linux-gnu" - @echo " rustup target add x86_64-apple-darwin" - @echo " rustup target add aarch64-apple-darwin" - @echo "" - @echo "Or use 'cross' for easier cross-compilation: cargo install cross" + #!/usr/bin/env bash + set -euo pipefail + echo "Building all platforms at '{{level}}' optimization level..." + echo "Note: cross targets need their toolchains installed first" + echo " (e.g. 'rustup target add '); a missing toolchain fails loudly." + for target in native linux linux-musl linux-arm macos macos-arm; do + echo "" + echo "=== Building target: $target ===" + just build-matrix {{level}} "$target" + done # Show build matrix help build-help: diff --git a/docs/src/changelog.md b/docs/src/changelog.md deleted file mode 100644 index 71fe45a..0000000 --- a/docs/src/changelog.md +++ /dev/null @@ -1,48 +0,0 @@ -# Changelog - -All notable changes to this project are documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -### Added - -- Standalone postmaster binary — a format-neutral local secret - materialization engine that decrypts encrypted inputs at process - launch time, injects them into a child process, and `execvp`s the - target binary. -- `.env` input adapter — wire-compatible with dotenvx-encrypted `.env` - files (ECIES/secp256k1 + HKDF-SHA256 + AES-256-GCM). -- `postmaster_bundle` JSON container format as a second input adapter. -- `KeyNaming` enum (Env, Bundle) for compile-time exhaustive adapter - dispatch — zero vtable overhead, controlled adapter set. -- Three injection modes: `env` (environment variables), `files` - (one-file-per-secret on RAM-backed filesystem), `credentials` - (systemd credentials via postmaster daemon). -- Four key sources: systemd credentials (`LoadCredential=`), files - (`.env.keys` on disk), macOS keychain, environment variables. -- `postmaster exec --check` for config shape validation (CI). -- `postmaster setup --recheck` for runtime key source verification - (host). -- `postmaster setup` interactive command — idempotent, creates keys - directory, verifies permissions, optionally seeds keychain (macOS). -- `postmaster cleanup --config ` subcommand for plaintext - secret file removal. Wired to `ExecStopPost` in systemd. -- `--verify-keys` flag on `exec` for stale key detection after rotation. -- `OFlags::CLOEXEC` on all `rustix::fs::open` call sites. -- RAM backing verification via `hdiutil info` on macOS. -- Pre-execvp zeroization of `KeyRing` and `Resolved` values. -- Symlink rejection at every secret path: `O_NOFOLLOW`, `fstat`, - `symlink_metadata`, `fchmod` on socket fd. -- External binary verification: `codesign -v` on macOS, root-owned - check on Linux. -- Input validation: NUL byte rejection, path traversal rejection, - identifier validation, no shell expansion invariant. -- Threat model documentation covering memory residency, hardening - inheritance across execvp, and the 5-stage secret pipeline. -- `verify_key_freshness` uses `KeyNaming::Env.metadata_prefix()`. -- Two security audits conducted (provider handoff + destination - handoff), all findings fixed. -- Memory hardening audit conducted, all findings fixed. diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md index 8448222..f5b4bf6 100644 --- a/docs/src/unsafe-code/signal-deferral.md +++ b/docs/src/unsafe-code/signal-deferral.md @@ -48,6 +48,7 @@ stable kernel ABI is libc, so there is no raw-syscall alternative. |------|------------|--------| | Kernel/libc signal quirks on future Darwin versions | Very low | Missed deferral (fail-open to pre-A11 behavior) | | Operator sends SIGKILL | n/a | Unblockable by design; ramdisk contents persist until next boot — accepted residual | +| Race: pending-check → mask-restore → exec | Microseconds | A termination signal arriving between the last `sigpending` check and the mask restore is delivered at restore — before `execvp` and before `cleanup_written` — stranding the just-written plaintext. Irreducible below a fork+exec or handler+flag design (both rejected: more unsafe surface and complexity than the window justifies). Worst case is bounded: the ramdisk is destroyed when the launchd job stops. Accepted residual. | ## Tests diff --git a/src/adapter/bundle.rs b/src/adapter/bundle.rs index 11dd8fb..9aa9017 100644 --- a/src/adapter/bundle.rs +++ b/src/adapter/bundle.rs @@ -155,7 +155,19 @@ pub fn resolve_bundle( } } match decrypted { - Some(pt) => out.push((name.clone(), pt, entry.encoding)), + Some(pt) => { + // `utf8` is a promise the bundle makes to env-mode + // consumers: validate it at the trust boundary and fail + // closed — invalid bytes must never flow into an + // environment value. `bytes` entries stay byte-exact. + if entry.encoding == Encoding::Utf8 && std::str::from_utf8(&pt).is_err() { + return Err(format!( + "{}: {name} declares utf8 but is not valid UTF-8", + bundle_path.display() + )); + } + out.push((name.clone(), pt, entry.encoding)); + } None => { let _ = ciphertext; // zeroize on drop // No candidate count in the error text (audit 2026-08-02 A15). @@ -352,6 +364,28 @@ mod tests { assert_eq!(resolved[0].2, Encoding::Bytes); } + #[test] + fn resolve_bundle_rejects_invalid_utf8_when_declared_utf8() { + // An entry declaring `encoding: "utf8"` whose plaintext is not + // valid UTF-8 must fail closed; the same plaintext under + // `encoding: "bytes"` stays byte-exact. + let invalid = b"\xff\xfe"; + let pk = hex::decode(test_pk_hex()).unwrap(); + let ct = BASE64.encode(ecies::encrypt_with_aad(&pk, invalid, b"GREETING").unwrap()); + let ring = crate::keys::tests::make_test_ring(); + + let bundle = make_bundle(vec![("GREETING", &ct, Encoding::Utf8)]); + let err = resolve_bundle(&bundle, &ring, Path::new("/test")).unwrap_err(); + assert!( + err.contains("GREETING declares utf8 but is not valid UTF-8"), + "{err}" + ); + + let bundle = make_bundle(vec![("GREETING", &ct, Encoding::Bytes)]); + let resolved = resolve_bundle(&bundle, &ring, Path::new("/test")).unwrap(); + assert_eq!(&resolved[0].1[..], &invalid[..]); + } + #[test] fn resolve_bundle_multiple_entries() { let ct1 = enc("KEY_A", "value1"); diff --git a/src/cli/help.rs b/src/cli/help.rs index 8311799..b72d5d1 100644 --- a/src/cli/help.rs +++ b/src/cli/help.rs @@ -37,10 +37,12 @@ as files / credential pointers depending on mode), and execs the command.\n\n\ OPTIONS:\n \ --config Exec config JSON (required)\n \ --check Validate config shape only, no decryption, no exec\n \ ---verify-keys Preflight: test-decrypt one value per env file before exec\n \ +--verify-keys Preflight: fail unless EVERY value in every env file decrypts;\n \ +under `strict:false` any skipped/undecryptable value also aborts\n \ +the launch (fail-closed)\n \ -- Everything after `--` is the child argv (required unless --check)\n\n\ The config must specify mode (env/files/credentials), key sources, and\n\ -artifact paths. See docs/src/launcher-contract.md for the full contract.\n"; +artifact paths. See docs/src/reference/launcher-contract.md for the full contract.\n"; /// Help text for the `fetch` subcommand. pub const HELP_FETCH: &str = "postmaster fetch — fetch a secret from a daemon socket\n\n\ diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 48d6d84..4b811e0 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -37,7 +37,9 @@ pub enum KeysSource { } #[derive(Deserialize, Clone, Debug)] -/// A single credential mapping served by postmaster. +#[serde(deny_unknown_fields)] +/// A single credential mapping served by postmaster. Unknown fields are +/// rejected (audit 2026-08-02 A21) — same strictness as `Config`. pub struct Entry { /// encrypted env file (a Nix store path; ciphertext is public). pub env_file: PathBuf, @@ -78,10 +80,11 @@ pub enum Invocation { config: PathBuf, /// Validate config shape only — no decryption, no exec. check: bool, - /// Preflight: attempt a test decryption of one encrypted value - /// from each env file before proceeding to exec. Catches stale - /// keys from a previous rotation cycle that are valid hex but - /// no longer match the ciphertext (audit finding #4). + /// Preflight: fail unless EVERY value in every env file + /// decrypts. Catches stale keys from a previous rotation cycle + /// that are valid hex but no longer match the ciphertext (audit + /// finding #4); under `strict: false` any skipped/undecryptable + /// value also aborts the launch (fail-closed). verify_keys: bool, /// Child argv — everything after `--` on the command line. argv: Vec, @@ -436,6 +439,30 @@ mod tests { assert!(parse(&[]).is_err()); } + #[test] + fn config_rejects_unknown_fields_in_nested_entry() { + // audit 2026-08-02 A21: the nested credential Entry is as strict + // as the top-level Config — an unknown field is a binding bug, + // not something to silently ignore. + let raw = serde_json::json!({ + "keys": {"file": "/run/postmaster/.env.keys"}, + "credentials": { + "/run/cred.sock": {"env_file": "/nix/store/x/.env", "key": "DB_URL", "bogus": 1} + } + }); + let err = serde_json::from_value::(raw).unwrap_err(); + assert!(err.to_string().contains("unknown field"), "{err}"); + + // A well-formed config still parses. + let raw = serde_json::json!({ + "keys": {"credential": "postmaster-keys"}, + "credentials": { + "/run/cred.sock": {"env_file": "/nix/store/x/.env", "key": "DB_URL", "peer_user": "_www"} + } + }); + serde_json::from_value::(raw).unwrap(); + } + #[test] fn parse_unknown_subcommand_fails() { let err = parse(&["bogus"]).unwrap_err(); diff --git a/src/keys/env.rs b/src/keys/env.rs index 2604eea..547d955 100644 --- a/src/keys/env.rs +++ b/src/keys/env.rs @@ -8,7 +8,7 @@ use crate::adapter::KeyNaming; /// True for exactly `PREFIX` or `PREFIX_`. A bare /// prefix match would slurp unrelated variables like /// `DOTENV_PRIVATE_KEYFOO` as key material (audit 2026-08-02 A16). -fn is_key_var_name(prefix: &str, name: &str) -> bool { +pub(crate) fn is_key_var_name(prefix: &str, name: &str) -> bool { name == prefix || name .strip_prefix(prefix) diff --git a/src/keys/mod.rs b/src/keys/mod.rs index b5e6660..c446170 100644 --- a/src/keys/mod.rs +++ b/src/keys/mod.rs @@ -28,6 +28,11 @@ mod verify; /// Re-exported so `crate::keys::verify_external_binary` keeps resolving. pub use verify::verify_external_binary; +/// The exact predicate `KeyRing::from_env` admits, re-exported so setup +/// verification accepts precisely the variables resolution would load +/// (audit 2026-08-02 A16). +pub(crate) use env::is_key_var_name; + /// Full variable name (adapter-specific, e.g. DOTENV_PRIVATE_KEY[_]) /// → candidate secret keys. Multiple candidates per name come from /// comma-separated rotation convention; decryption tries each in order. diff --git a/src/keys/provisioning/cleanup.rs b/src/keys/provisioning/cleanup.rs index e0b1d02..4dc7bde 100644 --- a/src/keys/provisioning/cleanup.rs +++ b/src/keys/provisioning/cleanup.rs @@ -1,8 +1,9 @@ //! `postmaster cleanup` command path. -use std::fs; +use std::os::fd::AsFd; use std::path::Path; +use crate::secret_files::{MANAGED_SENTINEL, open_secrets_dir, read_dir_names}; use crate::server::log; /// `postmaster cleanup`: remove all secret files from the secrets_dir @@ -10,47 +11,42 @@ use crate::server::log; /// or equivalent lifecycle hooks. Does not decrypt — only removes files /// that postmaster would have written. Bulk removal is guarded by the /// `.postmaster-managed` sentinel: a non-empty directory lacking it is -/// refused (postmaster only bulk-deletes directories it manages). Safe -/// to run even if the directory is empty or does not exist. +/// refused (postmaster only bulk-deletes directories it manages). The +/// sentinel is removed last, and ONLY when every managed regular file +/// was removed successfully — on any stat/unlink failure the sentinel +/// is RETAINED and the command fails, so a retry is not refused as +/// unmanaged while plaintext files survive. Safe to run even if the +/// directory is empty or does not exist. pub fn cleanup(config_path: &Path) -> Result<(), String> { let cfg = crate::launcher::parse_exec_config(config_path)?; let dir = cfg .secrets_dir .as_deref() .ok_or("cleanup: config has no secrets_dir — nothing to clean up")?; - // Refuse to bulk-delete in a directory that isn't clearly - // postmaster-managed (audit 2026-08-02 A19): in a symlinked or - // group/world-accessible dir these deletes could hit foreign files. - let md = match fs::symlink_metadata(dir) { - Ok(md) => md, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + // Pin the directory by fd: O_DIRECTORY|O_NOFOLLOW rejects a symlinked + // or non-directory secrets dir at open, and the sentinel check, the + // per-entry stat, and every unlink below are all relative to the + // pinned inode — no path is ever re-resolved (audit 2026-08-02 + // A12/A19). + let dir_fd = match open_secrets_dir(dir) { + Ok(fd) => fd, + Err(rustix::io::Errno::NOENT) => { log(&format!( "cleanup: {} does not exist; nothing to clean up", dir.display() )); return Ok(()); } - Err(e) => return Err(format!("{}: cleanup: {e}", dir.display())), - }; - if md.file_type().is_symlink() || !md.is_dir() { - return Err(format!( - "{}: cleanup: refusing a symlinked or non-directory secrets dir", - dir.display() - )); - } - let entries = match fs::read_dir(dir) { - Ok(e) => e, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - log(&format!( - "cleanup: {} does not exist; nothing to clean up", + Err(e @ (rustix::io::Errno::LOOP | rustix::io::Errno::NOTDIR)) => { + return Err(format!( + "{}: cleanup: refusing a symlinked or non-directory secrets dir ({e})", dir.display() )); - return Ok(()); } Err(e) => return Err(format!("{}: cleanup: {e}", dir.display())), }; - let entries: Vec> = entries.collect(); - if entries.is_empty() { + let names = read_dir_names(&dir_fd).map_err(|e| format!("{}: cleanup: {e}", dir.display()))?; + if names.is_empty() { log(&format!( "cleanup: {} is empty; nothing to clean up", dir.display() @@ -60,60 +56,81 @@ pub fn cleanup(config_path: &Path) -> Result<(), String> { // Managed-dir guard (audit 2026-08-02 A19): non-empty and no // sentinel means postmaster never wrote here — bulk deletes could // hit foreign files. Refuse. - match fs::symlink_metadata(dir.join(crate::secret_files::MANAGED_SENTINEL)) { - Ok(smd) if smd.is_file() => {} + match rustix::fs::statat( + &dir_fd, + MANAGED_SENTINEL, + rustix::fs::AtFlags::SYMLINK_NOFOLLOW, + ) { + Ok(stat) if rustix::fs::FileType::from_raw_mode(stat.st_mode).is_file() => {} _ => { return Err(format!( - "{}: cleanup: no {} sentinel; refusing to bulk-delete in a directory postmaster did not write to", - dir.display(), - crate::secret_files::MANAGED_SENTINEL + "{}: cleanup: no {MANAGED_SENTINEL} sentinel; refusing to bulk-delete in a directory postmaster did not write to", + dir.display() )); } } let mut removed = 0_usize; - for entry in entries { - let entry = match entry { - Ok(e) => e, - Err(e) => { - log(&format!( - "{}: cleanup: skip unreadable entry: {e}", - dir.display() - )); - continue; - } - }; - let path = entry.path(); + let mut had_failure = false; + for name in &names { // The sentinel is infrastructure, not a secret — skipped here // and removed last, so an interrupted cleanup can be re-run. - if entry.file_name().to_str() == Some(crate::secret_files::MANAGED_SENTINEL) { + if name.to_str() == Some(MANAGED_SENTINEL) { continue; } - match fs::symlink_metadata(&path) { - Ok(md) if md.is_file() => { - if let Err(e) = fs::remove_file(&path) { - log(&format!("{}: cleanup: {e}", path.display())); - } else { - removed += 1; + let path = dir.join(name); + match rustix::fs::statat(&dir_fd, name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW) { + Ok(stat) if rustix::fs::FileType::from_raw_mode(stat.st_mode).is_file() => { + match rustix::fs::unlinkat(&dir_fd, name, rustix::fs::AtFlags::empty()) { + Ok(()) => removed += 1, + Err(e) => { + had_failure = true; + log(&format!("{}: cleanup: {e}", path.display())); + } } } - Ok(md) => { + Ok(stat) => { + // Subdirectories and symlinks are skipped, not failures. log(&format!( "{}: cleanup: skipping non-file (type {:?})", path.display(), - md.file_type() + rustix::fs::FileType::from_raw_mode(stat.st_mode) )); } Err(e) => { + had_failure = true; log(&format!("{}: cleanup: stat: {e}", path.display())); } } } - // Remove the sentinel last (see above). - let sentinel = dir.join(crate::secret_files::MANAGED_SENTINEL); - if let Err(e) = fs::remove_file(&sentinel) - && e.kind() != std::io::ErrorKind::NotFound - { - log(&format!("{}: cleanup: {e}", sentinel.display())); + finish_cleanup(&dir_fd, dir, removed, had_failure) +} + +/// Sentinel disposition after the removal pass. The sentinel is removed +/// last (so an interrupted cleanup can be re-run), and ONLY when every +/// managed regular file came out: on any stat/unlink failure it is +/// retained and the command fails — removing it would make the next +/// retry refuse the directory as unmanaged and strand the surviving +/// plaintext files. +fn finish_cleanup( + dir_fd: impl AsFd, + dir: &Path, + removed: usize, + had_failure: bool, +) -> Result<(), String> { + if had_failure { + return Err(format!( + "{}: cleanup: not all files could be removed; retaining the {MANAGED_SENTINEL} sentinel so a retry is not refused as unmanaged", + dir.display() + )); + } + // Remove the sentinel last (see above); best-effort — with every + // secret gone, a surviving sentinel is harmless. + match rustix::fs::unlinkat(dir_fd, MANAGED_SENTINEL, rustix::fs::AtFlags::empty()) { + Ok(()) | Err(rustix::io::Errno::NOENT) => {} + Err(e) => log(&format!( + "{}: cleanup: {e}", + dir.join(MANAGED_SENTINEL).display() + )), } log(&format!( "cleanup: removed {removed} file(s) from {}", @@ -126,6 +143,7 @@ pub fn cleanup(config_path: &Path) -> Result<(), String> { #[allow(clippy::unwrap_used, clippy::panic)] mod tests { use super::*; + use std::fs; #[test] fn cleanup_removes_all_files_from_secrets_dir() { @@ -139,7 +157,7 @@ mod tests { fs::write(dir.join("KEY_A"), b"secret-a").unwrap(); fs::write(dir.join("KEY_B"), b"secret-b").unwrap(); fs::create_dir(dir.join("subdir")).unwrap(); - fs::write(dir.join(crate::secret_files::MANAGED_SENTINEL), b"").unwrap(); + fs::write(dir.join(MANAGED_SENTINEL), b"").unwrap(); let cfg_path = dir.join("exec.json"); fs::write( @@ -157,7 +175,7 @@ mod tests { assert!(!dir.join("KEY_B").exists(), "KEY_B should be removed"); assert!(dir.join("subdir").exists(), "subdir should be preserved"); assert!( - !dir.join(crate::secret_files::MANAGED_SENTINEL).exists(), + !dir.join(MANAGED_SENTINEL).exists(), "sentinel is removed last" ); } @@ -204,4 +222,67 @@ mod tests { assert!(cleanup(&cfg_path).is_ok()); } + + #[test] + fn cleanup_retains_sentinel_after_a_failed_removal() { + // Root bypasses directory permission checks (CAP_DAC_OVERRIDE), + // so the induced unlink failure below only occurs for non-root. + if rustix::process::geteuid().is_root() { + return; + } + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("pm-keyprov-partial-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); + fs::write(dir.join("KEY_A"), b"secret-a").unwrap(); + fs::write(dir.join(MANAGED_SENTINEL), b"").unwrap(); + let cfg_path = dir.join("exec.json"); + fs::write( + &cfg_path, + format!( + r#"{{"mode":"files","keys":["environment"],"env_files":["/nonexistent"],"secrets_dir":"{}"}}"#, + dir.display() + ), + ) + .unwrap(); + // Make every unlink inside the dir fail (EACCES): removal needs + // write permission on the containing directory. Enumeration and + // stat still work (r-x), so KEY_A is found and its removal fails. + fs::set_permissions(&dir, fs::Permissions::from_mode(0o500)).unwrap(); + + let err = cleanup(&cfg_path).unwrap_err(); + + // Restore write permission so the temp dir can be cleaned up. + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); + assert!(err.contains("retaining"), "{err}"); + assert!( + dir.join(MANAGED_SENTINEL).exists(), + "the sentinel must be retained so a retry is not refused as unmanaged" + ); + assert!( + dir.join("KEY_A").exists(), + "the file whose removal failed must still be there" + ); + } + + #[test] + fn finish_cleanup_removes_sentinel_only_without_failures() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("pm-keyprov-finish-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); + fs::write(dir.join(MANAGED_SENTINEL), b"").unwrap(); + let dir_fd = open_secrets_dir(&dir).unwrap(); + + // Failure leg: the sentinel is retained and the command fails. + let err = finish_cleanup(&dir_fd, &dir, 0, true).unwrap_err(); + assert!(err.contains("retaining"), "{err}"); + assert!(dir.join(MANAGED_SENTINEL).exists()); + + // Clean leg: the sentinel goes and the command succeeds. + finish_cleanup(&dir_fd, &dir, 1, false).unwrap(); + assert!(!dir.join(MANAGED_SENTINEL).exists()); + } } diff --git a/src/keys/provisioning/mod.rs b/src/keys/provisioning/mod.rs index 1eb3723..d8d72ee 100644 --- a/src/keys/provisioning/mod.rs +++ b/src/keys/provisioning/mod.rs @@ -375,8 +375,15 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> checked += 1; let env_prefix = KeyNaming::Env.key_prefix(); let bundle_prefix = KeyNaming::Bundle.key_prefix(); - let has_key = std::env::vars() - .any(|(k, _)| k.starts_with(env_prefix) || k.starts_with(bundle_prefix)); + // The SAME predicate KeyRing::from_env applies (audit + // 2026-08-02 A16): a bare starts_with would count a + // prefix-substring collision like DOTENV_PRIVATE_KEYFOO + // as key material that from_env then refuses to load — + // verification must not pass what resolution rejects. + let has_key = std::env::vars().any(|(k, _)| { + crate::keys::is_key_var_name(env_prefix, &k) + || crate::keys::is_key_var_name(bundle_prefix, &k) + }); if !has_key { return Err(format!( "environment: no {env_prefix}* or {bundle_prefix}* variables set" @@ -396,3 +403,65 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> )); Ok(()) } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic)] +mod tests { + use super::*; + + /// Serializes tests that mutate process-global env vars (same + /// pattern as `keys::source::tests::ENV_LOCK`): the test harness + /// runs tests in parallel threads of one process. + static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + fn env_only_cfg() -> ExecConfig { + serde_json::from_str(r#"{"mode":"env","keys":["environment"],"env_files":["/x/.env"]}"#) + .unwrap() + } + + #[test] + fn verify_key_sources_uses_from_env_predicate() { + // audit 2026-08-02 A16: verification must admit exactly what + // KeyRing::from_env admits. A prefix-substring collision like + // DOTENV_PRIVATE_KEYFOO is NOT a key var, so with only such a + // var set, verification must fail. + let _guard = ENV_LOCK.lock().unwrap(); + let cfg = env_only_cfg(); + let bogus = "DOTENV_PRIVATE_KEYFOO_PMVERIFY"; + let valid = "DOTENV_PRIVATE_KEY_PMVERIFY"; + + // Positive leg: an exact `PREFIX_` var passes. Robust + // against any other valid vars a concurrent test may have set. + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized within this module via ENV_LOCK; the + // var names are unique to this test. + unsafe { + std::env::set_var(valid, "aa".repeat(32)); + } + assert!( + verify_key_sources(&cfg, &[]).is_ok(), + "an exact PREFIX_ variable must pass verification" + ); + + // Negative leg: only a prefix-substring collision remains. + unsafe { + std::env::remove_var(valid); + std::env::set_var(bogus, "aa".repeat(32)); + } + let res = verify_key_sources(&cfg, &[]); + unsafe { + std::env::remove_var(bogus); + } + // env.rs's from_env test holds a valid DOTENV_PRIVATE_KEY_* var + // for a microsecond window; if any valid key var was present, + // the negative leg is not observable — skip rather than flake. + let any_valid = std::env::vars().any(|(k, _)| { + crate::keys::is_key_var_name(KeyNaming::Env.key_prefix(), &k) + || crate::keys::is_key_var_name(KeyNaming::Bundle.key_prefix(), &k) + }); + if !any_valid { + let err = res.expect_err("a prefix-substring variable must fail verification"); + assert!(err.contains("environment:"), "{err}"); + } + } +} diff --git a/src/launcher.rs b/src/launcher.rs index 68c6c8c..ab5ba02 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -18,7 +18,9 @@ use crate::exec_config::{ExecConfig, ExecMode}; use crate::key_source::load_ring; use crate::keys::resolve_all; use crate::ramdisk::verify_ramdisk; -use crate::secret_files::{Resolved, cleanup_written, env_pairs, prune_stale, write_secret_file}; +use crate::secret_files::{ + Resolved, cleanup_written, env_pairs, open_secrets_dir, prune_stale, write_secret_file, +}; use crate::server::{fetch_bytes, log, read_capped}; /// macOS-only guard deferring termination signals across the window where @@ -279,10 +281,16 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() // 2026-08-02 A11; no-op on Linux — see TerminationGuard docs). let sig_guard = TerminationGuard::block(); let mut extra: Vec<(OsString, OsString)> = Vec::new(); - // Plaintext files written by Files/Credentials modes, tracked across - // the match so the exec-failure path can remove them (audit - // 2026-08-02 A9). - let mut written: Vec = Vec::new(); + // Names of plaintext files written beneath the pinned secrets-dir + // fd, tracked across the match so the failure paths can unlink them + // fd-relative (audit 2026-08-02 A9). + let mut written: Vec = Vec::new(); + // The pinned secrets-dir fd (Files / Credentials-fetch modes only). + // Opened ONCE with O_DIRECTORY|O_NOFOLLOW|O_RDONLY|CLOEXEC and kept + // until after the exec-failure cleanup, so every write and every + // cleanup unlink is relative to the same pinned inode (audit + // 2026-08-02 A12). + let mut secrets_dir_fd: Option = None; match cfg.mode { ExecMode::Env => { @@ -328,20 +336,25 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() // Prune stale secret files from a prior launch before writing new ones. let keep_keys: Vec = resolved.iter().map(|(k, _)| k.clone()).collect(); prune_stale(dir, &keep_keys)?; + // Pin the secrets dir for the whole write window: the writes, + // the mid-loop cleanups, and the post-match cleanups all act + // relative to this one pinned fd. + let dir_fd = open_secrets_dir(dir) + .map_err(|e| format!("{}: {e} (refusing to follow a symlink)", dir.display()))?; written.reserve(resolved.len()); for (k, v) in &resolved { - let path = match write_secret_file(dir, k, v) { + let path = match write_secret_file(&dir_fd, dir, k, v) { Ok(p) => p, Err(e) => { - cleanup_written(&written); + cleanup_written(&dir_fd, &written); return Err(e); } }; - written.push(path.clone()); + written.push(k.clone()); extra.push((OsString::from(format!("{k}_FILE")), path.into_os_string())); if cfg.passthrough.iter().any(|p| p == k) { if v.contains(&0) { - cleanup_written(&written); + cleanup_written(&dir_fd, &written); return Err(format!("{k}: passthrough value contains NUL")); } extra.push((OsString::from(k.clone()), OsString::from_vec(v.to_vec()))); @@ -352,6 +365,7 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() // (extra: OsString pairs) survive to execvp, not the // plaintext values themselves. drop(resolved); + secrets_dir_fd = Some(dir_fd); } ExecMode::Credentials => { if cfg.credential_keys.is_empty() { @@ -381,6 +395,11 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() let sockets: &HashMap = &cfg.sockets; // Prune stale credential files from a prior launch. prune_stale(dir, &cfg.credential_keys)?; + // Pin the secrets dir for the whole fetch/write window + // (same single-fd discipline as files mode). + let dir_fd = open_secrets_dir(dir).map_err(|e| { + format!("{}: {e} (refusing to follow a symlink)", dir.display()) + })?; written.reserve(cfg.credential_keys.len()); for k in &cfg.credential_keys { let sock = sockets @@ -389,24 +408,25 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() let bytes = match fetch_bytes(sock) { Ok(b) => b, Err(e) => { - cleanup_written(&written); + cleanup_written(&dir_fd, &written); return Err(e); } }; - let path = match write_secret_file(dir, k, &bytes) { + let path = match write_secret_file(&dir_fd, dir, k, &bytes) { Ok(p) => p, Err(e) => { - cleanup_written(&written); + cleanup_written(&dir_fd, &written); return Err(e); } }; - written.push(path.clone()); + written.push(k.clone()); extra.push((OsString::from(format!("{k}_FILE")), path.into_os_string())); } extra.push(( OsString::from("CREDENTIALS_DIRECTORY"), dir.as_os_str().to_os_string(), )); + secrets_dir_fd = Some(dir_fd); } } } @@ -414,7 +434,9 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() // A termination signal arrived during the write window: remove the // plaintext, then die by that signal as the sender intended (A11). if let Some(sig) = sig_guard.pending() { - cleanup_written(&written); + if let Some(dir_fd) = &secrets_dir_fd { + cleanup_written(dir_fd, &written); + } sig_guard.die_by(sig); } // Restore the signal mask before execvp — the child must not inherit @@ -428,7 +450,9 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() // plaintext secret files written above would otherwise persist // (the macOS ramdisk survives process death). Remove them before // returning the error (audit 2026-08-02 A9). - cleanup_written(&written); + if let Some(dir_fd) = &secrets_dir_fd { + cleanup_written(dir_fd, &written); + } log(&format!("exec {program}: {err}")); Err(format!("exec {program}: {err}")) } diff --git a/src/secret_files.rs b/src/secret_files.rs index 7cd44ad..c263f5d 100644 --- a/src/secret_files.rs +++ b/src/secret_files.rs @@ -2,11 +2,15 @@ //! secret files on RAM-backed filesystems. //! //! All file operations use `O_NOFOLLOW` and fd-based permissions to -//! eliminate TOCTOU race conditions against symlink attacks. +//! eliminate TOCTOU race conditions against symlink attacks. The secrets +//! directory is pinned once by an open fd (`O_DIRECTORY|O_NOFOLLOW`) and +//! every create, stat, and unlink is relative to that pinned inode — +//! paths are never re-resolved. use std::ffi::OsString; use std::fs; use std::io::Write; +use std::os::fd::{AsFd, OwnedFd}; use std::os::unix::ffi::OsStringExt; use std::path::{Path, PathBuf}; @@ -38,17 +42,12 @@ pub fn env_pairs(resolved: &Resolved) -> Result, Strin Ok(out) } -/// Writes `value` to `dir.join(key)`. Invariant this enforces: plaintext -/// lands only on the mount `verify_ramdisk` already checked — a symlink -/// planted at the target path (e.g. by leftover/attacker-controlled state -/// in a per-service ramdisk dir that persists across restarts) must never -/// be followed onto persistent disk, so the open refuses symlinks -/// (`O_NOFOLLOW`) and fails closed instead. The directory itself is -/// pinned by fd (audit 2026-08-02 A12): a symlink swapped in at `dir` -/// after the caller's checks is rejected, and the file open is relative -/// to the pinned directory inode, not a path re-resolution. -pub fn write_secret_file(dir: &Path, key: &str, value: &[u8]) -> Result { - let dir_fd = rustix::fs::open( +/// Open and pin a secrets directory by fd: `O_RDONLY|O_DIRECTORY| +/// O_NOFOLLOW|O_CLOEXEC` rejects a symlink or non-directory at open and +/// pins the inode, so subsequent `*at` operations are relative to it +/// rather than to a re-resolved path (audit 2026-08-02 A12). +pub(crate) fn open_secrets_dir(dir: &Path) -> rustix::io::Result { + rustix::fs::open( dir, rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::DIRECTORY @@ -56,12 +55,58 @@ pub fn write_secret_file(dir: &Path, key: &str, value: &[u8]) -> Result rustix::io::Result> { + let reader = match rustix::fs::Dir::read_from(dir_fd) { + Ok(r) => r, + // Raced away between the open and here: nothing inside. + Err(rustix::io::Errno::NOENT) => return Ok(Vec::new()), + Err(e) => return Err(e), + }; + let mut names = Vec::new(); + for entry in reader { + let entry = entry?; + let name = entry.file_name().to_bytes(); + if name == b"." || name == b".." { + continue; + } + names.push(OsString::from_vec(name.to_vec())); + } + Ok(names) +} + +/// Writes `value` to `key` beneath the pinned secrets-dir fd `dir_fd` +/// and returns `dir.join(key)` for the `{KEY}_FILE` pointer. Invariant +/// this enforces: plaintext lands only on the mount `verify_ramdisk` +/// already checked — a symlink planted at the target path (e.g. by +/// leftover/attacker-controlled state in a per-service ramdisk dir that +/// persists across restarts) must never be followed onto persistent +/// disk, so the open refuses symlinks (`O_NOFOLLOW`) and fails closed +/// instead. The directory is pinned by the caller's fd (audit +/// 2026-08-02 A12): a symlink swapped in at `dir` after the caller's +/// checks is rejected, and the file open is relative to the pinned +/// directory inode, not a path re-resolution. On any post-open error +/// the just-created/truncated target is unlinked fd-relative before the +/// error is returned — the caller only learns the names of successful +/// writes, so it could never clean up a partial file itself. +pub fn write_secret_file( + dir_fd: impl AsFd, + dir: &Path, + key: &str, + value: &[u8], +) -> Result { + let dir_fd = dir_fd.as_fd(); let path = dir.join(key); // Drop the managed-dir sentinel (audit 2026-08-02 A19): prune_stale // and cleanup refuse to bulk-delete in a non-empty dir lacking it. let _sentinel_fd = rustix::fs::openat( - &dir_fd, + dir_fd, MANAGED_SENTINEL, rustix::fs::OFlags::WRONLY | rustix::fs::OFlags::CREATE @@ -78,7 +123,7 @@ pub fn write_secret_file(dir: &Path, key: &str, value: &[u8]) -> Result Result Result<(), String> { let keep: std::collections::HashSet<&str> = keep_keys.iter().map(String::as_str).collect(); - // Symlinked or non-directory secrets dir: refuse outright. - let md = match fs::symlink_metadata(dir) { - Ok(md) => md, + // Pin the directory by fd: O_DIRECTORY|O_NOFOLLOW rejects a symlinked + // or non-directory secrets dir at open, and the sentinel check, the + // per-entry stat, and every unlink below are all relative to the + // pinned inode — no path is ever re-resolved (audit 2026-08-02 A12). + let dir_fd = match open_secrets_dir(dir) { + Ok(fd) => fd, // If the directory does not exist yet, there is nothing to prune. - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(e) => return Err(format!("{}: prune: {e}", dir.display())), - }; - if md.file_type().is_symlink() || !md.is_dir() { - return Err(format!( - "{}: prune: refusing a symlinked or non-directory secrets dir", - dir.display() - )); - } - let entries = match fs::read_dir(dir) { - Ok(e) => e, - // Raced away between the stat and here: nothing to prune. - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(rustix::io::Errno::NOENT) => return Ok(()), + Err(e @ (rustix::io::Errno::LOOP | rustix::io::Errno::NOTDIR)) => { + return Err(format!( + "{}: prune: refusing a symlinked or non-directory secrets dir ({e})", + dir.display() + )); + } Err(e) => return Err(format!("{}: prune: {e}", dir.display())), }; - let entries: Vec> = entries.collect(); + let names = read_dir_names(&dir_fd).map_err(|e| format!("{}: prune: {e}", dir.display()))?; // An empty directory is trivially safe (first launch). - if entries.is_empty() { + if names.is_empty() { return Ok(()); } // Managed-dir guard (audit 2026-08-02 A19): non-empty and no // sentinel means postmaster never wrote here — bulk deletes could // hit foreign files. Refuse. - match fs::symlink_metadata(dir.join(MANAGED_SENTINEL)) { - Ok(smd) if smd.is_file() => {} + match rustix::fs::statat( + &dir_fd, + MANAGED_SENTINEL, + rustix::fs::AtFlags::SYMLINK_NOFOLLOW, + ) { + Ok(stat) if rustix::fs::FileType::from_raw_mode(stat.st_mode).is_file() => {} _ => { return Err(format!( "{}: prune: no {MANAGED_SENTINEL} sentinel; refusing to bulk-delete in a directory postmaster did not write to", @@ -152,18 +210,7 @@ pub fn prune_stale(dir: &Path, keep_keys: &[String]) -> Result<(), String> { )); } } - for entry in entries { - let entry = match entry { - Ok(e) => e, - Err(e) => { - crate::server::log(&format!( - "{}: prune: skip unreadable entry: {e}", - dir.display() - )); - continue; - } - }; - let name = entry.file_name(); + for name in &names { let Some(name_str) = name.to_str() else { continue; }; @@ -172,19 +219,21 @@ pub fn prune_stale(dir: &Path, keep_keys: &[String]) -> Result<(), String> { continue; } // Only unlink regular files; skip subdirectories and symlinks to - // avoid following attacker-controlled links in a shared dir. - let path = entry.path(); - match fs::symlink_metadata(&path) { - Ok(md) if md.is_file() => { - if let Err(e) = fs::remove_file(&path) { + // avoid following attacker-controlled links in a shared dir. Both + // the stat (SYMLINK_NOFOLLOW) and the unlink are relative to the + // pinned dir fd, so a swapped entry cannot redirect either one. + let path = dir.join(name); + match rustix::fs::statat(&dir_fd, name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW) { + Ok(stat) if rustix::fs::FileType::from_raw_mode(stat.st_mode).is_file() => { + if let Err(e) = rustix::fs::unlinkat(&dir_fd, name, rustix::fs::AtFlags::empty()) { crate::server::log(&format!("{}: prune: {e}", path.display())); } } - Ok(md) => { + Ok(stat) => { crate::server::log(&format!( "{}: prune: skipping non-file (type {:?})", path.display(), - md.file_type() + rustix::fs::FileType::from_raw_mode(stat.st_mode) )); } Err(e) => { @@ -219,6 +268,26 @@ mod tests { assert!(env_pairs(&bad).unwrap_err().contains("NUL")); } + #[test] + fn write_secret_file_writes_0600_via_pinned_fd() { + use std::os::unix::fs::PermissionsExt; + let dir = tdir("write-ok"); + let dir_fd = open_secrets_dir(&dir).unwrap(); + + let path = write_secret_file(&dir_fd, &dir, "KEY", b"plaintext").unwrap(); + + assert_eq!(fs::read(&path).unwrap(), b"plaintext"); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600, + "secret file must be owner-only" + ); + assert!( + dir.join(MANAGED_SENTINEL).exists(), + "the write drops the managed-dir sentinel (A19)" + ); + } + #[test] fn write_secret_file_refuses_symlink() { let dir = tdir("symlink"); @@ -229,7 +298,8 @@ mod tests { let link_path = dir.join("KEY"); std::os::unix::fs::symlink(&real_target, &link_path).unwrap(); - let result = write_secret_file(&dir, "KEY", b"attacker-controlled-plaintext"); + let dir_fd = open_secrets_dir(&dir).unwrap(); + let result = write_secret_file(&dir_fd, &dir, "KEY", b"attacker-controlled-plaintext"); assert!( result.is_err(), @@ -276,6 +346,23 @@ mod tests { assert!(dir.join("FOREIGN").exists(), "nothing may be deleted"); } + #[test] + fn prune_stale_refuses_symlinked_dir() { + // A symlink swapped in at the secrets-dir path itself must be + // rejected at open (O_DIRECTORY|O_NOFOLLOW), never traversed. + let dir = tdir("prune-symlinked"); + let real = dir.join("real"); + fs::create_dir(&real).unwrap(); + fs::write(real.join("FOREIGN"), b"not-ours").unwrap(); + let link = dir.join("link"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + + let err = prune_stale(&link, &[]).unwrap_err(); + + assert!(err.contains("refusing"), "{err}"); + assert!(real.join("FOREIGN").exists(), "nothing may be deleted"); + } + #[test] fn prune_stale_empty_dir_needs_no_sentinel() { // First launch: the secrets dir exists but is empty — nothing to @@ -291,11 +378,21 @@ mod tests { fs::create_dir(dir.join("subdir")).unwrap(); // A file that is kept should survive. fs::write(dir.join("KEEP_ME"), b"data").unwrap(); + // A symlink is skipped too — prune never follows links in a + // shared dir. + std::os::unix::fs::symlink(dir.join("KEEP_ME"), dir.join("a-link")).unwrap(); fs::write(dir.join(MANAGED_SENTINEL), b"").unwrap(); prune_stale(&dir, &["KEEP_ME".to_string()]).unwrap(); assert!(dir.join("KEEP_ME").exists()); assert!(dir.join("subdir").is_dir(), "subdir should not be removed"); + assert!( + fs::symlink_metadata(dir.join("a-link")) + .unwrap() + .file_type() + .is_symlink(), + "symlink should be skipped, not unlinked" + ); // Non-existent directory: no error, nothing to prune. let ghost = dir.join("does-not-exist"); @@ -309,8 +406,13 @@ mod tests { let f2 = dir.join("B"); fs::write(&f1, b"secret-a").unwrap(); fs::write(&f2, b"secret-b").unwrap(); + let dir_fd = open_secrets_dir(&dir).unwrap(); - cleanup_written(&[f1.clone(), f2.clone()]); + // A name that does not exist is ignored (best-effort). + cleanup_written( + &dir_fd, + &["A".to_string(), "B".to_string(), "MISSING".to_string()], + ); assert!(!f1.exists(), "cleanup should unlink f1"); assert!(!f2.exists(), "cleanup should unlink f2"); diff --git a/src/server.rs b/src/server.rs index f30ab8f..ecbfd8a 100644 --- a/src/server.rs +++ b/src/server.rs @@ -255,20 +255,26 @@ pub fn harden_process() { /// Resolve a user name to a uid without getpwnam FFI. pub fn uid_of(name: &str) -> Result { - #[cfg(target_os = "macos")] - const ID: &str = "/usr/bin/id"; - #[cfg(not(target_os = "macos"))] - const ID: &str = "id"; // Trust boundary (audit 2026-08-02 O2): a compromised `id` returning - // a wrong uid would defeat the socket peer-uid ACL. Verify before - // invoking where we invoke by absolute path under SIP (macOS); on - // Linux the lookup is PATH-relative config trust with no signing root. + // a wrong uid would defeat the socket peer-uid ACL. macOS invokes + // /usr/bin/id by absolute path under SIP, verified via codesign. + // Linux never uses PATH resolution — a PATH-resolved `id` would + // inherit a potentially attacker-controlled PATH; instead the first + // candidate absolute path that verifies (regular file, root-owned, + // no group/other write bits — checked by fstat on an + // O_NOFOLLOW|CLOEXEC fd) is invoked, and if none verifies the lookup + // fails closed. #[cfg(target_os = "macos")] - crate::keys::verify_external_binary(Path::new(ID))?; - let out = std::process::Command::new(ID) + let id: &str = { + crate::keys::verify_external_binary(Path::new("/usr/bin/id"))?; + "/usr/bin/id" + }; + #[cfg(not(target_os = "macos"))] + let id: &str = verified_id_binary()?; + let out = std::process::Command::new(id) .args(["-u", name]) .output() - .map_err(|e| format!("{ID}: {e}"))?; + .map_err(|e| format!("{id}: {e}"))?; if !out.status.success() { return Err(format!("peer_user {name:?}: no such user")); } @@ -278,6 +284,58 @@ pub fn uid_of(name: &str) -> Result { .map_err(|_| format!("peer_user {name:?}: `id -u` output not a uid")) } +/// First `id(1)` candidate that exists and verifies, or a fail-closed +/// error listing why each was rejected (Linux only — see `uid_of`). +/// Candidates are well-known absolute paths in preference order; the +/// NixOS path covers systems without /usr/bin or /bin. +#[cfg(not(target_os = "macos"))] +fn verified_id_binary() -> Result<&'static str, String> { + const CANDIDATES: [&str; 3] = ["/usr/bin/id", "/bin/id", "/run/current-system/sw/bin/id"]; + let mut failures: Vec = Vec::new(); + for path in CANDIDATES { + match verify_id_candidate(path) { + Ok(()) => return Ok(path), + Err(e) => failures.push(e), + } + } + Err(format!( + "no trustworthy `id` binary found (refusing PATH resolution; tried {}): {}", + CANDIDATES.join(", "), + failures.join("; ") + )) +} + +/// Verify one `id(1)` candidate by fstat on the opened fd +/// (O_NOFOLLOW|CLOEXEC, so a symlink at the path is rejected at open): +/// must be a regular file, owned by root, with no group/other write +/// bits. Same fd-based discipline as the keys-file checks — nothing is +/// ever re-resolved by path (audit 2026-08-02 O2). +#[cfg(not(target_os = "macos"))] +fn verify_id_candidate(path: &str) -> Result<(), String> { + let fd = rustix::fs::open( + path, + rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC, + rustix::fs::Mode::empty(), + ) + .map_err(|e| format!("{path}: {e}"))?; + let stat = rustix::fs::fstat(&fd).map_err(|e| format!("{path}: fstat: {e}"))?; + if !rustix::fs::FileType::from_raw_mode(stat.st_mode).is_file() { + return Err(format!("{path}: not a regular file")); + } + if stat.st_uid != 0 { + return Err(format!( + "{path}: owned by uid {} (expected root/0); refusing to trust", + stat.st_uid + )); + } + if rustix::fs::Mode::from_bits_truncate(stat.st_mode) + .intersects(rustix::fs::Mode::WGRP | rustix::fs::Mode::WOTH) + { + return Err(format!("{path}: group/other writable; refusing to trust")); + } + Ok(()) +} + /// Resolve the keys file path from a `KeysSource` configuration. pub fn keys_path(source: &KeysSource) -> Result { match source { @@ -518,4 +576,35 @@ mod tests { assert!(fetch_bytes(&sock).unwrap_err().contains("zero bytes")); t.join().unwrap(); } + + #[test] + #[cfg(not(target_os = "macos"))] + fn verify_id_candidate_rejects_untrusted_file() { + // A user-owned, group/other-writable file must fail: non-root + // runs trip the root-ownership check, root runs trip the + // write-bits check — either way the file is refused. + use std::os::unix::fs::PermissionsExt; + let path = std::env::temp_dir().join(format!("pm-idfake-{}", std::process::id())); + fs::write(&path, b"fake id").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o666)).unwrap(); + let p = path.to_str().unwrap().to_string(); + + let err = verify_id_candidate(&p).unwrap_err(); + + let _ = fs::remove_file(&path); + assert!( + err.contains("owned by uid") || err.contains("writable"), + "{err}" + ); + } + + #[test] + #[cfg(not(target_os = "macos"))] + fn verified_id_binary_finds_a_system_id() { + // On any Linux host at least one candidate must verify — glibc + // systems have /usr/bin/id or /bin/id, NixOS has + // /run/current-system/sw/bin/id. + let id = verified_id_binary().unwrap(); + assert!(id.starts_with('/')); + } } From 776cbd009692437c7883d9750b67bc1969f85e78 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Wed, 5 Aug 2026 09:27:27 -0500 Subject: [PATCH 11/47] docs: move the signal pending/exec race residual to the threat model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The unsafe-code section documents unsafe *usage* (UB vectors and their mitigations) only. The pending-check/exec window is a design-level logic race in how the launcher uses the guard, not a property of the unsafe blocks — it belongs in the threat model's plaintext-persistence section, where it now lives. signal-deferral.md keeps a cross-reference only; the PR thread comment was updated to match. --- docs/src/architecture/threat-model.md | 14 ++++++++++++++ docs/src/unsafe-code/signal-deferral.md | 7 ++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index 54b890b..bebf0c6 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -451,6 +451,20 @@ ramdisk is destroyed when the `postmaster-ramdisk` launchd job stops. The `prune_stale` function also removes stale files from prior launches before writing new ones. +On macOS, a `TerminationGuard` additionally blocks +SIGTERM/SIGINT/SIGHUP/SIGQUIT across the write window; before `execvp` +the launcher checks `sigpending` and, if a termination signal arrived +during the window, removes the plaintext and dies by that signal +(audit 2026-08-02 A11). + +*Accepted residual:* a termination signal arriving between that final +pending check and the mask restore/exec is delivered at restore — +before `execvp` and before cleanup — stranding the just-written +plaintext. The window is microseconds and irreducible below a +fork+exec or handler+flag design (both rejected: more unsafe surface +and complexity than the window justifies); the worst case is bounded +because the ramdisk is destroyed when the launchd job stops. + ### Ramdisk mount verification (macOS) — Mitigated `verify_ramdisk` verifies the mount is RAM-backed by parsing diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md index f5b4bf6..51ece83 100644 --- a/docs/src/unsafe-code/signal-deferral.md +++ b/docs/src/unsafe-code/signal-deferral.md @@ -48,7 +48,12 @@ stable kernel ABI is libc, so there is no raw-syscall alternative. |------|------------|--------| | Kernel/libc signal quirks on future Darwin versions | Very low | Missed deferral (fail-open to pre-A11 behavior) | | Operator sends SIGKILL | n/a | Unblockable by design; ramdisk contents persist until next boot — accepted residual | -| Race: pending-check → mask-restore → exec | Microseconds | A termination signal arriving between the last `sigpending` check and the mask restore is delivered at restore — before `execvp` and before `cleanup_written` — stranding the just-written plaintext. Irreducible below a fork+exec or handler+flag design (both rejected: more unsafe surface and complexity than the window justifies). Worst case is bounded: the ramdisk is destroyed when the launchd job stops. Accepted residual. | + +For the design-level race in how the guard is *used* (pending-check → +mask-restore → exec — a property of the launch flow, not of these +unsafe blocks), see the threat model's +[plaintext persistence window](../architecture/threat-model.md#plaintext-file-persistence-window-files-mode--mitigated) +section. ## Tests From a0322622348fe7b864849c2c010035293ce52c55 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Wed, 5 Aug 2026 15:17:26 -0500 Subject: [PATCH 12/47] fix(launcher): close the termination-signal check/exec race (A11 follow-up) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pending-check/exec handoff had a documented residual: a termination signal arriving between the final sigpending check and the mask restore was delivered at restore — before execvp, before cleanup — stranding plaintext on the ramdisk. Microseconds-wide, but nonzero. The guard now disarms by installing a flag-recording handler while the signals are still blocked, then restoring the mask: anything pending from the window is delivered to the handler (a single atomic store — the canonical async-signal-safe operation), never to the default disposition, so no termination signal can kill the launcher without cleanup_written running first. sigaction rc failures fall back to the previous pending-check behavior with a log line (fail closed into the old behavior, never silently weaker). This is not a new unsafe surface: the sigaction install is the same libc signal-operation family, same file, same invariants as the four blocks that already existed — the surface grows in size, not in kind. One residual remains, of a different kind: a signal landing between the final flag check and execvp is recorded but unexamined, so the launch proceeds and the manager's escalation performs the stop — supervision-semantics, not plaintext exposure (threat model updated). - deterministic test: disarm_records_signal_raised_during_the_window (raise SIGTERM at self mid-window; flag observes it; process survives) - docs: unsafe-code/signal-deferral rewritten for the new mechanism (UB table, handler-purity registry rule, fallback), threat-model residual replaced, CHANGELOG + registry index updated Verified: fmt, clippy (macOS + x86_64-linux-gnu + release, -D warnings), 83 lib + 7 exec_check + 16 conformance tests, cargo deny, cargo audit, mdbook build. --- CHANGELOG.md | 3 +- docs/src/architecture/threat-model.md | 17 ++-- docs/src/unsafe-code/index.md | 2 +- docs/src/unsafe-code/signal-deferral.md | 44 ++++++--- src/launcher.rs | 124 +++++++++++++++++++----- 5 files changed, 144 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4d472f..be3c650 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `encrypt_with_aad`/`decrypt_with_aad` on the ecies fork (upstream PR ecies/rs#159), consumed via a git+rev `[patch.crates-io]` pin. - Hardening: macOS termination-signal deferral across the plaintext-write - window; logged hardening failures; fd-pinned secret-file writes and + window, with a flag-handler handoff closing the check/exec race (no + death before exec without cleanup); logged hardening failures; fd-pinned secret-file writes and fd-relative prune/cleanup; `O_NOFOLLOW` ciphertext opens; sentinel-guarded bulk cleanup (`.postmaster-managed`); keychain reads via the Security.framework API (no `/usr/bin/security`); `--verify-keys` diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index bebf0c6..518d8dc 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -457,13 +457,16 @@ the launcher checks `sigpending` and, if a termination signal arrived during the window, removes the plaintext and dies by that signal (audit 2026-08-02 A11). -*Accepted residual:* a termination signal arriving between that final -pending check and the mask restore/exec is delivered at restore — -before `execvp` and before cleanup — stranding the just-written -plaintext. The window is microseconds and irreducible below a -fork+exec or handler+flag design (both rejected: more unsafe surface -and complexity than the window justifies); the worst case is bounded -because the ramdisk is destroyed when the launchd job stops. +*Race closed (2026-08-05):* the pending-check/exec handoff was +previously an accepted residual here. The guard now installs a +flag-recording handler while the signals are still blocked, then +restores the mask — any signal pending from the window is delivered to +the handler, never to the default disposition — so death-before-exec +always runs cleanup first. The one remaining sliver is +supervision-semantics, not plaintext exposure: a signal arriving after +the final flag check but before `execvp` is recorded but unexamined, +so the launch proceeds and the service manager's escalation (SIGKILL) +performs the stop. ### Ramdisk mount verification (macOS) — Mitigated diff --git a/docs/src/unsafe-code/index.md b/docs/src/unsafe-code/index.md index 0ca7241..40cdc97 100644 --- a/docs/src/unsafe-code/index.md +++ b/docs/src/unsafe-code/index.md @@ -21,7 +21,7 @@ Every `unsafe` block requires: | Location | Platform | Purpose | Page | |----------|----------|---------|------| -| `launcher.rs` (TerminationGuard: block/pending/die_by/Drop) | macOS | Defer termination signals across the plaintext-write window | [signal-deferral](./signal-deferral.md) | +| `launcher.rs` (TerminationGuard: block/disarm (sigaction flag handler)/die_by/Drop) | macOS | Defer termination signals across the plaintext-write window, then hand off without a check/exec race | [signal-deferral](./signal-deferral.md) | | `server.rs` (`peer_euid`) | macOS | Peer credential check via `getpeereid(2)` | [macos-libc-boundary](./macos-libc-boundary.md) | | `server.rs` (`harden_process`) | macOS, release only | `PT_DENY_ATTACH` anti-debug hardening | [macos-libc-boundary](./macos-libc-boundary.md) | | `server.rs` (socket activation) | Linux | `UnixListener::from_raw_fd` on systemd-inherited sockets | [systemd-fd-ownership](./systemd-fd-ownership.md) | diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md index 51ece83..646321b 100644 --- a/docs/src/unsafe-code/signal-deferral.md +++ b/docs/src/unsafe-code/signal-deferral.md @@ -13,11 +13,16 @@ Audit 2026-08-02 A11: on macOS, plaintext secret files persist on the ramdisk until explicitly removed, so a SIGTERM landing *during* the plaintext-write window would leave material on disk with no cleanup. `TerminationGuard` blocks SIGTERM/SIGINT/SIGHUP/SIGQUIT from just after -config validation until just before `execvp`. Before `execvp`, the -launcher synchronously checks `sigpending`; if a termination signal -arrived during the window, it runs `cleanup_written` and then dies by -that signal (`die_by`). The saved mask is always restored before exec — -a child must never inherit blocked termination signals. +config validation until just before `execvp`. At the end of the window +the guard is *disarmed*: while the signals are still blocked (so nothing +can be delivered mid-install), a flag-recording handler is installed for +the four signals, and only then is the saved mask restored. Any signal +pending from the window is delivered to that handler — never to the +default disposition — so no termination signal can kill the launcher +without `cleanup_written` running first. If the flag is set, the +launcher removes the plaintext and dies by that signal (`die_by`); +otherwise it `execvp`s. Caught-signal dispositions reset to default at +exec, so the child starts with a clean signal state. Linux needs no equivalent: tmpfs does not persist across reboots, systemd's `ExecStopPost` runs `postmaster cleanup`, and the next @@ -26,10 +31,13 @@ launch's `prune_stale` removes residuals (documented decision, A11). ## Why Unsafe Raw libc signal operations — `sigemptyset`/`sigaddset`, -`pthread_sigmask`, `sigpending`, `signal`, `raise`, `_exit` — are -invisible to Rust's type system: a wrong mask, an invalid `sigset_t`, or -a bad pointer is undefined behavior the compiler cannot reject. Darwin's -stable kernel ABI is libc, so there is no raw-syscall alternative. +`pthread_sigmask`, `sigpending`, `sigaction`, `signal`, `raise`, +`_exit` — are invisible to Rust's type system: a wrong mask, an invalid +`sigset_t`, or a bad pointer is undefined behavior the compiler cannot +reject. Darwin's stable kernel ABI is libc, so there is no raw-syscall +alternative. Note that the `sigaction` install added for the race +closure is the *same* libc signal-operation family as the pre-existing +mask operations: the unsafe surface grows in size, not in kind. ## UB Vectors and Mitigations @@ -38,9 +46,13 @@ stable kernel ABI is libc, so there is no raw-syscall alternative. | Invalid `sigset_t` | Uninitialized set passed to libc | `zeroed()` (valid empty representation) then `sigemptyset` | | Dangling pointers | set/old must outlive each call | Locals live for the full block; no pointers escape | | Thread-model mismatch | `sigprocmask` is unspecified in multithreaded processes | `pthread_sigmask` form used throughout | -| Async-signal context | Work inside a handler would be unsound | **No handlers are ever installed** — deferral is mask-only; the pending check is synchronous | +| Handler soundness | Any non-reentrant work in a handler is unsound | The handler body is a single atomic store (`PENDING_SIG`) — the canonical async-signal-safe operation. Registry rule: it must NEVER grow logging, allocation, or locking | +| `sigaction` validity | Malformed struct/mask/handler pointer is UB | Zeroed struct + `sigemptyset` mask; handler has the C signal-handler ABI; every `sigaction` rc is checked — any failure falls back to the pre-handler pending check (the documented residual then applies to that launch) | +| Install-time delivery | Signal delivered between the four `sigaction` calls | All four signals are still blocked during install, so nothing can be delivered mid-install | +| Signal floods | Many termination signals while blocked | Non-realtime signals coalesce in the kernel; the flag records one — any of them means die | | Mask leak to child | Child inheriting blocked termination signals | Mask restored before `execvp` on every path (explicit + `Drop` on early-Err) | | Lost signal | Deferred signal swallowed | `die_by` resets `SIG_DFL`, restores the saved mask, re-raises; `libc::_exit(128 + sig)` if `raise` itself fails | +| Signal after final check | TERM lands between flag check and `execvp` | Recorded by the handler but unexamined — the launch proceeds and the manager's escalation (SIGKILL) performs the stop. Supervision-semantics, not plaintext exposure (the files are the child's by design) | ## Remaining Risks @@ -57,8 +69,10 @@ section. ## Tests -Exercised by the exec integration suites (`tests/exec_check.rs`, -`tests/exec_conformance/`) for the surrounding write/exec contract. The -guard's restore-before-exec is structural (consuming `Drop`); a direct -signal-race unit test would be timing-flaky by nature and is documented -as intentionally absent. +`launcher::tests::disarm_records_signal_raised_during_the_window` +(deterministic, macOS): blocks the guard, raises SIGTERM at the process +itself, and asserts `disarm()` returns `Some(SIGTERM)` with the process +still alive — proving the whole handoff: delivery goes to the recording +handler, never to the default disposition. The surrounding write/exec +contract is exercised by the exec integration suites +(`tests/exec_check.rs`, `tests/exec_conformance/`). diff --git a/src/launcher.rs b/src/launcher.rs index ab5ba02..cf794ab 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -22,19 +22,36 @@ use crate::secret_files::{ Resolved, cleanup_written, env_pairs, open_secrets_dir, prune_stale, write_secret_file, }; use crate::server::{fetch_bytes, log, read_capped}; +#[cfg(target_os = "macos")] +use std::sync::atomic::{AtomicI32, Ordering}; /// macOS-only guard deferring termination signals across the window where /// plaintext secret files exist on the ramdisk (audit 2026-08-02 A11). /// The ramdisk persists across process death, so a signal landing /// mid-write would otherwise strand partial plaintext. Signals are -/// *blocked*, not handled — nothing runs in async-signal context; the -/// pending set is checked synchronously before execvp, and the mask is -/// always restored before exec (a child must never inherit blocked -/// termination signals). +/// *blocked* across the window; before execvp the guard is disarmed by +/// installing a flag-recording handler (while still blocked) and then +/// restoring the saved mask — anything pending from the window is +/// delivered to that handler, never to the default disposition, so no +/// termination signal can kill the launcher without cleanup running +/// first. The handler's body is a single atomic store (the canonical +/// async-signal-safe operation). /// /// Linux needs no equivalent: tmpfs does not persist across reboots, /// systemd's `ExecStopPost` runs `postmaster cleanup`, and the next /// launch's `prune_stale` removes residuals — documented decision per A11. +#[cfg(target_os = "macos")] +static PENDING_SIG: AtomicI32 = AtomicI32::new(0); + +/// Records a deferred termination signal for the launcher's +/// check-before-exec. This MUST remain a pure atomic store: no logging, +/// no allocation, no locking — anything more is unsound in async-signal +/// context. +#[cfg(target_os = "macos")] +unsafe extern "C" fn record_sig(sig: libc::c_int) { + PENDING_SIG.store(sig, Ordering::Relaxed); +} + #[cfg(target_os = "macos")] struct TerminationGuard { old: libc::sigset_t, @@ -60,7 +77,49 @@ impl TerminationGuard { } } - /// First deferred termination signal currently pending, if any. + /// Disarm the guard at the end of the write window: install + /// `record_sig` for the deferred signals while they are still blocked + /// (so nothing can be delivered mid-install), then restore the saved + /// mask. Pending termination signals are delivered to the handler and + /// recorded — never to the default disposition — and the first one + /// observed is returned. `None` means no termination signal arrived + /// across the entire window; the mask is restored either way, and + /// caught-signal dispositions reset to default at execvp, so the + /// child starts with a clean signal state. + fn disarm(&self) -> Option { + let mut ok = true; + unsafe { + // SAFETY: zeroed sigaction is a valid starting representation; + // sa_mask is made a valid empty set; the handler pointer is a + // valid function with the C signal-handler ABI. + let mut act: libc::sigaction = std::mem::zeroed(); + libc::sigemptyset(&mut act.sa_mask); + act.sa_sigaction = record_sig as *const () as usize; + for sig in Self::SIGNALS { + if libc::sigaction(sig, &act, std::ptr::null_mut()) != 0 { + ok = false; + } + } + } + if !ok { + // Defensive: sigaction(2) cannot realistically fail for these + // four signals (EINVAL covers SIGKILL/SIGSTOP/invalid, none of + // which we touch) — but if it ever does, fall back to the + // pre-handler pending check rather than silently weaken the + // guard. The residual race that disarm() exists to close then + // applies to this launch (see the threat model). + log("termination-guard: sigaction failed; falling back to pending-check"); + let sig = self.pending(); + self.restore_mask(); + return sig; + } + self.restore_mask(); + let sig = PENDING_SIG.load(Ordering::Relaxed); + (sig != 0).then_some(sig) + } + + /// First deferred termination signal pending right now, if any. + /// Fallback path for `disarm` when the handler cannot be installed. fn pending(&self) -> Option { unsafe { // SAFETY: zeroed sigset_t is valid; sigpending fills it. @@ -77,10 +136,13 @@ impl TerminationGuard { } } - /// Restore the saved signal mask. MUST be called before execvp — - /// the child must not inherit blocked termination signals. - fn restore(self) { - // Consuming self runs Drop, which does the restore. + /// Restore the saved signal mask. Always called before execvp — the + /// child must not inherit blocked termination signals. + fn restore_mask(&self) { + unsafe { + // SAFETY: restoring a previously saved valid mask. + libc::pthread_sigmask(libc::SIG_SETMASK, &self.old, std::ptr::null_mut()); + } } /// Restore the mask, reset the signal to its default disposition, and @@ -102,10 +164,7 @@ impl TerminationGuard { #[cfg(target_os = "macos")] impl Drop for TerminationGuard { fn drop(&mut self) { - unsafe { - // SAFETY: restoring a previously saved valid mask. - libc::pthread_sigmask(libc::SIG_SETMASK, &self.old, std::ptr::null_mut()); - } + self.restore_mask(); } } @@ -119,15 +178,14 @@ impl TerminationGuard { Self } - fn pending(&self) -> Option { + /// No persistence window exists on non-macOS platforms (see above): + /// always clear. + fn disarm(&self) -> Option { None } - /// No-op (nothing was blocked). - fn restore(self) {} - fn die_by(&self, _sig: i32) -> ! { - // Unreachable: pending() is always None here. + // Unreachable: disarm() is always None here. std::process::abort() } } @@ -433,15 +491,15 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() // A termination signal arrived during the write window: remove the // plaintext, then die by that signal as the sender intended (A11). - if let Some(sig) = sig_guard.pending() { + if let Some(sig) = sig_guard.disarm() { if let Some(dir_fd) = &secrets_dir_fd { cleanup_written(dir_fd, &written); } sig_guard.die_by(sig); } - // Restore the signal mask before execvp — the child must not inherit - // blocked termination signals. - sig_guard.restore(); + // disarm() already restored the pre-guard signal mask, and + // caught-signal dispositions reset to default at execvp — the child + // starts with a clean signal state. let err = std::process::Command::new(program) .args(&argv[1..]) .envs(extra) @@ -462,6 +520,28 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() mod tests { use super::*; + /// The disarm handoff must convert a signal raised during the blocked + /// window into a recorded flag instead of process death — the whole + /// point of the flag-handler design (A11 race closure). + #[cfg(target_os = "macos")] + #[test] + fn disarm_records_signal_raised_during_the_window() { + PENDING_SIG.store(0, Ordering::Relaxed); + let guard = TerminationGuard::block(); + // Sent while blocked: pends. At disarm it is delivered to the + // recording handler, not the default disposition — so this test + // process keeps running. + unsafe { + libc::raise(libc::SIGTERM); + } + assert_eq!(guard.disarm(), Some(libc::SIGTERM)); + // Leave the process as we found it. + PENDING_SIG.store(0, Ordering::Relaxed); + unsafe { + libc::signal(libc::SIGTERM, libc::SIG_DFL); + } + } + #[test] fn validate_credential_keys_accepts_identifiers() { assert!(validate_credential_keys(&["DB_URL".to_string()]).is_ok()); From 2841cfa624325bdfaff4faffd5d68a5b02bfd179 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Thu, 6 Aug 2026 00:28:06 -0500 Subject: [PATCH 13/47] fix(launcher): second termination-flag gate immediately before execvp Narrows the unexamined-consumption sliver from the disarm->Command-build window (~5-50us) to the execve path itself (~1-10us): the flag is now read at disarm and again immediately before exec, and a recorded signal triggers cleanup_written + die_by instead of being carried silently into the child (A11 follow-up). Verified: fmt, clippy (macOS + x86_64-linux-gnu + release, -D warnings), 83 lib + 7 exec_check + 16 conformance tests, mdbook build. --- CHANGELOG.md | 5 +++-- docs/src/architecture/threat-model.md | 11 +++++----- docs/src/unsafe-code/signal-deferral.md | 2 +- src/launcher.rs | 29 +++++++++++++++++++++---- 4 files changed, 35 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be3c650..2d34040 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,8 +18,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `encrypt_with_aad`/`decrypt_with_aad` on the ecies fork (upstream PR ecies/rs#159), consumed via a git+rev `[patch.crates-io]` pin. - Hardening: macOS termination-signal deferral across the plaintext-write - window, with a flag-handler handoff closing the check/exec race (no - death before exec without cleanup); logged hardening failures; fd-pinned secret-file writes and + window, with a flag-handler handoff plus a final pre-exec gate closing + the check/exec race (no death before exec without cleanup); logged + hardening failures; fd-pinned secret-file writes and fd-relative prune/cleanup; `O_NOFOLLOW` ciphertext opens; sentinel-guarded bulk cleanup (`.postmaster-managed`); keychain reads via the Security.framework API (no `/usr/bin/security`); `--verify-keys` diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index 518d8dc..5d39340 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -462,11 +462,12 @@ previously an accepted residual here. The guard now installs a flag-recording handler while the signals are still blocked, then restores the mask — any signal pending from the window is delivered to the handler, never to the default disposition — so death-before-exec -always runs cleanup first. The one remaining sliver is -supervision-semantics, not plaintext exposure: a signal arriving after -the final flag check but before `execvp` is recorded but unexamined, -so the launch proceeds and the service manager's escalation (SIGKILL) -performs the stop. +always runs cleanup first. The flag is read twice (at disarm and again +immediately before `execvp`), narrowing the unexamined-consumption +sliver to the execve path itself (~microseconds): a signal landing +only there is recorded but unexamined, so the launch proceeds and the +service manager's escalation (SIGKILL) performs the stop — +supervision-semantics, not plaintext exposure. ### Ramdisk mount verification (macOS) — Mitigated diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md index 646321b..4dba505 100644 --- a/docs/src/unsafe-code/signal-deferral.md +++ b/docs/src/unsafe-code/signal-deferral.md @@ -52,7 +52,7 @@ mask operations: the unsafe surface grows in size, not in kind. | Signal floods | Many termination signals while blocked | Non-realtime signals coalesce in the kernel; the flag records one — any of them means die | | Mask leak to child | Child inheriting blocked termination signals | Mask restored before `execvp` on every path (explicit + `Drop` on early-Err) | | Lost signal | Deferred signal swallowed | `die_by` resets `SIG_DFL`, restores the saved mask, re-raises; `libc::_exit(128 + sig)` if `raise` itself fails | -| Signal after final check | TERM lands between flag check and `execvp` | Recorded by the handler but unexamined — the launch proceeds and the manager's escalation (SIGKILL) performs the stop. Supervision-semantics, not plaintext exposure (the files are the child's by design) | +| Signal after final check | TERM lands between flag check and `execvp` | The flag is read a second time immediately before `execvp`; only a signal inside the execve path itself (~microseconds) can slip through — recorded but unexamined, the manager's escalation (SIGKILL) performs the stop. Supervision-semantics, not plaintext exposure (the files are the child's by design) | ## Remaining Risks diff --git a/src/launcher.rs b/src/launcher.rs index cf794ab..059610c 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -136,6 +136,15 @@ impl TerminationGuard { } } + /// A termination signal recorded by `record_sig` since `disarm`, if + /// any. Read once more immediately before `execvp` so a signal + /// consumed in the disarm→exec gap is not carried silently into the + /// child (A11). + fn recorded(&self) -> Option { + let sig = PENDING_SIG.load(Ordering::Relaxed); + (sig != 0).then_some(sig) + } + /// Restore the saved signal mask. Always called before execvp — the /// child must not inherit blocked termination signals. fn restore_mask(&self) { @@ -184,6 +193,11 @@ impl TerminationGuard { None } + /// Always clear (see above). + fn recorded(&self) -> Option { + None + } + fn die_by(&self, _sig: i32) -> ! { // Unreachable: disarm() is always None here. std::process::abort() @@ -500,10 +514,17 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() // disarm() already restored the pre-guard signal mask, and // caught-signal dispositions reset to default at execvp — the child // starts with a clean signal state. - let err = std::process::Command::new(program) - .args(&argv[1..]) - .envs(extra) - .exec(); // only returns on failure + let mut cmd = std::process::Command::new(program); + cmd.args(&argv[1..]).envs(extra); + // Final gate: a termination signal recorded since disarm() must not + // be carried silently into the child — clean up and die by it (A11). + if let Some(sig) = sig_guard.recorded() { + if let Some(dir_fd) = &secrets_dir_fd { + cleanup_written(dir_fd, &written); + } + sig_guard.die_by(sig); + } + let err = cmd.exec(); // only returns on failure // execvp failed: the process image was NOT replaced, so any // plaintext secret files written above would otherwise persist // (the macOS ramdisk survives process death). Remove them before From 613935ea8e155e4fd36d328f2e0caa91a073f075 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Thu, 6 Aug 2026 09:54:36 -0500 Subject: [PATCH 14/47] =?UTF-8?q?feat(launcher):=20sibling=20launch=20moni?= =?UTF-8?q?tor=20=E2=80=94=20per-service=20supervision=20and=20cleanup=20o?= =?UTF-8?q?n=20every=20death=20path?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per the sibling-monitor design (author-approved 2026-08-05; rulings: 250 ms grace constant, retire the flag-handler, pidfd+kqueue liveness, monitor on all exec launches). - The launcher forks after zeroization, before execvp: the parent execs the service (MainPID unchanged), the fork-child becomes the monitor. - The monitor keeps the four termination signals blocked for life and consumes them synchronously (sigpending/sigwait) — no signal handlers anywhere; the sigaction flag-handler and second pre-exec gate are retired. - Stop policy: forward -> 250 ms grace -> SIGKILL -> cleanup -> exit. Service death from ANY cause (natural exit, kill -9, crash) -> cleanup -> exit — including interactive kill -9, which previously had no cleanup path outside systemd ExecStopPost. - Liveness: pidfd+poll on Linux (pidfd_send_signal for forwarding — PID-reuse-proof), kqueue NOTE_EXIT on macOS; kill(pid,0) polling is fallback-only. - The monitor scrubs the inherited env-pair heap at start (into_vec + zeroize in place): free() alone would leave plaintext in mapped pages for the monitor's whole life. - fork failure fails closed — no unsupervised launch. - The Linux TerminationGuard leg is now real (rustix runtime rt_sigprocmask); rustix runtime/event features adopted (experimental API, lockfile-pinned, fails loudly on change); libc::fork is the single libc FFI call on the Linux exec path (doctrine exception, documented in the registry, monitor.md, postmaster.md, CHANGELOG). Tests: four new monitor tests run the real loop in real forked processes (natural death, forwarded TERM, TERM-ignoring service SIGKILLed after grace, env-mode no-op) plus the wipe_pair scrub test; two conformance tests updated to the new contract (plaintext removed on service death; 0600 verified in-service). 87 lib + 7 exec_check + 16 conformance, zero regressions. Docs: new unsafe-code/monitor.md; signal-deferral rewritten for the reduced guard; registry, threat model (monitor model + inherited-heap mitigation), postmaster.md Stage 5 + dependency policy, CHANGELOG, SUMMARY. Verified: fmt, clippy (macOS + x86_64-linux-gnu + release, -D warnings), full test suite, cargo deny, cargo audit, mdbook build. --- CHANGELOG.md | 30 +- Cargo.toml | 26 +- docs/src/SUMMARY.md | 3 +- docs/src/architecture/postmaster.md | 27 +- docs/src/architecture/threat-model.md | 74 +- docs/src/unsafe-code/index.md | 9 +- docs/src/unsafe-code/macos-libc-boundary.md | 11 +- docs/src/unsafe-code/monitor.md | 103 +++ docs/src/unsafe-code/signal-deferral.md | 100 +-- src/launcher.rs | 316 ++++---- src/lib.rs | 1 + src/monitor.rs | 758 ++++++++++++++++++++ tests/exec_conformance/files_mode.rs | 27 +- 13 files changed, 1192 insertions(+), 293 deletions(-) create mode 100644 docs/src/unsafe-code/monitor.md create mode 100644 src/monitor.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d34040..00c8344 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,18 +17,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 pre-AAD bundles are rejected. AAD support comes from the additive `encrypt_with_aad`/`decrypt_with_aad` on the ecies fork (upstream PR ecies/rs#159), consumed via a git+rev `[patch.crates-io]` pin. -- Hardening: macOS termination-signal deferral across the plaintext-write - window, with a flag-handler handoff plus a final pre-exec gate closing - the check/exec race (no death before exec without cleanup); logged - hardening failures; fd-pinned secret-file writes and - fd-relative prune/cleanup; `O_NOFOLLOW` ciphertext opens; - sentinel-guarded bulk cleanup (`.postmaster-managed`); keychain reads - via the Security.framework API (no `/usr/bin/security`); `--verify-keys` - fails on ANY undecryptable value, including under `strict:false`; - daemon config rejects unknown fields (root and nested); Linux `id` - resolved from verified absolute paths only; setup verification reuses - the runtime key-variable predicate; bundle `encoding: "utf8"` is - validated at resolution. +- Hardening: a sibling launch monitor now owns stop semantics on the + exec path — the launcher forks after zeroization, the parent execs the + service (MainPID unchanged), and the fork-child supervises it: + synchronous stop-signal forwarding with a fixed 250 ms grace before + SIGKILL escalation, pidfd/kqueue liveness, and plaintext-file cleanup + on EVERY service-death path (natural exit, `kill -9`, crash) — the + macOS termination-signal deferral across the plaintext-write window + remains, while the sigaction flag-handler and second pre-exec gate are + retired (the monitor subsumes the race; fork(2) on Linux is the one + libc FFI call there, review-gated); logged hardening failures; + fd-pinned secret-file writes and fd-relative prune/cleanup; + `O_NOFOLLOW` ciphertext opens; sentinel-guarded bulk cleanup + (`.postmaster-managed`); keychain reads via the Security.framework API + (no `/usr/bin/security`); `--verify-keys` fails on ANY undecryptable + value, including under `strict:false`; daemon config rejects unknown + fields (root and nested); Linux `id` resolved from verified absolute + paths only; setup verification reuses the runtime key-variable + predicate; bundle `encoding: "utf8"` is validated at resolution. ### Changed diff --git a/Cargo.toml b/Cargo.toml index bed5a14..7e624c0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,10 @@ repository = "https://github.com/beardedeagle/postmaster" # `unsafe_code` (some stricter projects deny it outright). postmaster is a # syscall-boundary daemon and needs a handful of justified `unsafe` blocks: # getpeereid(2) and PT_DENY_ATTACH on macOS (Darwin's stable kernel ABI is -# libc), signal-mask deferral around the plaintext-write window (macOS), +# libc), signal-mask deferral around the plaintext-write window and the +# sibling launch monitor (fork + pidfd/kqueue liveness — see +# docs/src/unsafe-code/monitor.md; on Linux the monitor's signal ops use +# rustix's linux_raw `runtime` API, fork(2) is the single libc FFI call), # UnixListener::from_raw_fd on the inherited systemd sockets (Linux), and # test-only set_var/remove_var (unsafe on edition 2024). Each site carries # a SAFETY comment and is documented in docs/src/unsafe-code/ (the mdbook @@ -115,10 +118,27 @@ rustix = { version = "1", features = ["net", "process", "mm", "fs"] } [patch.crates-io] ecies = { git = "https://github.com/beardedeagle/rs.git", rev = "81e1b84" } +[target.'cfg(target_os = "linux")'.dependencies] +# Linux-only additions for the sibling launch monitor +# (docs/src/unsafe-code/monitor.md): +# - rustix "runtime": the monitor's signal ops (mask for life, synchronous +# consumption) use kernel_sigprocmask/kernel_sigpending/kernel_sigwait — +# rustix's experimental, doc-hidden runtime API — so the Linux leg stays +# on linux_raw with NO libc signal FFI. Cargo.lock pins the exact rustix; +# an update that changes this unstable API fails the build loudly, +# never silently. +# - rustix "event": poll(2) on the service pidfd for liveness. +# - libc: fork(2) ONLY. rustix deliberately has no fork wrapper; this is +# the single libc FFI call on the Linux exec path (house-doctrine +# exception, review-gated — flagged in the unsafe-code registry). +rustix = { version = "1", features = ["runtime", "event"] } +libc = "0.2" + [target.'cfg(target_os = "macos")'.dependencies] # Darwin's stable kernel ABI *is* libc (raw syscalls are unsupported there; -# rustix itself calls through libc on darwin). Two narrow calls use it -# directly: getpeereid for the peer check and PT_DENY_ATTACH hardening. +# rustix itself calls through libc on darwin). Narrow direct uses: getpeereid +# for the peer check, PT_DENY_ATTACH hardening, and the sibling monitor's +# kqueue/signal-mask ops (docs/src/unsafe-code/monitor.md). libc = "0.2" security-framework = "3.7.0" diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 68df15e..f0c9368 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -17,7 +17,8 @@ # Unsafe Code - [Overview](./unsafe-code/index.md) -- [Signal deferral (macOS)](./unsafe-code/signal-deferral.md) +- [Signal deferral](./unsafe-code/signal-deferral.md) +- [Sibling launch monitor](./unsafe-code/monitor.md) - [macOS libc boundary](./unsafe-code/macos-libc-boundary.md) - [systemd fd ownership (Linux)](./unsafe-code/systemd-fd-ownership.md) - [Test-only env mutation](./unsafe-code/test-env-mutation.md) diff --git a/docs/src/architecture/postmaster.md b/docs/src/architecture/postmaster.md index a2c3045..53afc28 100644 --- a/docs/src/architecture/postmaster.md +++ b/docs/src/architecture/postmaster.md @@ -200,13 +200,22 @@ context. This is the only stage postmaster owns. ### Stage 5: Launch (execvp) -Postmaster calls `execvp`. The process image is replaced. The child -binary IS `MainPID`. Postmaster is gone. +Postmaster forks a **sibling monitor** and then calls `execvp` in the +parent. The parent's process image is replaced. The child binary IS +`MainPID`. Postmaster is gone from the service's process. + +The fork-child is the monitor: secretless by construction (forked after +zeroization), it keeps the termination signals blocked for life and +supervises its parent — forwards stop signals with a 250 ms grace +before SIGKILL escalation, and removes the plaintext secret files on +every service-death path (natural exit, `kill -9`, crash), then exits. +One tiny extra process per service for the service's lifetime; liveness +is pidfd+`poll` on Linux and kqueue `NOTE_EXIT` on macOS. The service manager (systemd/launchd) supervises the child from this point. `ExecStopPost` runs `postmaster cleanup` to remove plaintext -files after the child exits (Linux). The ramdisk is destroyed when -the launchd job stops (macOS). +files after the child exits (Linux) — now a backstop behind the +monitor. The ramdisk is destroyed when the launchd job stops (macOS). ## Implementation @@ -243,15 +252,19 @@ and per-mode injection rules are the cross-binding contract at ## Dependency policy -Postmaster has 10 direct dependencies (8 portable, 2 macOS-only): +Postmaster has 10 direct dependencies (8 portable, 2 platform-gated): - `ecies` — crypto (secp256k1 + AES-256-GCM) - `dotenvy` — `.env` file parser - `serde` + `serde_json` — JSON config deserialization - `base64` — ciphertext decoding - `hex` — key parsing -- `rustix` — syscalls (no libc FFI on Linux) -- `libc` — macOS only (for `getpeereid` and `PT_DENY_ATTACH`) +- `rustix` — syscalls (raw syscalls via `linux_raw` on Linux, incl. the + monitor's pidfd/poll and the experimental `runtime` signal-mask API; + the only libc FFI on Linux is `fork(2)` — see the unsafe registry) +- `libc` — macOS (getpeereid, `PT_DENY_ATTACH`, the monitor's + kqueue/signal ops) plus Linux `fork(2)` only (rustix has no fork + wrapper — review-gated doctrine exception) - `security-framework` — macOS only (Security.framework keychain reads) - `zeroize` — secret memory wiping diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index 5d39340..c0e3e12 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -386,6 +386,22 @@ to be intact at the moment of `execvp`, and `execvp` replaces the process image without running destructors. Fork+wait would keep secrets in a long-lived parent heap (strictly worse) and was rejected. +### Monitor inherited heap — Mitigated + +The sibling monitor is forked after zeroization, so the key ring and +the `Zeroizing` resolved values are already wiped in the copy it +inherits. One plaintext-bearing structure does cross the fork: the +`extra` env array (plaintext values in env mode and in files-mode +passthrough). The monitor scrubs its copy **first**, before the +supervision loop starts: each `OsString` is consumed into its existing +buffer (no copy) and wiped in place with `zeroize` — free() alone +would leave the bytes in the monitor's mapped pages for its whole life, +and the monitor never allocates again, so they would never even be +reused. The parent's copy dies with `execvp` (image replacement). What +the monitor keeps beyond the scrub is non-secret metadata only: the +pinned secrets-dir fd and entry names (already visible in the +directory listing). + ### File-backed memory (page cache) — Mitigated by design Postmaster does not `mmap` secret files. Secret files on Linux tmpfs @@ -444,30 +460,40 @@ privileged memory inspection within the same kernel. ### Plaintext file persistence window (files mode) — Mitigated -Secret files written to the tmpfs/ramdisk are removed by `postmaster -cleanup --config `, wired to `ExecStopPost` in the systemd -Nix module — it runs immediately after the child exits. On macOS, the -ramdisk is destroyed when the `postmaster-ramdisk` launchd job stops. -The `prune_stale` function also removes stale files from prior -launches before writing new ones. - -On macOS, a `TerminationGuard` additionally blocks -SIGTERM/SIGINT/SIGHUP/SIGQUIT across the write window; before `execvp` -the launcher checks `sigpending` and, if a termination signal arrived -during the window, removes the plaintext and dies by that signal -(audit 2026-08-02 A11). - -*Race closed (2026-08-05):* the pending-check/exec handoff was -previously an accepted residual here. The guard now installs a -flag-recording handler while the signals are still blocked, then -restores the mask — any signal pending from the window is delivered to -the handler, never to the default disposition — so death-before-exec -always runs cleanup first. The flag is read twice (at disarm and again -immediately before `execvp`), narrowing the unexamined-consumption -sliver to the execve path itself (~microseconds): a signal landing -only there is recorded but unexamined, so the launch proceeds and the -service manager's escalation (SIGKILL) performs the stop — -supervision-semantics, not plaintext exposure. +Secret files written to the tmpfs/ramdisk are removed by the **sibling +launch monitor** (design 2026-08-05), by `postmaster cleanup --config +` wired to `ExecStopPost` in the systemd Nix module, and by +ramdisk destruction when the `postmaster-ramdisk` launchd job stops. The +`prune_stale` function also removes stale files from prior launches +before writing new ones. + +A `TerminationGuard` blocks SIGTERM/SIGINT/SIGHUP/SIGQUIT across the +write window on both platforms, so a signal landing mid-write cannot +strand partial plaintext (audit 2026-08-02 A11). At the end of the +window — after zeroization, before `execvp` — the launcher forks. The +parent restores its pre-guard mask and execs the service (MainPID +unchanged); the fork-child is the **sibling monitor**: it keeps the +four termination signals blocked for life and owns stop semantics. + +*Monitor model (2026-08-05):* the monitor consumes stop signals +synchronously (no handlers anywhere — the sigaction flag-handler and +second pre-exec gate were retired with this design), forwards them to +the service, and escalates to SIGKILL after a **250 ms grace** — a +single global constant, deliberately not configurable (per-service +erosion of a security policy is unacceptable; the per-unit knob is the +manager's own stop timeout). Cleanup runs on **every** death path: +forwarded stops, natural exit, `kill -9`, crashes. Liveness uses a +pidfd + `poll` on Linux and kqueue `NOTE_EXIT` on macOS — both fire at +exit (zombie- and PID-reuse-proof); `kill(pid, 0)` polling is fallback +only. On systemd the monitor receives its own copy of cgroup-wide stop +signals, so it never depends on a signal the launcher already consumed. +On launchd, signals go to the job's main process only, so the monitor +is primarily a cleanup-watcher there — the macOS stop-path exposure +(plus the bounded PID-reuse window of its `kill(2)` forwarding, Darwin +having no pidfd) remains bounded by the ramdisk teardown at job stop, +the strongest backstop in the system. A monitor that dies before the +service leaves the pre-existing backstops (`ExecStopPost`, teardown, +`prune_stale`) — the same floor as before the monitor existed. ### Ramdisk mount verification (macOS) — Mitigated diff --git a/docs/src/unsafe-code/index.md b/docs/src/unsafe-code/index.md index 40cdc97..ebdc23b 100644 --- a/docs/src/unsafe-code/index.md +++ b/docs/src/unsafe-code/index.md @@ -2,8 +2,9 @@ Postmaster deliberately allows `unsafe` at the lint level (documented in `[lints.rust]` in `Cargo.toml`) because it is a syscall-boundary daemon: -peer-credential checks, anti-debug hardening, signal-mask deferral, and -the systemd socket-activation contract cannot be expressed in safe Rust. +peer-credential checks, anti-debug hardening, signal-mask deferral, the +sibling launch monitor (fork + pidfd/kqueue liveness), and the systemd +socket-activation contract cannot be expressed in safe Rust. This section documents every approved site. ## Policy @@ -21,7 +22,9 @@ Every `unsafe` block requires: | Location | Platform | Purpose | Page | |----------|----------|---------|------| -| `launcher.rs` (TerminationGuard: block/disarm (sigaction flag handler)/die_by/Drop) | macOS | Defer termination signals across the plaintext-write window, then hand off without a check/exec race | [signal-deferral](./signal-deferral.md) | +| `launcher.rs` (TerminationGuard: block/restore_mask/Drop) | macOS, Linux | Defer termination signals across the plaintext-write window; the fork-child monitor inherits the mask for life | [signal-deferral](./signal-deferral.md) | +| `launcher.rs` (fork(2)) | macOS, Linux | Fork the sibling monitor before exec — the single libc FFI call on Linux (doctrine exception) | [monitor](./monitor.md) | +| `monitor.rs` (signal mask/wait ops, pidfd+poll / kqueue, `_exit`/`exit_group`, raw stderr write) | macOS, Linux | Sibling monitor: synchronous stop consumption, liveness watch, cleanup on every death path | [monitor](./monitor.md) | | `server.rs` (`peer_euid`) | macOS | Peer credential check via `getpeereid(2)` | [macos-libc-boundary](./macos-libc-boundary.md) | | `server.rs` (`harden_process`) | macOS, release only | `PT_DENY_ATTACH` anti-debug hardening | [macos-libc-boundary](./macos-libc-boundary.md) | | `server.rs` (socket activation) | Linux | `UnixListener::from_raw_fd` on systemd-inherited sockets | [systemd-fd-ownership](./systemd-fd-ownership.md) | diff --git a/docs/src/unsafe-code/macos-libc-boundary.md b/docs/src/unsafe-code/macos-libc-boundary.md index e6ad38b..34c046a 100644 --- a/docs/src/unsafe-code/macos-libc-boundary.md +++ b/docs/src/unsafe-code/macos-libc-boundary.md @@ -1,9 +1,12 @@ # macOS libc Boundary -Two unrelated `unsafe` sites share one justification: on Darwin the -stable kernel ABI *is* libc, so these calls have no raw-syscall route -(contrast with Linux, where rustix's `linux_raw` backend avoids libc FFI -entirely). +On Darwin the stable kernel ABI *is* libc, so these calls have no +raw-syscall route (contrast with Linux, where rustix's `linux_raw` +backend avoids libc FFI except `fork(2)`). This page covers the daemon's +two sites; the launcher's signal-mask guard and the sibling monitor's +kqueue/signal ops share the same justification and live on their own +pages ([signal deferral](./signal-deferral.md), +[sibling launch monitor](./monitor.md)). ## getpeereid — peer credential check diff --git a/docs/src/unsafe-code/monitor.md b/docs/src/unsafe-code/monitor.md new file mode 100644 index 0000000..d4ba6a3 --- /dev/null +++ b/docs/src/unsafe-code/monitor.md @@ -0,0 +1,103 @@ +# Sibling Launch Monitor + +## Location + +``` +src/monitor.rs — the monitor loop, liveness watches, signal ops, exit +src/launcher.rs — the fork(2) site and the Linux TerminationGuard leg +Unsafe blocks: fork(2) (libc, both platforms); rustix `runtime` + kernel_sigprocmask/kernel_sigwait (Linux); libc pthread_sigmask/ + sigpending/sigwait/kqueue/kevent/_exit (macOS); + OwnedFd::from_raw_fd (macOS kqueue fd); BorrowedFd::borrow_raw (stderr) +``` + +## Purpose + +The sibling-monitor launch supervision design (2026-08-05) closes the +launch-handoff stop-semantics gap and adds plaintext cleanup on **every** +service-death path. After validation, plaintext writes, and zeroization — +and before `execvp` — the launcher `fork()`s. The parent restores its +pre-guard signal mask and execs the service (MainPID unchanged); the +fork-child becomes the monitor: it keeps the four termination signals +blocked for life, consumes them synchronously (sigpending/sigwait — no +handlers anywhere), forwards stops to the service, escalates to SIGKILL +after a 250 ms grace (a single global security policy, deliberately not +configurable), watches liveness (pidfd+poll on Linux, kqueue +`EVFILT_PROC`/`NOTE_EXIT` on macOS, `kill(pid, 0)` only as fallback), and +runs `cleanup_written` before exiting — on stop, on natural exit, on +`kill -9`, on crash. The sigaction flag-handler and second pre-exec gate +were retired with this design: the monitor is the single owner of stop +semantics, so no async-signal context exists anywhere. + +## Why Unsafe + +- **`fork(2)` has no rustix wrapper** (a deliberate rustix omission), so + it is a direct libc call on both platforms. On Linux this is the + **single libc FFI call on the exec path** — an explicit, review-gated + exception to the "rustix linux_raw / no libc FFI on Linux" doctrine. + Everything else on the Linux leg is rustix. +- **Linux signal masking and synchronous consumption** use rustix's + `runtime` module (`kernel_sigprocmask`, `kernel_sigwait`, + `kernel_sigpending`, `exit_group`) — rustix's experimental, doc-hidden + API for libc-like runtimes. It is the only rustix route to signal masks + (there is no `rustix::process::sigprocmask`), and taking it avoids libc + signal FFI on Linux. Cargo.lock pins the exact rustix; an update that + changes this unstable API fails the build loudly, never silently. The + documented hazard class (a libc in the process reserves some signals) + does not apply: the mask set holds only TERM/INT/HUP/QUIT/PIPE, none of + which any libc reserves (glibc reserves 32/33). +- **Darwin has no raw-syscall ABI** and no `sigtimedwait` at all, so the + macOS leg uses libc for `pthread_sigmask`, `sigpending`, `sigwait`, + `kqueue`/`kevent`, and `_exit` — the same libc-signal family already on + this boundary, plus kqueue. rustix's `runtime` module does not exist + off Linux (it is `linux_raw_sys`-typed), and rustix's stable API has no + signal-mask or sigwait wrappers on any platform. +- `OwnedFd::from_raw_fd` (kqueue fd) and `BorrowedFd::borrow_raw(2)` + (monitor diagnostics) are fd-ownership assertions of the same kind as + the systemd socket boundary. + +Liveness findings that shaped the code: rustix 1.x **does** cover +`pidfd_open`/`pidfd_send_signal` (Linux-only) and `poll`, so the pidfd +leg needs no fallback in practice; `kill(pid, 0)` polling is kept only +for kernels without `pidfd_open` (< 5.3) and for kqueue failure. An +`ESRCH` from `pidfd_open`, from `kevent` registration, or from +`kill(pid, 0)` is race-free "definitely gone" and short-circuits to +cleanup (on macOS, xnu drops exited procs from the pid table before they +are reaped, so NOTE_EXIT registration on an already-exited service fails +`ESRCH` — handled as death, not as a fallback trigger). + +## UB Vectors and Mitigations + +| Vector | Description | Mitigation | +|--------|-------------|------------| +| Fork in a threaded process | The child inherits locked malloc/stdio state | The exec path is single-threaded at fork (worker threads exist only in serve mode). The child performs no allocation, no stdio locks, no destructor runs — only the async-signal-safe syscall set documented at the top of `monitor.rs` — and exits via `_exit`/`exit_group` (no atexit, no stdio flush). Tests fork from the multithreaded harness under the same discipline | +| Invalid `sigset_t` | Uninitialized set passed to sigwait/sigpending | `KernelSigSet::empty()` (rustix) / `zeroed()` + `sigemptyset` (libc) | +| Blocking sigwait hang | `sigwait` blocks until a set member is pending | Called only after `sigpending` shows a member pending — single-threaded, so nothing else can dequeue it first | +| Mask clobber | Restoring a mask never captured | Linux guard stores `None` on block failure (logged); restore then no-ops | +| Mask leak to the service | Service inheriting blocked termination signals | The parent restores the saved mask before `execvp` (explicit call + `Drop` on early-Err paths); the fork-child's guard is never dropped (`monitor::run` diverges, `_exit` runs no destructors), so the monitor keeps the mask for life | +| Wrong-fd ownership | Closing an fd not owned | `from_raw_fd` wraps a fresh `kqueue()` result exactly once; `borrow_raw(2)` never closes and never outlives the call (an absent stderr just fails the write with EBADF) | +| PID reuse | Signals/liveness hitting a recycled PID | pidfd pins the process: `poll` fires at exit (zombie-proof) and `pidfd_send_signal` cannot hit a recycled PID. `ESRCH` anywhere is treated as race-free death. Residual: the macOS stop-forward path uses plain `kill(2)` (Darwin has no pidfd) — a bounded exposure, accepted in the threat model | +| Zombie blindness | `kill(pid, 0)` succeeds on zombies | pidfd/kqueue are the primary mechanisms precisely because they fire at exit, not at reap; polling is fallback-only and documented | +| Handler unsoundness | Non-reentrant work in signal context | Eliminated by design — there are no signal handlers; consumption is synchronous in the loop | + +## Remaining Risks + +| Risk | Likelihood | Impact | +|------|------------|--------| +| rustix `runtime` API changes in a future rustix | Low (lockfile-pinned; build fails loudly at update time) | Build breakage, not a runtime defect | +| Monitor dies before the service | Very low (tiny, secretless loop) | Cleanup falls to the pre-existing backstops: `ExecStopPost`, ramdisk teardown, next-launch `prune_stale` — the same floor as before the monitor | +| Job-control stop (SIGTSTP) of the monitor's process group | Interactive sessions only | The monitor suspends with the service; cleanup waits for continuation — backstops remain | +| Service unkillable in D-state after SIGKILL | Kernel pathology | The monitor's post-SIGKILL death wait is unbounded by design (abandoning cleanup is worse); the manager's own escalation path still applies | +| Polling fallback on a pre-5.3 kernel | Legacy kernels only | Zombie-blindness until the parent reaps (systemd reaps promptly); PID-reuse exposure as documented | + +## Tests + +`monitor::tests` fork the REAL monitor loop in a real fork-child against +real service processes (deterministic; grace/poll injectable; no env +mutation): natural `kill -9` death → cleanup + exit; TERM to the monitor +→ forwarded (service dies by TERM, proving no escalation) → cleanup + +exit; a TERM-ignoring forked service (`SIG_IGN` + `pause`) → SIGKILL only +after the grace → cleanup + exit; env-mode (no fd, empty names) → exit on +service death. The exec integration suites +(`tests/exec_check.rs`, `tests/exec_conformance/`) exercise the full +fork+exec path and assert the post-exit cleanup contract. diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md index 4dba505..fad81eb 100644 --- a/docs/src/unsafe-code/signal-deferral.md +++ b/docs/src/unsafe-code/signal-deferral.md @@ -1,10 +1,10 @@ -# Signal Deferral (macOS) +# Signal Deferral (TerminationGuard) ## Location ``` -src/launcher.rs — struct TerminationGuard (macOS cfg only) -Blocks: block() (sigmask), pending() (sigpending), die_by() (re-raise), Drop (restore) +src/launcher.rs — struct TerminationGuard (macOS and Linux legs) +Blocks: block() (sigmask), restore_mask() (sigmask), Drop (restore) ``` ## Purpose @@ -12,67 +12,71 @@ Blocks: block() (sigmask), pending() (sigpending), die_by() (re-raise), Drop (re Audit 2026-08-02 A11: on macOS, plaintext secret files persist on the ramdisk until explicitly removed, so a SIGTERM landing *during* the plaintext-write window would leave material on disk with no cleanup. -`TerminationGuard` blocks SIGTERM/SIGINT/SIGHUP/SIGQUIT from just after -config validation until just before `execvp`. At the end of the window -the guard is *disarmed*: while the signals are still blocked (so nothing -can be delivered mid-install), a flag-recording handler is installed for -the four signals, and only then is the saved mask restored. Any signal -pending from the window is delivered to that handler — never to the -default disposition — so no termination signal can kill the launcher -without `cleanup_written` running first. If the flag is set, the -launcher removes the plaintext and dies by that signal (`die_by`); -otherwise it `execvp`s. Caught-signal dispositions reset to default at -exec, so the child starts with a clean signal state. - -Linux needs no equivalent: tmpfs does not persist across reboots, -systemd's `ExecStopPost` runs `postmaster cleanup`, and the next -launch's `prune_stale` removes residuals (documented decision, A11). +`TerminationGuard` blocks SIGTERM/SIGINT/SIGHUP/SIGQUIT +(`monitor::STOP_SIGNALS`) from just after config validation until the +fork/exec at the end of the window — a deterministic write window: no +termination signal can kill the launcher mid-write. + +At the end of the window the launcher forks the sibling monitor (see +[Sibling Launch Monitor](./monitor.md)), which **inherits the blocked +mask and keeps it for life** — the fork-child's guard is never dropped +(the monitor entry point diverges and exits via `_exit`/`exit_group`, +running no destructors). The parent calls `restore_mask()` before +`execvp` so the service starts with a clean signal state. + +The guard previously also carried a sigaction flag-recording handler +(`disarm`/`recorded`) and a second pre-exec gate to close the +check/exec race. Both were **retired with the sibling-monitor design +(2026-08-05)**: the monitor owns stop semantics on every death path, so +no async handler is needed anywhere and the handler's forever-purity +constraint is gone with it. What remains — `block()` and +`restore_mask()` — is what this page covers. + +The guard became real on Linux with the same change: the fork+monitor +model runs there too, and the blocked mask is the monitor's inheritance. +The Linux leg uses rustix's raw `rt_sigprocmask` (`runtime` module — the +experimental API; see the monitor page for the doctrinal discussion), so +the Linux exec path adds no libc signal FFI. ## Why Unsafe -Raw libc signal operations — `sigemptyset`/`sigaddset`, -`pthread_sigmask`, `sigpending`, `sigaction`, `signal`, `raise`, -`_exit` — are invisible to Rust's type system: a wrong mask, an invalid -`sigset_t`, or a bad pointer is undefined behavior the compiler cannot -reject. Darwin's stable kernel ABI is libc, so there is no raw-syscall -alternative. Note that the `sigaction` install added for the race -closure is the *same* libc signal-operation family as the pre-existing -mask operations: the unsafe surface grows in size, not in kind. +Raw signal-mask operations — `pthread_sigmask` on Darwin (whose stable +kernel ABI is libc), `rt_sigprocmask` via rustix's `runtime` module on +Linux — are invisible to Rust's type system: a wrong mask or an invalid +`sigset_t` is undefined behavior the compiler cannot reject. The +pre-fork guard shares its platform notes with the monitor page: the +rustix `runtime` API is experimental (lockfile-pinned), and the mask set +holds only standard signals no libc reserves. ## UB Vectors and Mitigations | Vector | Description | Mitigation | |--------|-------------|------------| -| Invalid `sigset_t` | Uninitialized set passed to libc | `zeroed()` (valid empty representation) then `sigemptyset` | +| Invalid `sigset_t` | Uninitialized set passed to the mask call | `zeroed()` (valid empty representation) then `sigemptyset` on Darwin; `KernelSigSet::empty()` on Linux | | Dangling pointers | set/old must outlive each call | Locals live for the full block; no pointers escape | -| Thread-model mismatch | `sigprocmask` is unspecified in multithreaded processes | `pthread_sigmask` form used throughout | -| Handler soundness | Any non-reentrant work in a handler is unsound | The handler body is a single atomic store (`PENDING_SIG`) — the canonical async-signal-safe operation. Registry rule: it must NEVER grow logging, allocation, or locking | -| `sigaction` validity | Malformed struct/mask/handler pointer is UB | Zeroed struct + `sigemptyset` mask; handler has the C signal-handler ABI; every `sigaction` rc is checked — any failure falls back to the pre-handler pending check (the documented residual then applies to that launch) | -| Install-time delivery | Signal delivered between the four `sigaction` calls | All four signals are still blocked during install, so nothing can be delivered mid-install | -| Signal floods | Many termination signals while blocked | Non-realtime signals coalesce in the kernel; the flag records one — any of them means die | -| Mask leak to child | Child inheriting blocked termination signals | Mask restored before `execvp` on every path (explicit + `Drop` on early-Err) | -| Lost signal | Deferred signal swallowed | `die_by` resets `SIG_DFL`, restores the saved mask, re-raises; `libc::_exit(128 + sig)` if `raise` itself fails | -| Signal after final check | TERM lands between flag check and `execvp` | The flag is read a second time immediately before `execvp`; only a signal inside the execve path itself (~microseconds) can slip through — recorded but unexamined, the manager's escalation (SIGKILL) performs the stop. Supervision-semantics, not plaintext exposure (the files are the child's by design) | +| Thread-model mismatch | `sigprocmask` is unspecified in multithreaded processes | `pthread_sigmask` form on Darwin; on Linux the launcher is single-threaded at this point (worker threads exist only in serve mode) | +| libc-reserved signals | Masking a signal a libc reserves is UB (rustix `runtime` safety note) | The set holds only TERM/INT/HUP/QUIT — none reserved (glibc reserves 32/33) | +| Mask clobber | Restoring a mask never captured | The Linux leg stores `None` on block failure (logged); restore then no-ops | +| Mask leak to the service | Service inheriting blocked termination signals | Mask restored before `execvp` on every path (explicit + `Drop` on early-Err) — the monitor *wants* the mask and is the only inheritor | ## Remaining Risks | Risk | Likelihood | Impact | |------|------------|--------| -| Kernel/libc signal quirks on future Darwin versions | Very low | Missed deferral (fail-open to pre-A11 behavior) | -| Operator sends SIGKILL | n/a | Unblockable by design; ramdisk contents persist until next boot — accepted residual | +| Kernel/libc signal quirks on future OS versions | Very low | Missed deferral (fail-open to pre-A11 behavior) | +| Operator sends SIGKILL mid-write | n/a | Unblockable by design; ramdisk contents persist until next boot (macOS) — accepted residual; the monitor covers everything *after* the fork | -For the design-level race in how the guard is *used* (pending-check → -mask-restore → exec — a property of the launch flow, not of these -unsafe blocks), see the threat model's +For the design-level stop semantics the guard feeds into (monitor +forwarding, grace, escalation, cleanup on every death path), see the +threat model's [plaintext persistence window](../architecture/threat-model.md#plaintext-file-persistence-window-files-mode--mitigated) -section. +section and the [monitor page](./monitor.md). ## Tests -`launcher::tests::disarm_records_signal_raised_during_the_window` -(deterministic, macOS): blocks the guard, raises SIGTERM at the process -itself, and asserts `disarm()` returns `Some(SIGTERM)` with the process -still alive — proving the whole handoff: delivery goes to the recording -handler, never to the default disposition. The surrounding write/exec -contract is exercised by the exec integration suites -(`tests/exec_check.rs`, `tests/exec_conformance/`). +The guard's contract is exercised end-to-end by the monitor tests +(`monitor::tests` — every one of them blocks via +`TerminationGuard::block()` before forking the real monitor loop, exactly +mirroring production) and by the exec integration suites +(`tests/exec_check.rs`, `tests/exec_conformance/`). The retired +flag-handler test was removed with the handler. diff --git a/src/launcher.rs b/src/launcher.rs index 059610c..72e3a69 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -17,58 +17,43 @@ use crate::bundle::{parse_bundle, resolve_bundle}; use crate::exec_config::{ExecConfig, ExecMode}; use crate::key_source::load_ring; use crate::keys::resolve_all; +use crate::monitor::{self, STOP_SIGNALS}; use crate::ramdisk::verify_ramdisk; use crate::secret_files::{ Resolved, cleanup_written, env_pairs, open_secrets_dir, prune_stale, write_secret_file, }; use crate::server::{fetch_bytes, log, read_capped}; -#[cfg(target_os = "macos")] -use std::sync::atomic::{AtomicI32, Ordering}; -/// macOS-only guard deferring termination signals across the window where -/// plaintext secret files exist on the ramdisk (audit 2026-08-02 A11). -/// The ramdisk persists across process death, so a signal landing -/// mid-write would otherwise strand partial plaintext. Signals are -/// *blocked* across the window; before execvp the guard is disarmed by -/// installing a flag-recording handler (while still blocked) and then -/// restoring the saved mask — anything pending from the window is -/// delivered to that handler, never to the default disposition, so no -/// termination signal can kill the launcher without cleanup running -/// first. The handler's body is a single atomic store (the canonical -/// async-signal-safe operation). +/// Guard deferring termination signals across the window where plaintext +/// secret files exist on the ramdisk/tmpfs (audit 2026-08-02 A11). A +/// signal landing mid-write would otherwise strand partial plaintext, so +/// the four termination signals (`STOP_SIGNALS`) are *blocked* across the +/// window. The sibling monitor is then forked — it inherits the blocked +/// mask and keeps it for life (see monitor.rs) — and the parent restores +/// the saved mask before execvp so the service starts with a clean +/// signal state. /// -/// Linux needs no equivalent: tmpfs does not persist across reboots, -/// systemd's `ExecStopPost` runs `postmaster cleanup`, and the next -/// launch's `prune_stale` removes residuals — documented decision per A11. -#[cfg(target_os = "macos")] -static PENDING_SIG: AtomicI32 = AtomicI32::new(0); - -/// Records a deferred termination signal for the launcher's -/// check-before-exec. This MUST remain a pure atomic store: no logging, -/// no allocation, no locking — anything more is unsound in async-signal -/// context. +/// The sigaction flag-handler and second pre-exec gate this guard used +/// to implement were retired with the sibling-monitor design +/// (2026-08-05): the monitor owns stop semantics, so no async handler is +/// needed anywhere. What remains is the deterministic write window +/// (`block`) and the pre-exec mask restore (`restore_mask`) — now real +/// on Linux too, because the fork+monitor model runs there as well. #[cfg(target_os = "macos")] -unsafe extern "C" fn record_sig(sig: libc::c_int) { - PENDING_SIG.store(sig, Ordering::Relaxed); -} - -#[cfg(target_os = "macos")] -struct TerminationGuard { +pub(crate) struct TerminationGuard { old: libc::sigset_t, } #[cfg(target_os = "macos")] impl TerminationGuard { - const SIGNALS: [i32; 4] = [libc::SIGTERM, libc::SIGINT, libc::SIGHUP, libc::SIGQUIT]; - - fn block() -> Self { + pub(crate) fn block() -> Self { unsafe { // SAFETY: zeroed sigset_t is a valid empty set representation; // all pointers are valid and outlive the calls. let mut set: libc::sigset_t = std::mem::zeroed(); libc::sigemptyset(&mut set); - for sig in Self::SIGNALS { - libc::sigaddset(&mut set, sig); + for sig in STOP_SIGNALS { + libc::sigaddset(&mut set, sig.as_raw()); } let mut old: libc::sigset_t = std::mem::zeroed(); // pthread form: correct in single- and multi-threaded processes. @@ -77,97 +62,14 @@ impl TerminationGuard { } } - /// Disarm the guard at the end of the write window: install - /// `record_sig` for the deferred signals while they are still blocked - /// (so nothing can be delivered mid-install), then restore the saved - /// mask. Pending termination signals are delivered to the handler and - /// recorded — never to the default disposition — and the first one - /// observed is returned. `None` means no termination signal arrived - /// across the entire window; the mask is restored either way, and - /// caught-signal dispositions reset to default at execvp, so the - /// child starts with a clean signal state. - fn disarm(&self) -> Option { - let mut ok = true; - unsafe { - // SAFETY: zeroed sigaction is a valid starting representation; - // sa_mask is made a valid empty set; the handler pointer is a - // valid function with the C signal-handler ABI. - let mut act: libc::sigaction = std::mem::zeroed(); - libc::sigemptyset(&mut act.sa_mask); - act.sa_sigaction = record_sig as *const () as usize; - for sig in Self::SIGNALS { - if libc::sigaction(sig, &act, std::ptr::null_mut()) != 0 { - ok = false; - } - } - } - if !ok { - // Defensive: sigaction(2) cannot realistically fail for these - // four signals (EINVAL covers SIGKILL/SIGSTOP/invalid, none of - // which we touch) — but if it ever does, fall back to the - // pre-handler pending check rather than silently weaken the - // guard. The residual race that disarm() exists to close then - // applies to this launch (see the threat model). - log("termination-guard: sigaction failed; falling back to pending-check"); - let sig = self.pending(); - self.restore_mask(); - return sig; - } - self.restore_mask(); - let sig = PENDING_SIG.load(Ordering::Relaxed); - (sig != 0).then_some(sig) - } - - /// First deferred termination signal pending right now, if any. - /// Fallback path for `disarm` when the handler cannot be installed. - fn pending(&self) -> Option { - unsafe { - // SAFETY: zeroed sigset_t is valid; sigpending fills it. - let mut set: libc::sigset_t = std::mem::zeroed(); - if libc::sigpending(&mut set) != 0 { - return None; - } - for sig in Self::SIGNALS { - if libc::sigismember(&set, sig) == 1 { - return Some(sig); - } - } - None - } - } - - /// A termination signal recorded by `record_sig` since `disarm`, if - /// any. Read once more immediately before `execvp` so a signal - /// consumed in the disarm→exec gap is not carried silently into the - /// child (A11). - fn recorded(&self) -> Option { - let sig = PENDING_SIG.load(Ordering::Relaxed); - (sig != 0).then_some(sig) - } - - /// Restore the saved signal mask. Always called before execvp — the - /// child must not inherit blocked termination signals. - fn restore_mask(&self) { + /// Restore the saved signal mask. The parent calls this before + /// execvp — the child must not inherit blocked termination signals. + pub(crate) fn restore_mask(&self) { unsafe { // SAFETY: restoring a previously saved valid mask. libc::pthread_sigmask(libc::SIG_SETMASK, &self.old, std::ptr::null_mut()); } } - - /// Restore the mask, reset the signal to its default disposition, and - /// re-raise it so the process dies by the signal as the sender - /// intended. Never returns. - fn die_by(&self, sig: i32) -> ! { - unsafe { - // SAFETY: plain single-threaded-at-this-point signal ops; - // SIG_DFL is the documented default-disposition constant. - libc::signal(sig, libc::SIG_DFL); - libc::pthread_sigmask(libc::SIG_SETMASK, &self.old, std::ptr::null_mut()); - libc::raise(sig); - // Unreachable unless raise(3) itself failed. - libc::_exit(128 + sig); - } - } } #[cfg(target_os = "macos")] @@ -177,30 +79,58 @@ impl Drop for TerminationGuard { } } -/// No-op on non-macOS platforms (see the macOS docs above). -#[cfg(not(target_os = "macos"))] -struct TerminationGuard; +/// Linux leg of the guard (see the macOS docs above): same block/restore +/// contract via rustix's raw `rt_sigprocmask` — no libc FFI. +#[cfg(target_os = "linux")] +pub(crate) struct TerminationGuard { + /// `None` only if the block call failed (logged); restore then no-ops + /// rather than clobbering a mask that was never captured. + old: Option, +} -#[cfg(not(target_os = "macos"))] +#[cfg(target_os = "linux")] impl TerminationGuard { - fn block() -> Self { - Self - } - - /// No persistence window exists on non-macOS platforms (see above): - /// always clear. - fn disarm(&self) -> Option { - None + pub(crate) fn block() -> Self { + let mut set = rustix::runtime::KernelSigSet::empty(); + for sig in STOP_SIGNALS { + set.insert(sig); + } + // SAFETY: the set holds only the four standard termination + // signals — none reserved by any libc in the process (glibc + // reserves 32/33, untouched). The launcher is single-threaded at + // this point (the exec path spawns no threads; worker threads + // exist only in serve mode). + match unsafe { + rustix::runtime::kernel_sigprocmask(rustix::runtime::How::BLOCK, Some(&set)) + } { + Ok(old) => Self { old: Some(old) }, + Err(e) => { + // rt_sigprocmask cannot realistically fail here (EINVAL/ + // EFAULT cover bad arguments, both impossible) — but if it + // ever does, log it and run unguarded rather than silently + // pretend the window is protected. + log(&format!("termination-guard: sigprocmask failed: {e}")); + Self { old: None } + } + } } - /// Always clear (see above). - fn recorded(&self) -> Option { - None + /// Restore the saved signal mask (see the macOS docs). + pub(crate) fn restore_mask(&self) { + if let Some(old) = &self.old { + // SAFETY: restoring a mask previously returned by the kernel + // for this thread. + let _ = unsafe { + rustix::runtime::kernel_sigprocmask(rustix::runtime::How::SETMASK, Some(old)) + }; + } } +} - fn die_by(&self, _sig: i32) -> ! { - // Unreachable: disarm() is always None here. - std::process::abort() +#[cfg(target_os = "linux")] +impl Drop for TerminationGuard { + fn drop(&mut self) { + self.restore_mask(); } } @@ -348,20 +278,24 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() cfg.validate_shape()?; let program = argv.first().ok_or("exec: empty argv")?; - // Defer termination signals until just before execvp, so a signal - // landing mid-write can't strand plaintext on disk (audit - // 2026-08-02 A11; no-op on Linux — see TerminationGuard docs). + // Defer termination signals until the fork/exec below, so a signal + // landing mid-write can't strand plaintext on disk (audit 2026-08-02 + // A11 — see TerminationGuard docs). The fork-child monitor inherits + // the blocked mask and keeps it for life; the parent restores the + // saved mask before execvp. let sig_guard = TerminationGuard::block(); let mut extra: Vec<(OsString, OsString)> = Vec::new(); // Names of plaintext files written beneath the pinned secrets-dir - // fd, tracked across the match so the failure paths can unlink them - // fd-relative (audit 2026-08-02 A9). + // fd, tracked across the match so the failure paths (and the monitor, + // post-fork) can unlink them fd-relative (audit 2026-08-02 A9). let mut written: Vec = Vec::new(); // The pinned secrets-dir fd (Files / Credentials-fetch modes only). // Opened ONCE with O_DIRECTORY|O_NOFOLLOW|O_RDONLY|CLOEXEC and kept // until after the exec-failure cleanup, so every write and every // cleanup unlink is relative to the same pinned inode (audit - // 2026-08-02 A12). + // 2026-08-02 A12). Across the fork the monitor inherits the fd + // (CLOEXEC fires only on exec, which the monitor never performs) and + // holds it for the service's lifetime. let mut secrets_dir_fd: Option = None; match cfg.mode { @@ -503,32 +437,68 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() } } - // A termination signal arrived during the write window: remove the - // plaintext, then die by that signal as the sender intended (A11). - if let Some(sig) = sig_guard.disarm() { - if let Some(dir_fd) = &secrets_dir_fd { - cleanup_written(dir_fd, &written); + // Zeroization is complete at this point (the key ring dropped inside + // decrypt(); `resolved` dropped at the end of each arm above): fork + // the sibling monitor BEFORE exec. The fork-child keeps the guard's + // blocked mask for life and supervises this process — stop-signal + // forwarding, bounded grace, SIGKILL escalation, and plaintext cleanup + // on every death path (sibling-monitor design 2026-08-05; see + // monitor.rs). The parent execs the service exactly as before, so + // MainPID is unchanged. The monitor runs for ALL exec launches, + // including env mode (uniform semantics; its cleanup is a no-op + // there). The pid is captured pre-fork: post-fork the parent IS the + // service-to-be, so the monitor needs no racy getppid. + let service_pid = rustix::process::getpid(); + // SAFETY: fork(2) in a single-threaded process (the exec path spawns + // no threads; the daemon's worker threads exist only in serve mode). + // The fork-child executes only monitor::run — the async-signal-safe + // syscall set documented in monitor.rs: no allocation, no stdio + // locks, no destructors — and exits via _exit/exit_group. rustix + // deliberately has no fork wrapper; on Linux this is the one libc FFI + // call on the exec path, flagged in docs/src/unsafe-code/monitor.md. + match unsafe { libc::fork() } { + -1 => { + // No monitor means no stop semantics and no cleanup on + // abnormal death: fail closed like an exec failure rather + // than launch unsupervised. + if let Some(dir_fd) = &secrets_dir_fd { + cleanup_written(dir_fd, &written); + } + let err = std::io::Error::last_os_error(); + log(&format!("exec {program}: fork: {err}")); + return Err(format!("exec {program}: fork: {err}")); + } + 0 => { + // Fork-child = the monitor (never returns). sig_guard is + // deliberately NOT dropped here: monitor::run diverges + // (`-> !`) and the _exit path runs no destructors, so the + // termination mask stays blocked for the monitor's life + // (run() re-asserts the block regardless). The inherited + // `extra` env pairs are SCRUBBED first — they hold plaintext + // values in env mode (and files-mode passthrough), and + // free() alone would leave the bytes in the monitor's + // mapped pages for its whole life (threat model: monitor + // inherited heap). + for (k, v) in extra { + drop(monitor::wipe_pair(k, v)); + } + monitor::run(service_pid, secrets_dir_fd, written); } - sig_guard.die_by(sig); + _ => {} } - // disarm() already restored the pre-guard signal mask, and - // caught-signal dispositions reset to default at execvp — the child - // starts with a clean signal state. + // Parent only from here (the fork-child diverged). Restore the + // pre-guard signal mask so the service starts with a clean signal + // state, then exec exactly as before. + sig_guard.restore_mask(); let mut cmd = std::process::Command::new(program); cmd.args(&argv[1..]).envs(extra); - // Final gate: a termination signal recorded since disarm() must not - // be carried silently into the child — clean up and die by it (A11). - if let Some(sig) = sig_guard.recorded() { - if let Some(dir_fd) = &secrets_dir_fd { - cleanup_written(dir_fd, &written); - } - sig_guard.die_by(sig); - } let err = cmd.exec(); // only returns on failure // execvp failed: the process image was NOT replaced, so any // plaintext secret files written above would otherwise persist // (the macOS ramdisk survives process death). Remove them before - // returning the error (audit 2026-08-02 A9). + // returning the error (audit 2026-08-02 A9). The monitor watching + // this process fires on the imminent exit and cleans again — + // unlinkat of already-removed names is a no-op. if let Some(dir_fd) = &secrets_dir_fd { cleanup_written(dir_fd, &written); } @@ -541,28 +511,6 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() mod tests { use super::*; - /// The disarm handoff must convert a signal raised during the blocked - /// window into a recorded flag instead of process death — the whole - /// point of the flag-handler design (A11 race closure). - #[cfg(target_os = "macos")] - #[test] - fn disarm_records_signal_raised_during_the_window() { - PENDING_SIG.store(0, Ordering::Relaxed); - let guard = TerminationGuard::block(); - // Sent while blocked: pends. At disarm it is delivered to the - // recording handler, not the default disposition — so this test - // process keeps running. - unsafe { - libc::raise(libc::SIGTERM); - } - assert_eq!(guard.disarm(), Some(libc::SIGTERM)); - // Leave the process as we found it. - PENDING_SIG.store(0, Ordering::Relaxed); - unsafe { - libc::signal(libc::SIGTERM, libc::SIG_DFL); - } - } - #[test] fn validate_credential_keys_accepts_identifiers() { assert!(validate_credential_keys(&["DB_URL".to_string()]).is_ok()); diff --git a/src/lib.rs b/src/lib.rs index 172589e..6ae9304 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,6 +20,7 @@ pub mod cli; pub mod exec_config; pub mod keys; pub mod launcher; +pub(crate) mod monitor; pub mod ramdisk; pub mod secret_files; pub mod server; diff --git a/src/monitor.rs b/src/monitor.rs new file mode 100644 index 0000000..740a4a9 --- /dev/null +++ b/src/monitor.rs @@ -0,0 +1,758 @@ +//! Sibling launch monitor — a per-service fork-child that owns stop +//! semantics and plaintext cleanup on every service-death path +//! (sibling-monitor launch supervision design, 2026-08-05). +//! +//! The launcher forks the monitor after validation, plaintext writes, and +//! zeroization, and immediately before `execvp`: the parent restores its +//! pre-guard signal mask and execs the service (MainPID unchanged), and +//! the fork-child becomes the monitor. The monitor carries only the +//! pinned secrets-dir fd (inherited across fork; `CLOEXEC` does not fire +//! because the monitor never execs) and the list of written entry names +//! — in env mode both are empty and cleanup is a no-op, but the monitor +//! still runs (uniform semantics: it forwards stops regardless). +//! +//! Signal discipline: the four termination signals ({TERM, INT, HUP, +//! QUIT}) stay *blocked for the monitor's whole life* — the mask is +//! inherited from the launcher's `TerminationGuard` across fork and +//! re-asserted at monitor start — and are consumed synchronously via the +//! `sigpending`/`sigwait` family. No signal handlers exist anywhere in +//! the process (the sigaction flag-handler was retired with this design). +//! SIGPIPE is additionally blocked so a stderr write to a closed pipe +//! cannot kill the monitor mid-supervision. +//! +//! Loop semantics (one tick = `POLL_INTERVAL`): +//! 1. A pending stop signal is dequeued → forward it to the service → +//! wait up to `GRACE` (250 ms constant — a single global security +//! policy, deliberately not configurable) for the service to die → +//! if still alive, `SIGKILL` → wait for death (unbounded: `SIGKILL` +//! cannot be blocked or ignored; only a D-state hang can delay it, and +//! abandoning cleanup is worse) → `cleanup_written` → exit. +//! 2. Otherwise, if the service is dead (liveness watch: pidfd + `poll` +//! on Linux, kqueue `EVFILT_PROC`/`NOTE_EXIT` on macOS, `kill(pid, 0)` +//! only as fallback) → `cleanup_written` → exit. This covers natural +//! exit, `kill -9`, and crashes — the net-new cleanup coverage. +//! 3. Otherwise, sleep one tick. Liveness/stop latency adds to cleanup +//! latency, never to the grace cap. +//! +//! Fork-child discipline (the soundness contract for `launcher.rs`'s +//! `fork`): the fork parent may be multithreaded (it is under +//! `cargo test`), so between fork and exit the monitor performs no +//! allocation and takes no stdio locks — only the async-signal-safe +//! syscall set: signal mask/wait ops, `pidfd_open`/`poll`/`kevent`, +//! `kill`/`pidfd_send_signal`, `unlinkat`, `nanosleep`, raw `write(2)` +//! for diagnostics, and `_exit`/`exit_group`. All inputs (`names`, the +//! dir fd) are allocated pre-fork and moved in. Exit never runs +//! destructors, atexit handlers, or stdio flushes (inherited buffers +//! must not flush twice). + +use std::os::fd::{AsFd, OwnedFd}; +use std::time::{Duration, Instant}; + +use rustix::io::Errno; +use rustix::process::{Pid, Signal, kill_process, test_kill_process}; +use zeroize::Zeroize; + +#[cfg(target_os = "linux")] +use rustix::event::{PollFd, PollFlags, poll}; +#[cfg(target_os = "linux")] +use rustix::process::{PidfdFlags, pidfd_open, pidfd_send_signal}; +#[cfg(target_os = "linux")] +use rustix::runtime::{self, KernelSigSet}; +#[cfg(target_os = "macos")] +use std::os::fd::{AsRawFd, FromRawFd}; + +use crate::secret_files::cleanup_written; + +/// Scrub one inherited env pair in place and return the wiped buffers +/// (threat model: monitor inherited heap). The fork-child monitor +/// inherits the launcher's `extra` env array — plaintext values in env +/// mode and in files-mode passthrough — and `free()` alone would leave +/// those bytes in the monitor's mapped pages for its whole life (the +/// monitor never allocates again, so they would never even be reused). +/// `into_vec` takes ownership of the existing `OsString` buffer with no +/// copy, and `zeroize` wipes it in place before the buffers are freed. +pub(crate) fn wipe_pair(k: std::ffi::OsString, v: std::ffi::OsString) -> (Vec, Vec) { + use std::os::unix::ffi::OsStringExt; + let mut kb = k.into_vec(); + let mut vb = v.into_vec(); + kb.zeroize(); + vb.zeroize(); + (kb, vb) +} + +/// The termination signals the monitor consumes synchronously and +/// forwards to the service. Also blocked across the launcher's +/// plaintext-write window (`TerminationGuard`) and inherited by the +/// monitor across fork. +pub(crate) const STOP_SIGNALS: [Signal; 4] = [Signal::TERM, Signal::INT, Signal::HUP, Signal::QUIT]; + +/// Grace between forwarding a stop signal and `SIGKILL` escalation: +/// 250 ms, a single global security policy (author ruling 2026-08-05 — +/// per-service erosion is unacceptable; the per-unit knob is the service +/// manager's own stop timeout). Injectable in tests via `run_inner`. +pub(crate) const GRACE: Duration = Duration::from_millis(250); + +/// Liveness/poll tick. Short is fine: this latency adds to cleanup +/// latency, not to the grace cap. +pub(crate) const POLL_INTERVAL: Duration = Duration::from_millis(25); + +/// Zero timeout for non-blocking `poll(2)` liveness checks on the pidfd. +#[cfg(target_os = "linux")] +const ZERO_TIMESPEC: rustix::event::Timespec = rustix::event::Timespec { + tv_sec: 0, + tv_nsec: 0, +}; + +/// Monitor entry point with production timing. Never returns: the +/// monitor exits the process (via `_exit`/`exit_group`) once the service +/// is dead and the plaintext is cleaned. `dir_fd`/`names` are the pinned +/// secrets-dir fd and written entry names from the launcher; both are +/// absent in env mode (cleanup is then a no-op, but the monitor still +/// runs — uniform stop semantics). +pub(crate) fn run(service_pid: Pid, dir_fd: Option, names: Vec) -> ! { + run_inner(service_pid, dir_fd, names, GRACE, POLL_INTERVAL) +} + +/// The monitor loop, parameterized for deterministic tests. +fn run_inner( + service_pid: Pid, + dir_fd: Option, + names: Vec, + grace: Duration, + poll_interval: Duration, +) -> ! { + block_monitor_signals(); + let set = stop_sigset(); + let watch = Watch::new(service_pid); + loop { + if let Some(sig) = take_pending_stop(&set) { + // Stop semantics (diverges): forward, bounded grace, SIGKILL + // escalation, then clean and exit. + signal_service(&watch, service_pid, sig); + if !wait_for_death(&watch, service_pid, grace, poll_interval) { + monitor_log("postmaster monitor: grace expired; escalating to SIGKILL"); + signal_service(&watch, service_pid, Signal::KILL); + while !watch.dead(service_pid) { + std::thread::sleep(poll_interval); + } + } + cleanup_and_exit(dir_fd.as_ref(), &names); + } + if watch.dead(service_pid) { + // Service death from any cause: natural exit, kill -9, crash. + cleanup_and_exit(dir_fd.as_ref(), &names); + } + std::thread::sleep(poll_interval); + } +} + +/// Wait up to `grace` for the service to die. Returns true when death is +/// confirmed within the grace window. +fn wait_for_death(watch: &Watch, pid: Pid, grace: Duration, poll_interval: Duration) -> bool { + let deadline = Instant::now() + grace; + loop { + if watch.dead(pid) { + return true; + } + let now = Instant::now(); + if now >= deadline { + return false; + } + std::thread::sleep(poll_interval.min(deadline - now)); + } +} + +/// Unlink the written plaintext files (fd-relative, best-effort — an +/// already-vanished entry is ignored) and exit the monitor. Never +/// returns. +fn cleanup_and_exit(dir_fd: Option<&Fd>, names: &[String]) -> ! { + if let Some(fd) = dir_fd { + cleanup_written(fd, names); + } else if !names.is_empty() { + // Unreachable from the launcher (names are only tracked in fd + // modes); logged so a future caller regression is visible. + monitor_log("postmaster monitor: entry names without a directory fd; cannot clean"); + } + exit_process(0) +} + +/// Send `sig` to the service. Delivery errors (e.g. `ESRCH` because the +/// service died first) are ignored — the subsequent death wait settles +/// the outcome either way. +#[cfg(target_os = "linux")] +fn signal_service(watch: &Watch, pid: Pid, sig: Signal) { + // With a pidfd, signal through it: pidfd_send_signal(2) pins the + // process and cannot hit a recycled PID — the same PID-reuse + // rationale that makes pidfd the liveness choice. + if let Watch::Pidfd(fd) = watch { + let _ = pidfd_send_signal(fd, sig); + } else { + let _ = kill_process(pid, sig); + } +} + +/// Send `sig` to the service (see the Linux leg). Darwin has no pidfd, +/// so forwarding is plain kill(2); the bounded PID-reuse exposure on the +/// macOS stop path is documented in the threat model. +#[cfg(target_os = "macos")] +fn signal_service(_watch: &Watch, pid: Pid, sig: Signal) { + let _ = kill_process(pid, sig); +} + +/// Exit the monitor without running destructors, atexit handlers, or +/// stdio flushes — mandatory in a fork-child (inherited buffers and +/// handlers must not run twice; see module docs). +#[cfg(target_os = "linux")] +fn exit_process(code: i32) -> ! { + // exit_group(2) ≡ _exit(2): a safe rustix wrapper, no libc FFI. + runtime::exit_group(code) +} + +/// Exit the monitor (see the Linux leg). +#[cfg(target_os = "macos")] +fn exit_process(code: i32) -> ! { + // SAFETY: _exit(2) is async-signal-safe and callable from any + // context; it runs no handlers and flushes nothing — exactly the + // fork-child exit semantics required here. + unsafe { libc::_exit(code) } +} + +/// Best-effort diagnostic to stderr that stays inside the fork-child +/// discipline: a raw write(2) — no allocation, no stdio locks (the fork +/// parent may be multithreaded, e.g. under `cargo test`). SIGPIPE is +/// blocked for the monitor's life, so a closed pipe cannot kill us here. +fn monitor_log(msg: &str) { + // SAFETY: fd 2 is the process's stderr; if it has been closed the + // write simply fails with EBADF. The borrowed fd is not stored and + // does not outlive the call; nothing is closed. + let stderr = unsafe { std::os::fd::BorrowedFd::borrow_raw(2) }; + let _ = rustix::io::write(stderr, msg.as_bytes()); + let _ = rustix::io::write(stderr, b"\n"); +} + +/// The service liveness watch. Event sources (pidfd `POLLIN`, kqueue +/// `NOTE_EXIT`) fire at process exit — zombie- and PID-reuse-proof, +/// which is why they are the choice and `kill(pid, 0)` polling is only +/// the fallback (zombie-blind, PID-reuse-prone). +#[cfg(target_os = "linux")] +enum Watch { + /// pidfd(2) opened at monitor start; the fd pins the process. + Pidfd(OwnedFd), + /// kill(pid, 0) fallback for kernels without pidfd_open (< 5.3). + Poll, + /// The service was already dead when the monitor started. + Dead, +} + +#[cfg(target_os = "linux")] +impl Watch { + fn new(pid: Pid) -> Self { + match pidfd_open(pid, PidfdFlags::empty()) { + Ok(fd) => Self::Pidfd(fd), + // ESRCH is race-free "definitely gone" — clean up at once. + Err(Errno::SRCH) => Self::Dead, + // ENOSYS (old kernel), EMFILE, …: degrade to polling. + Err(_) => { + monitor_log( + "postmaster monitor: pidfd_open failed; falling back to kill(pid, 0) polling", + ); + Self::Poll + } + } + } + + fn dead(&self, pid: Pid) -> bool { + match self { + Self::Dead => true, + Self::Poll => matches!(test_kill_process(pid), Err(Errno::SRCH)), + Self::Pidfd(fd) => { + let mut fds = [PollFd::new(fd, PollFlags::IN)]; + match poll(&mut fds, Some(&ZERO_TIMESPEC)) { + // POLLIN: the process has terminated (fires at exit, + // not at reap — zombie-proof). POLLERR is treated as + // dead too: a pidfd that errors cannot supervise. + Ok(_) => fds[0].revents().intersects(PollFlags::IN | PollFlags::ERR), + // A failed poll means "unknown", not "dead": keep + // watching rather than abandon supervision. + Err(_) => false, + } + } + } + } +} + +/// The service liveness watch (see the Linux leg). +#[cfg(target_os = "macos")] +enum Watch { + /// kqueue with `EVFILT_PROC`/`NOTE_EXIT` registered for the service. + Kqueue(OwnedFd), + /// kill(pid, 0) fallback (kqueue creation failed — fd exhaustion). + Poll, + /// The service was already dead when the monitor started. + Dead, +} + +#[cfg(target_os = "macos")] +impl Watch { + fn new(pid: Pid) -> Self { + // ESRCH is race-free "definitely gone" — clean up at once. + if matches!(test_kill_process(pid), Err(Errno::SRCH)) { + return Self::Dead; + } + // SAFETY: kqueue(2) has no preconditions and returns a fresh + // queue fd on success. The kevent registration passes valid + // stack pointers and a well-formed changelist built from + // constants; a NULL timeout with an empty eventlist cannot block. + unsafe { + let kq = libc::kqueue(); + if kq == -1 { + monitor_log( + "postmaster monitor: kqueue failed; falling back to kill(pid, 0) polling", + ); + return Self::Poll; + } + let change = libc::kevent { + ident: pid.as_raw_pid() as usize, + filter: libc::EVFILT_PROC, + flags: libc::EV_ADD, + fflags: libc::NOTE_EXIT, + data: 0, + udata: std::ptr::null_mut(), + }; + if libc::kevent(kq, &change, 1, std::ptr::null_mut(), 0, std::ptr::null()) == -1 { + // With a changelist-only call, a knote error comes back + // as the kevent errno. ESRCH means the pid lookup failed + // because the service already exited (xnu drops exited + // procs from the pid table before they are reaped) — + // race-free "definitely gone", same as pidfd_open's ESRCH + // on Linux, so clean up at once rather than degrading to + // zombie-blind polling. + let dead = std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH); + libc::close(kq); + if dead { + return Self::Dead; + } + monitor_log( + "postmaster monitor: kevent registration failed; falling back to kill(pid, 0) polling", + ); + return Self::Poll; + } + // SAFETY: kq is a fresh, valid fd owned by this process; + // wrapping it in OwnedFd closes it exactly once at drop. + Self::Kqueue(OwnedFd::from_raw_fd(kq)) + } + } + + fn dead(&self, pid: Pid) -> bool { + match self { + Self::Dead => true, + Self::Poll => matches!(test_kill_process(pid), Err(Errno::SRCH)), + Self::Kqueue(kq) => { + // SAFETY: `ev`/`ts` are valid stack locals that outlive + // the call; a zero timeout makes kevent(2) a non-blocking + // queue drain; the queue fd is valid (owned). + unsafe { + let mut ev: libc::kevent = std::mem::zeroed(); + let ts = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + if libc::kevent(kq.as_raw_fd(), std::ptr::null(), 0, &mut ev, 1, &ts) > 0 { + // The queue holds only the one NOTE_EXIT knote. + return true; + } + } + // Defense-in-depth net for any exit the knote misses + // (xnu attach subtleties): ESRCH is race-free "definitely + // gone". The registration-time case of this race returns + // Watch::Dead above instead. + matches!(test_kill_process(pid), Err(Errno::SRCH)) + } + } + } +} + +/// Block the stop signals plus `SIGPIPE` for the monitor's lifetime. +/// The four stop signals are normally already blocked by the launcher's +/// `TerminationGuard` and inherited across fork (blocking again is a +/// no-op); re-asserting keeps the monitor correct when the caller did +/// not pre-block (unit tests). `SIGPIPE` is monitor-local so the raw +/// stderr write in `monitor_log` cannot kill the monitor via a closed +/// pipe. A failure is logged and supervision continues: the inherited +/// mask is the common case, and failing to block cannot strand +/// plaintext by itself. +#[cfg(target_os = "linux")] +fn block_monitor_signals() { + let mut set = KernelSigSet::empty(); + for sig in STOP_SIGNALS { + set.insert(sig); + } + set.insert(Signal::PIPE); + // SAFETY: single-threaded fork-child; the set holds only standard + // signals — none reserved by a libc in the process (glibc reserves + // 32/33, untouched). Blocking these signals for life breaks no other + // code's assumptions: the monitor consumes the stop set synchronously + // and never installs handlers. + if unsafe { runtime::kernel_sigprocmask(runtime::How::BLOCK, Some(&set)) }.is_err() { + monitor_log("postmaster monitor: failed to block termination signals"); + } +} + +/// Block the stop signals plus `SIGPIPE` (see the Linux leg). +#[cfg(target_os = "macos")] +fn block_monitor_signals() { + // SAFETY: zeroed sigset_t is a valid empty set representation; all + // pointers are valid stack locals that outlive the calls; the pthread + // form is correct in single- and multi-threaded processes. + unsafe { + let mut set: libc::sigset_t = std::mem::zeroed(); + libc::sigemptyset(&mut set); + for sig in STOP_SIGNALS { + libc::sigaddset(&mut set, sig.as_raw()); + } + libc::sigaddset(&mut set, libc::SIGPIPE); + if libc::pthread_sigmask(libc::SIG_BLOCK, &set, std::ptr::null_mut()) != 0 { + monitor_log("postmaster monitor: failed to block termination signals"); + } + } +} + +/// The set of signals consumed synchronously by the loop. +#[cfg(target_os = "linux")] +fn stop_sigset() -> KernelSigSet { + let mut set = KernelSigSet::empty(); + for sig in STOP_SIGNALS { + set.insert(sig); + } + set +} + +/// The set of signals consumed synchronously by the loop. +#[cfg(target_os = "macos")] +fn stop_sigset() -> libc::sigset_t { + // SAFETY: zeroed sigset_t is a valid empty set representation; + // sigemptyset/sigaddset operate on a valid stack local. + unsafe { + let mut set: libc::sigset_t = std::mem::zeroed(); + libc::sigemptyset(&mut set); + for sig in STOP_SIGNALS { + libc::sigaddset(&mut set, sig.as_raw()); + } + set + } +} + +/// Dequeue a pending stop signal without blocking, if one is pending. +/// The signals are blocked for life, so they pend until consumed here — +/// synchronous consumption, no handlers anywhere. (Darwin has no +/// `sigtimedwait`, so both platforms use the portable +/// sigpending-then-sigwait form on the poll tick; the bounded stop +/// latency — one tick — is the latency the design explicitly budgets.) +#[cfg(target_os = "linux")] +fn take_pending_stop(set: &KernelSigSet) -> Option { + if !STOP_SIGNALS + .iter() + .any(|s| runtime::kernel_sigpending().contains(*s)) + { + return None; + } + // SAFETY: a signal from the set IS pending (checked above), so + // sigwait dequeues and returns immediately; the set holds only + // standard non-reserved signals; single-threaded here. + unsafe { runtime::kernel_sigwait(set) }.ok() +} + +/// Dequeue a pending stop signal without blocking (see the Linux leg). +#[cfg(target_os = "macos")] +fn take_pending_stop(set: &libc::sigset_t) -> Option { + // SAFETY: zeroed sigset_t is valid and sigpending fills it; sigwait + // is called only when a set member is pending, so it returns + // immediately; all pointers are valid stack locals. + unsafe { + let mut pending: libc::sigset_t = std::mem::zeroed(); + if libc::sigpending(&mut pending) != 0 { + return None; + } + if !STOP_SIGNALS + .iter() + .any(|s| libc::sigismember(&pending, s.as_raw()) == 1) + { + return None; + } + let mut got: libc::c_int = 0; + if libc::sigwait(set, &mut got) != 0 { + return None; + } + Signal::from_named_raw(got) + } +} + +#[cfg(not(any(target_os = "linux", target_os = "macos")))] +compile_error!("postmaster's sibling monitor supports Linux and macOS only"); + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic)] +mod tests { + use super::*; + use std::fs; + use std::os::unix::process::ExitStatusExt; + use std::path::{Path, PathBuf}; + use std::process::Command; + + use rustix::process::{WaitOptions, waitpid}; + + use crate::launcher::TerminationGuard; + use crate::secret_files::open_secrets_dir; + + fn tdir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("pm-monitor-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d + } + + /// Fork a monitor watching `service_pid`, mirroring the production + /// launcher: the calling thread blocks the stop signals first (the + /// child is born with them blocked — no ready-race between fork and + /// the monitor's own block), the fork-child runs the REAL monitor + /// loop with test-scaled timing, the parent restores its mask and + /// returns the monitor's pid. + fn fork_monitor( + service_pid: Pid, + dir: Option<&Path>, + names: Vec, + grace: Duration, + poll_interval: Duration, + ) -> Pid { + let guard = TerminationGuard::block(); + let dir_fd = dir.map(|d| open_secrets_dir(d).unwrap()); + // SAFETY: fork(2) in the test process. The child executes only + // run_inner — documented async-signal-safe discipline: no + // allocation, no stdio locks, raw syscalls only — and then exits + // via _exit/exit_group, so the multithreaded test harness's + // malloc locks and output buffers are never touched in the child. + match unsafe { libc::fork() } { + -1 => panic!("fork: {}", std::io::Error::last_os_error()), + 0 => { + // Never returns (`-> !`), so the guard is never dropped + // and the mask stays blocked for the monitor's life + // (run_inner re-asserts it regardless). + run_inner(service_pid, dir_fd, names, grace, poll_interval); + } + child => { + guard.restore_mask(); + Pid::from_raw(child).unwrap() + } + } + } + + /// Reap the monitor, asserting it exits 0 within `timeout`. On + /// timeout the monitor is SIGKILLed and reaped so a regression fails + /// the test instead of hanging the suite. + fn wait_monitor_exit(pid: Pid, timeout: Duration) -> i32 { + let deadline = Instant::now() + timeout; + loop { + match waitpid(Some(pid), WaitOptions::NOHANG).unwrap() { + Some((_, status)) => { + if let Some(sig) = status.terminating_signal() { + panic!("monitor died by signal {sig}"); + } + return status.exit_status().unwrap_or(-1); + } + None => { + if Instant::now() >= deadline { + let _ = kill_process(pid, Signal::KILL); + let _ = waitpid(Some(pid), WaitOptions::empty()); + panic!("monitor did not exit within {timeout:?}"); + } + std::thread::sleep(Duration::from_millis(5)); + } + } + } + } + + fn write_dummies(dir: &Path) -> Vec { + fs::write(dir.join("A"), b"secret-a").unwrap(); + fs::write(dir.join("B"), b"secret-b").unwrap(); + vec!["A".to_string(), "B".to_string()] + } + + /// Reaps a forked/spawned pid on drop (SIGKILL first) so a failed + /// assertion can't leak a stray service process — important for the + /// TERM-ignoring service, which would otherwise outlive the test + /// binary indefinitely. + struct ReapOnDrop(Pid); + + impl Drop for ReapOnDrop { + fn drop(&mut self) { + let _ = kill_process(self.0, Signal::KILL); + let _ = waitpid(Some(self.0), WaitOptions::empty()); + } + } + + /// Fork a "service" that ignores SIGTERM until SIGKILLed: a + /// fork-child that sets TERM to SIG_IGN and pause()s forever. This + /// exercises the grace → SIGKILL escalation deterministically, unlike + /// a shell `trap` — macOS /bin/sh resets TERM for exec'd commands, + /// so the disposition doesn't survive into `sleep` there. + fn fork_term_ignoring_service() -> Pid { + // SAFETY: fork(2) in the test process; the child executes only + // async-signal-safe calls (signal(2), pause(2)) and never returns + // into the test harness — no allocation, no stdio, no locks. + match unsafe { libc::fork() } { + -1 => panic!("fork: {}", std::io::Error::last_os_error()), + 0 => unsafe { + // SAFETY: plain single-threaded signal op on this + // process; SIG_IGN is the documented ignore-disposition + // constant. pause(2) suspends until a caught signal + // arrives; TERM is ignored, so only SIGKILL ends the loop. + libc::signal(libc::SIGTERM, libc::SIG_IGN); + loop { + libc::pause(); + } + }, + child => Pid::from_raw(child).unwrap(), + } + } + + /// Service death NOT mediated by the monitor (kill -9 / crash + /// stand-in) must still trigger cleanup and monitor exit. + #[test] + fn natural_service_death_triggers_cleanup_and_monitor_exit() { + let dir = tdir("natural"); + let names = write_dummies(&dir); + let mut service = Command::new("sleep").arg("30").spawn().unwrap(); + let service_pid = Pid::from_child(&service); + let _reap = ReapOnDrop(service_pid); + let monitor = fork_monitor( + service_pid, + Some(&dir), + names, + Duration::from_millis(50), + Duration::from_millis(10), + ); + + assert!(dir.join("A").exists()); + kill_process(service_pid, Signal::KILL).unwrap(); + let status = service.wait().unwrap(); + assert_eq!(status.signal(), Some(libc::SIGKILL)); + + assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); + assert!( + !dir.join("A").exists() && !dir.join("B").exists(), + "monitor must remove the plaintext files on service death" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// A stop signal to the monitor is forwarded to the service; death + /// follows within the grace (no SIGKILL escalation needed), then + /// cleanup runs and the monitor exits 0. The monitor is born with + /// the signal blocked, so the TERM pends until its first tick — + /// no settle sleep is needed. + #[test] + fn stop_signal_is_forwarded_then_grace_then_cleanup() { + let dir = tdir("forward"); + let names = write_dummies(&dir); + let mut service = Command::new("sleep").arg("30").spawn().unwrap(); + let service_pid = Pid::from_child(&service); + let _reap = ReapOnDrop(service_pid); + let monitor = fork_monitor( + service_pid, + Some(&dir), + names, + Duration::from_millis(500), + Duration::from_millis(10), + ); + + kill_process(monitor, Signal::TERM).unwrap(); + + assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); + let status = service.wait().unwrap(); + assert_eq!( + status.signal(), + Some(libc::SIGTERM), + "the service must die by the forwarded TERM, not by an escalated SIGKILL" + ); + assert!( + !dir.join("A").exists() && !dir.join("B").exists(), + "cleanup must run before the monitor exits" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// A service that ignores SIGTERM is SIGKILLed only after the grace + /// elapses; cleanup still runs and the monitor exits 0. + #[test] + fn term_ignoring_service_is_sigkilled_after_grace() { + let dir = tdir("grace"); + let names = write_dummies(&dir); + let service_pid = fork_term_ignoring_service(); + let _reap = ReapOnDrop(service_pid); + let grace = Duration::from_millis(50); + let monitor = fork_monitor( + service_pid, + Some(&dir), + names, + grace, + Duration::from_millis(10), + ); + + let start = Instant::now(); + kill_process(monitor, Signal::TERM).unwrap(); + + assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); + let Some((_, status)) = waitpid(Some(service_pid), WaitOptions::empty()).unwrap() else { + panic!("blocking waitpid returned no status"); + }; + assert_eq!( + status.terminating_signal(), + Some(libc::SIGKILL), + "a TERM-ignoring service must be SIGKILLed" + ); + assert!( + start.elapsed() >= grace, + "SIGKILL must not come before the grace elapses" + ); + assert!( + !dir.join("A").exists() && !dir.join("B").exists(), + "cleanup must run after the SIGKILL path" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// The inherited-heap scrub (threat model): both buffers of an env + /// pair must come back fully wiped. + #[test] + fn wipe_pair_scrubs_both_buffers() { + let (k, v) = wipe_pair( + std::ffi::OsString::from("SECRET_NAME"), + std::ffi::OsString::from("s3cr3t-value"), + ); + assert!(k.iter().all(|b| *b == 0), "name buffer not wiped"); + assert!(v.iter().all(|b| *b == 0), "value buffer not wiped"); + } + + /// Uniform semantics (design decision 4): the monitor runs even in + /// env mode — no dir fd, an empty name list, cleanup a no-op — and + /// still exits when the service dies. + #[test] + fn env_mode_monitor_with_no_files_exits_on_service_death() { + let mut service = Command::new("sleep").arg("30").spawn().unwrap(); + let service_pid = Pid::from_child(&service); + let _reap = ReapOnDrop(service_pid); + let monitor = fork_monitor( + service_pid, + None, + Vec::new(), + Duration::from_millis(50), + Duration::from_millis(10), + ); + + kill_process(service_pid, Signal::TERM).unwrap(); + let status = service.wait().unwrap(); + assert_eq!(status.signal(), Some(libc::SIGTERM)); + + assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); + } +} diff --git a/tests/exec_conformance/files_mode.rs b/tests/exec_conformance/files_mode.rs index f9773aa..906fc92 100644 --- a/tests/exec_conformance/files_mode.rs +++ b/tests/exec_conformance/files_mode.rs @@ -1,4 +1,3 @@ -use std::os::unix::fs::PermissionsExt; use std::process::Command; use crate::common; @@ -34,7 +33,8 @@ fn files_mode_writes_0600_pointers_and_passthrough() { cat "$SECRET_FILE" > '{d}'/secret_contents.out && \ printf %s "${{SECRET:-UNSET}}" > '{d}'/secret_var.out && \ printf %s "$PLAIN" > '{d}'/plain.out && \ - printf %s "${{POSTMASTER_SECRETS_DIR:-UNSET}}" > '{d}'/secretsdir.out"#, + printf %s "${{POSTMASTER_SECRETS_DIR:-UNSET}}" > '{d}'/secretsdir.out && \ + find "$SECRET_FILE" -perm 600 -print | grep -q ."#, d = d.display() ); let out = run_exec(&cfg, &sh, &[]); @@ -61,8 +61,16 @@ fn files_mode_writes_0600_pointers_and_passthrough() { "UNSET" ); - let md = std::fs::metadata(secrets_dir.join("SECRET")).unwrap(); - assert_eq!(md.permissions().mode() & 0o777, 0o600); + // The 0600 check ran inside the service above (the file must be + // exactly 0600 while it exists). Once the service exits, the sibling + // monitor removes the plaintext (cleanup on every death path) — + // run_exec returning implies the monitor has already exited: it + // inherits postmaster's stdout/stderr pipe ends across the fork and + // output() only sees EOF after the monitor's cleanup has run. + assert!( + !secrets_dir.join("SECRET").exists(), + "the sibling monitor must remove plaintext files on service death" + ); } #[test] @@ -126,7 +134,7 @@ fn credentials_mode_fetch_loop() { ), ); let sh = format!( - "printf %s \"$CREDENTIALS_DIRECTORY\" > '{d}'/creddir.out && cat '{sd}'/K > '{d}'/kcontents.out", + "printf %s \"$CREDENTIALS_DIRECTORY\" > '{d}'/creddir.out && cat '{sd}'/K > '{d}'/kcontents.out && find '{sd}/K' -perm 600 -print | grep -q .", d = d.display(), sd = secrets_dir.display() ); @@ -142,6 +150,11 @@ fn credentials_mode_fetch_loop() { secrets_dir.display().to_string() ); assert_eq!(std::fs::read(d.join("kcontents.out")).unwrap(), b"s3cret"); - let md = std::fs::metadata(secrets_dir.join("K")).unwrap(); - assert_eq!(md.permissions().mode() & 0o777, 0o600); + // The 0600 check ran inside the service above; after the service + // exits the sibling monitor removes the plaintext (see the files-mode + // test for why run_exec returning implies the monitor has exited). + assert!( + !secrets_dir.join("K").exists(), + "the sibling monitor must remove plaintext files on service death" + ); } From 7be71fea529d58fd5edc658362f26b8b0badc5be Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Thu, 6 Aug 2026 12:15:28 -0500 Subject: [PATCH 15/47] test: serialize env-mutating tests on one process-wide ENV_LOCK Three separate disciplines raced: module-local ENV_LOCK statics in keys/source.rs and keys/provisioning/mod.rs, and no lock at all in keys/env.rs. Module-local locks do not exclude each other, so two env-mutating tests still raced (~1 in 5 baseline runs); the loser's panic poisoned a mutex and failed unrelated key_source tests. - new src/test_util.rs (cfg(test)) with the single process-wide crate::test_util::ENV_LOCK; both module-local statics deleted - every env-mutating test now holds it for the mutation's full scope, including keys/env.rs's previously-unlocked from_env test - provisioning skip-guard now covers only ambient runner env; a concurrent test can no longer be the source - unsafe-code docs: test-env-mutation.md rewritten to the process-wide discipline; index rationale line corrected (plaintext custody is minimized by design; unsafe code is where that can silently break) Verified: fmt, clippy x3 (dev/release/x86_64-linux-gnu), 87 lib + 7 exec_check + 16 conformance, deny, audit --deny, mdbook; 15/15 clean lib-suite runs as the flake shake. --- docs/src/unsafe-code/index.md | 2 +- docs/src/unsafe-code/test-env-mutation.md | 30 ++++++++++++----------- src/keys/env.rs | 17 +++++++------ src/keys/provisioning/mod.rs | 21 ++++++++-------- src/keys/source.rs | 24 +++++++----------- src/lib.rs | 2 ++ src/test_util.rs | 15 ++++++++++++ 7 files changed, 63 insertions(+), 48 deletions(-) create mode 100644 src/test_util.rs diff --git a/docs/src/unsafe-code/index.md b/docs/src/unsafe-code/index.md index ebdc23b..4e4d019 100644 --- a/docs/src/unsafe-code/index.md +++ b/docs/src/unsafe-code/index.md @@ -43,4 +43,4 @@ Note what is NOT in the inventory: `mlockall`, `setrlimit(Core, 0)`, and 6. **Write tests** — verify the mitigations work (or document why untestable) 7. **Get review** — unsafe requires explicit approval -The bar is intentionally high. Postmaster handles plaintext secrets. +The bar is intentionally high. Postmaster's design keeps plaintext custody to microseconds — decrypt at the last instant, zeroize immediately, never persist. A memory-safety bug is one of the few things that can silently break that invariant. diff --git a/docs/src/unsafe-code/test-env-mutation.md b/docs/src/unsafe-code/test-env-mutation.md index 2d61bca..aec22b3 100644 --- a/docs/src/unsafe-code/test-env-mutation.md +++ b/docs/src/unsafe-code/test-env-mutation.md @@ -3,8 +3,10 @@ ## Location ``` +src/test_util.rs — the shared ENV_LOCK itself src/keys/source.rs (test module) — 4 sites -src/keys/env.rs (test module) — 2 sites +src/keys/env.rs (test module) — 1 test, 2 set/remove pairs +src/keys/provisioning/mod.rs (test module) — 1 test, 2 set/remove pairs + a full vars() scan ``` ## Purpose @@ -19,23 +21,23 @@ Several key-source tests must set or clear `DOTENV_PRIVATE_KEY*` / | Vector | Description | Mitigation | |--------|-------------|------------| -| Concurrent env access | Two tests mutating/reading env at once | Every call site holds a module-level `ENV_LOCK` mutex for the mutation's full scope | -| Lock-ordering | Multiple env-mutating tests in one binary | Single mutex per module; no nested acquisition | +| Concurrent env access | Two tests mutating/reading env at once | Every call site holds the single process-wide `ENV_LOCK` (`crate::test_util`) for the mutation's full scope | +| Lock-ordering | Multiple env-mutating tests in one binary | One shared mutex for the whole test binary; no nested acquisition | Each site carries a SAFETY comment naming the serialization discipline. -## Known Gap (tracked) +## Why one process-wide lock -The discipline is currently **per-module, not per-process**: -`keys/source.rs` and `keys/env.rs` (and `keys/mod.rs`'s tests) use -*separate* `ENV_LOCK` statics, and -`keys::tests::from_env_loads_and_fails_closed` mutates env without -holding any lock. Two such tests can still race — the loser may poison a -mutex and fail unrelated tests (~1 in 5 baseline runs observed). The -fix is one shared lock for every env-mutating test; it is tracked on the -project board and deliberately not smuggled into unrelated changes. +The discipline was previously **per-module**: `keys/source.rs` and +`keys/provisioning/mod.rs` each had their own `ENV_LOCK` static, and +`keys/env.rs`'s `from_env_loads_and_fails_closed` mutated env holding no +lock at all. Module-local locks do not exclude each other, so two such +tests still raced — the loser's panic poisoned a mutex and failed +unrelated tests (~1 in 5 baseline runs, observed 2026-08-04). Since +2026-08-06 every env-mutating test in every module acquires the single +`crate::test_util::ENV_LOCK`; any new env-touching test must do the same. ## Tests -These sites exist *in* tests; the flaky-race card above doubles as their -correctness tracking. +These sites exist *in* tests; the shared-lock discipline is their +correctness property, exercised by every suite run. diff --git a/src/keys/env.rs b/src/keys/env.rs index 547d955..67ee3a9 100644 --- a/src/keys/env.rs +++ b/src/keys/env.rs @@ -32,6 +32,7 @@ pub(super) fn from_env(naming: KeyNaming) -> Result { #[allow(clippy::unwrap_used, clippy::panic, unused_qualifications)] mod tests { use super::*; + use crate::test_util::ENV_LOCK; #[test] fn is_key_var_name_rules() { @@ -50,17 +51,19 @@ mod tests { fn from_env_loads_and_fails_closed() { // from_env reads ALL DOTENV_PRIVATE_KEY* vars from the process // environment and delegates to from_pairs. This is a single test - // (not two) because env mutation is global and tests run in - // parallel — two tests mutating DOTENV_PRIVATE_KEY* simultaneously - // would race. Using a unique suffix to avoid collision with any - // ambient vars in the test runner. + // (not two) because env mutation is global; the shared ENV_LOCK + // serializes it against every other env-mutating test. Using a + // unique suffix to avoid collision with any ambient vars in the + // test runner. + // + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. + let _guard = ENV_LOCK.lock().unwrap(); let var_name = "DOTENV_PRIVATE_KEY_TESTFROMENV"; let key_hex = "aa".repeat(32); // Positive path: set a valid key, from_env succeeds. - // SAFETY: set_var/remove_var are unsafe on edition 2024 (not - // thread-safe). This test does not spawn threads and the var name - // is unique, so no concurrent test mutates the same var. unsafe { std::env::set_var(var_name, &key_hex); } diff --git a/src/keys/provisioning/mod.rs b/src/keys/provisioning/mod.rs index d8d72ee..77a873a 100644 --- a/src/keys/provisioning/mod.rs +++ b/src/keys/provisioning/mod.rs @@ -408,11 +408,7 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> #[allow(clippy::unwrap_used, clippy::panic)] mod tests { use super::*; - - /// Serializes tests that mutate process-global env vars (same - /// pattern as `keys::source::tests::ENV_LOCK`): the test harness - /// runs tests in parallel threads of one process. - static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + use crate::test_util::ENV_LOCK; fn env_only_cfg() -> ExecConfig { serde_json::from_str(r#"{"mode":"env","keys":["environment"],"env_files":["/x/.env"]}"#) @@ -431,10 +427,11 @@ mod tests { let valid = "DOTENV_PRIVATE_KEY_PMVERIFY"; // Positive leg: an exact `PREFIX_` var passes. Robust - // against any other valid vars a concurrent test may have set. + // against any valid key vars ambient in the test runner's own + // environment. // SAFETY: set_var/remove_var are unsafe on edition 2024 (not - // thread-safe). Serialized within this module via ENV_LOCK; the - // var names are unique to this test. + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. unsafe { std::env::set_var(valid, "aa".repeat(32)); } @@ -452,9 +449,11 @@ mod tests { unsafe { std::env::remove_var(bogus); } - // env.rs's from_env test holds a valid DOTENV_PRIVATE_KEY_* var - // for a microsecond window; if any valid key var was present, - // the negative leg is not observable — skip rather than flake. + // Guard against an ambient valid key var in the test runner's + // own environment (e.g. DOTENV_PRIVATE_KEY exported in CI): if + // one is present, the negative leg is not observable — skip + // rather than flake. A concurrent test cannot be the source: + // every env-mutating test holds the shared ENV_LOCK. let any_valid = std::env::vars().any(|(k, _)| { crate::keys::is_key_var_name(KeyNaming::Env.key_prefix(), &k) || crate::keys::is_key_var_name(KeyNaming::Bundle.key_prefix(), &k) diff --git a/src/keys/source.rs b/src/keys/source.rs index 8555975..3195423 100644 --- a/src/keys/source.rs +++ b/src/keys/source.rs @@ -79,13 +79,7 @@ pub fn load_ring(specs: &[KeySourceSpec], wanted_vars: &[String]) -> Result = std::sync::Mutex::new(()); + use crate::test_util::ENV_LOCK; #[test] fn load_ring_credential_is_skippable() { @@ -96,8 +90,8 @@ mod tests { // source, not from the credential source. // // SAFETY: set_var/remove_var are unsafe on edition 2024 (not - // thread-safe). Serialized via ENV_LOCK against the other - // CREDENTIALS_DIRECTORY-mutating tests in this module. + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. let _guard = ENV_LOCK.lock().unwrap(); unsafe { std::env::remove_var("CREDENTIALS_DIRECTORY"); @@ -132,8 +126,8 @@ mod tests { std::os::unix::fs::symlink(&real, &link).unwrap(); // SAFETY: set_var/remove_var are unsafe on edition 2024 (not - // thread-safe). Serialized via ENV_LOCK against the other - // CREDENTIALS_DIRECTORY-mutating tests in this module. + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. let _guard = ENV_LOCK.lock().unwrap(); unsafe { std::env::set_var("CREDENTIALS_DIRECTORY", &cred_dir); @@ -162,8 +156,8 @@ mod tests { fs::create_dir_all(&sub).unwrap(); // SAFETY: set_var/remove_var are unsafe on edition 2024 (not - // thread-safe). Serialized via ENV_LOCK against the other - // CREDENTIALS_DIRECTORY-mutating tests in this module. + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. let _guard = ENV_LOCK.lock().unwrap(); unsafe { std::env::set_var("CREDENTIALS_DIRECTORY", &cred_dir); @@ -223,8 +217,8 @@ mod tests { // source" fallback message. // // SAFETY: set_var/remove_var are unsafe on edition 2024 (not - // thread-safe). Serialized via ENV_LOCK against the other - // CREDENTIALS_DIRECTORY-mutating tests in this module. + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. let _guard = ENV_LOCK.lock().unwrap(); let var_name = "DOTENV_PRIVATE_KEY_TESTTERMINAL"; unsafe { diff --git a/src/lib.rs b/src/lib.rs index 6ae9304..d2310c6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -24,6 +24,8 @@ pub(crate) mod monitor; pub mod ramdisk; pub mod secret_files; pub mod server; +#[cfg(test)] +pub(crate) mod test_util; /// The bundle adapter, re-exported so `crate::bundle` keeps resolving. pub use adapter::bundle; diff --git a/src/test_util.rs b/src/test_util.rs new file mode 100644 index 0000000..c07c015 --- /dev/null +++ b/src/test_util.rs @@ -0,0 +1,15 @@ +//! Test-only shared utilities (compiled under `#[cfg(test)]` only). + +/// Process-wide lock serializing every unit test that mutates — or +/// wholesale snapshots — the process-global environment. The test +/// harness runs tests in parallel threads of one process, so +/// unsynchronized `set_var`/`remove_var`, or a full `vars()` scan +/// racing another test's mutation, is a data race; edition 2024 marks +/// those calls `unsafe`. +/// +/// ALL env-touching tests in every module hold this ONE lock for the +/// mutation's full scope. Module-local locks do not exclude each other: +/// separate per-module statics raced, and the loser's panic poisoned a +/// mutex, failing unrelated tests (~1 in 5 baseline runs, observed +/// 2026-08-04). +pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); From e1f1c214d9ef93fce3a167653c99234600e8090a Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Thu, 6 Aug 2026 12:16:08 -0500 Subject: [PATCH 16/47] fix: admit config-required key namings into the key ring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit load_ring hardcoded KeyNaming::Env at every source leg, so POSTMASTER_KEY* material was dropped (zeroized) at parse time and every bundle_files config failed at exec with "key ring has no POSTMASTER_KEY entry", while setup --recheck accepted either prefix and reported OK. Unit/conformance tests never saw it: they build rings directly, bypassing load_ring. - ExecConfig::required_namings() derives the adapter set from the config (env_files -> Env, bundle_files -> Bundle, both -> both) - from_pairs/load/from_env/from_keychain/load_ring take &[KeyNaming] and admit exactly the required prefixes; unrequired material is dropped+zeroized at parse even when the source offers it - verify_key_sources environment leg now requires EVERY required naming present (was: either prefix) — kills the setup-OK/exec-fails lie in both directions - daemon keeps [Env] with a documenting comment; bundle is not in the fetch contract (conscious exclusion) - regression coverage at the broken seam: load_ring unit tests (admits-bundle-when-required, excludes-unrequired), from_pairs and from_env multi-naming tests, per-naming verify tests, and two end-to-end conformance tests driving the real binary (bundle-only and mixed env+bundle) in tests/exec_conformance/bundle.rs Verified: fmt, clippy x3 (dev/release/x86_64-linux-gnu), 92 lib + 7 exec_check + 18 conformance, deny, audit --deny, mdbook; 10/10 full-suite flake shake. --- src/exec_config.rs | 17 +++++ src/keys/env.rs | 49 ++++++++++-- src/keys/keychain.rs | 4 +- src/keys/load.rs | 16 ++-- src/keys/mod.rs | 102 ++++++++++++++++++++----- src/keys/provisioning/mod.rs | 115 ++++++++++++++++++++++++---- src/keys/source.rs | 87 ++++++++++++++++++--- src/launcher.rs | 2 +- src/server.rs | 5 +- tests/exec_conformance/bundle.rs | 126 ++++++++++++++++++++++++++++++- tests/exec_conformance/main.rs | 2 +- 11 files changed, 455 insertions(+), 70 deletions(-) diff --git a/src/exec_config.rs b/src/exec_config.rs index 4f53ed7..bd2ecc3 100644 --- a/src/exec_config.rs +++ b/src/exec_config.rs @@ -100,6 +100,23 @@ impl ExecConfig { validate_mode_required_fields(self)?; Ok(()) } + + /// The key-naming conventions this config's artifacts require: + /// `Env` when `env_files` are present, `Bundle` when `bundle_files` + /// are present (both when both are). `load_ring` admits exactly these + /// namings into the key ring — no more (least privilege on key + /// material), no less (a bundle config must actually see + /// `POSTMASTER_KEY`). + pub fn required_namings(&self) -> Vec { + let mut namings = Vec::with_capacity(2); + if !self.env_files.is_empty() { + namings.push(KeyNaming::Env); + } + if !self.bundle_files.is_empty() { + namings.push(KeyNaming::Bundle); + } + namings + } } fn validate_mode_required_fields(cfg: &ExecConfig) -> Result<(), String> { diff --git a/src/keys/env.rs b/src/keys/env.rs index 67ee3a9..f198b5e 100644 --- a/src/keys/env.rs +++ b/src/keys/env.rs @@ -17,13 +17,12 @@ pub(crate) fn is_key_var_name(prefix: &str, name: &str) -> bool { /// Implementation of [`KeyRing::from_env`]; the contract is documented on /// the method. -pub(super) fn from_env(naming: KeyNaming) -> Result { - let prefix = naming.key_prefix(); +pub(super) fn from_env(namings: &[KeyNaming]) -> Result { KeyRing::from_pairs( std::env::vars() - .filter(|(k, _)| is_key_var_name(prefix, k)) + .filter(|(k, _)| namings.iter().any(|n| is_key_var_name(n.key_prefix(), k))) .map(|(k, v)| (k, Zeroizing::new(v))), - naming, + namings, ) .map_err(|e| format!("environment: {e}")) } @@ -67,7 +66,7 @@ mod tests { unsafe { std::env::set_var(var_name, &key_hex); } - let ring = KeyRing::from_env(KeyNaming::Env); + let ring = KeyRing::from_env(&[KeyNaming::Env]); unsafe { std::env::remove_var(var_name); } @@ -84,7 +83,7 @@ mod tests { unsafe { std::env::set_var(var_name, "not-valid-hex-at-all"); } - let err = KeyRing::from_env(KeyNaming::Env); + let err = KeyRing::from_env(&[KeyNaming::Env]); unsafe { std::env::remove_var(var_name); } @@ -102,9 +101,45 @@ mod tests { "NOT_A_DOTENV_KEY".to_string(), Zeroizing::new("x".to_string()) )], - KeyNaming::Env, + &[KeyNaming::Env], ) .is_err() ); } + + #[test] + fn from_env_admits_only_the_required_namings() { + // The bundle-ring gap fix: with Bundle required, POSTMASTER_KEY + // enters the ring; when it is not required, the same variable is + // NOT admitted (least privilege). + // + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. + let _guard = ENV_LOCK.lock().unwrap(); + let dotenv_var = "DOTENV_PRIVATE_KEY_TESTNAMINGS"; + let bundle_var = "POSTMASTER_KEY_TESTNAMINGS"; + let key_hex = "aa".repeat(32); + unsafe { + std::env::set_var(dotenv_var, &key_hex); + std::env::set_var(bundle_var, &key_hex); + } + let both = KeyRing::from_env(&[KeyNaming::Env, KeyNaming::Bundle]); + let bundle_only = KeyRing::from_env(&[KeyNaming::Bundle]); + unsafe { + std::env::remove_var(dotenv_var); + std::env::remove_var(bundle_var); + } + + let both = both.expect("both namings required should load"); + assert!(both.candidates(dotenv_var).is_some()); + assert!(both.candidates(bundle_var).is_some()); + + let bundle_only = bundle_only.expect("bundle naming alone should load"); + assert!( + bundle_only.candidates(dotenv_var).is_none(), + "an unrequired naming must not enter the ring" + ); + assert!(bundle_only.candidates(bundle_var).is_some()); + } } diff --git a/src/keys/keychain.rs b/src/keys/keychain.rs index 048408e..64892c2 100644 --- a/src/keys/keychain.rs +++ b/src/keys/keychain.rs @@ -11,7 +11,7 @@ use crate::adapter::KeyNaming; pub(super) fn from_keychain( service: &str, vars: &[String], - naming: KeyNaming, + namings: &[KeyNaming], ) -> Result { // Reads go through the Security.framework API, not the // /usr/bin/security CLI (F1 direction): no subprocess, no argv, @@ -31,5 +31,5 @@ pub(super) fn from_keychain( // no separate trim is needed here. pairs.push((var.clone(), Zeroizing::new(s.to_string()))); } - KeyRing::from_pairs(pairs, naming).map_err(|e| format!("keychain {service}: {e}")) + KeyRing::from_pairs(pairs, namings).map_err(|e| format!("keychain {service}: {e}")) } diff --git a/src/keys/load.rs b/src/keys/load.rs index 9a59893..63c6d57 100644 --- a/src/keys/load.rs +++ b/src/keys/load.rs @@ -9,7 +9,7 @@ use crate::adapter::KeyNaming; /// Implementation of [`KeyRing::load`]; the contract is documented on the /// method. -pub(super) fn load(path: &Path, naming: KeyNaming) -> Result { +pub(super) fn load(path: &Path, namings: &[KeyNaming]) -> Result { let oflags = rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC; let fd = rustix::fs::open(path, oflags, rustix::fs::Mode::empty()).map_err(|e| { @@ -44,7 +44,7 @@ pub(super) fn load(path: &Path, naming: KeyNaming) -> Result { let (k, v) = item.map_err(|e| format!("keys file {}: {e}", path.display()))?; pairs.push((k, Zeroizing::new(v))); } - KeyRing::from_pairs(pairs, naming).map_err(|e| format!("keys file {}: {e}", path.display())) + KeyRing::from_pairs(pairs, namings).map_err(|e| format!("keys file {}: {e}", path.display())) } #[cfg(test)] @@ -57,7 +57,7 @@ mod tests { #[test] fn load_rejects_bad_hex() { let content = "DOTENV_PRIVATE_KEY=not-hex\n"; - with_temp_keys(content, |p| match KeyRing::load(p, KeyNaming::Env) { + with_temp_keys(content, |p| match KeyRing::load(p, &[KeyNaming::Env]) { Err(e) if e.contains("not valid hex") => {} other => panic!("expected bad hex error, got {other:?}"), }); @@ -78,7 +78,7 @@ mod tests { } // 0644: world-readable — must be rejected. std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); - match KeyRing::load(&path, KeyNaming::Env) { + match KeyRing::load(&path, &[KeyNaming::Env]) { Err(e) if e.contains("group/world accessible") => {} other => panic!("expected group/world permission error, got {other:?}"), } @@ -100,7 +100,7 @@ mod tests { } // 0640: group-readable — must be rejected. std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap(); - match KeyRing::load(&path, KeyNaming::Env) { + match KeyRing::load(&path, &[KeyNaming::Env]) { Err(e) if e.contains("group/world accessible") => {} other => panic!("expected group permission error, got {other:?}"), } @@ -116,7 +116,7 @@ mod tests { std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o600)).unwrap(); let link = dir.join(".env.keys"); std::os::unix::fs::symlink(&real, &link).unwrap(); - match KeyRing::load(&link, KeyNaming::Env) { + match KeyRing::load(&link, &[KeyNaming::Env]) { Err(e) if e.contains("symlink") => {} other => panic!("expected symlink rejection error, got {other:?}"), } @@ -129,7 +129,7 @@ mod tests { // permission and ownership checks. let content = format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32)); with_temp_keys(&content, |p| { - KeyRing::load(p, KeyNaming::Env).expect("0600 keys file owned by euid should load"); + KeyRing::load(p, &[KeyNaming::Env]).expect("0600 keys file owned by euid should load"); }); } @@ -148,7 +148,7 @@ mod tests { } // 0400: read-only by owner — stricter than 0600, must pass. std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400)).unwrap(); - KeyRing::load(&path, KeyNaming::Env).expect("0400 keys file owned by euid should load"); + KeyRing::load(&path, &[KeyNaming::Env]).expect("0400 keys file owned by euid should load"); let _ = std::fs::remove_file(&path); } } diff --git a/src/keys/mod.rs b/src/keys/mod.rs index c446170..b86be33 100644 --- a/src/keys/mod.rs +++ b/src/keys/mod.rs @@ -56,24 +56,28 @@ impl KeyRing { /// file accidentally `chmod 0644` would expose private keys to every /// process on the host; fail closed instead. /// - `st_uid == euid`: the file must be owned by the service user. - pub fn load(path: &Path, naming: KeyNaming) -> Result { - load::load(path, naming) + /// + /// `namings` is the required adapter set; entries under other + /// prefixes are dropped (and zeroized) at parse time. + pub fn load(path: &Path, namings: &[KeyNaming]) -> Result { + load::load(path, namings) } - /// Core parser shared by every key source: keep keys matching the - /// adapter's key prefix, split comma-separated rotation candidates, - /// hex-decode to 32-byte zeroized keys. Empty result is an error - /// (fail closed). Takes `Zeroizing` values so callers never - /// hand key material as a plain heap String that drops without - /// zeroization. + /// Core parser shared by every key source: keep keys matching any of + /// the required adapters' key prefixes, split comma-separated rotation + /// candidates, hex-decode to 32-byte zeroized keys. Empty result is an + /// error (fail closed). Takes `Zeroizing` values so callers + /// never hand key material as a plain heap String that drops without + /// zeroization. `namings` is the set the config's artifacts require + /// (see `ExecConfig::required_namings`) — the ring admits exactly + /// those prefixes, no more (least privilege on key material). pub fn from_pairs( pairs: impl IntoIterator)>, - naming: KeyNaming, + namings: &[KeyNaming], ) -> Result { - let prefix = naming.key_prefix(); let mut map: HashMap>> = HashMap::new(); for (name, mut value) in pairs { - if !name.starts_with(prefix) { + if !namings.iter().any(|n| name.starts_with(n.key_prefix())) { value.zeroize(); continue; } @@ -101,16 +105,16 @@ impl KeyRing { map.insert(name, keys); } if map.is_empty() { - return Err(naming.empty_error()); + return Err(empty_error(namings)); } Ok(KeyRing(map)) } /// Private key variables from the process environment (external /// provisioning; `key.file = null` in the module). Reads all - /// variables matching the adapter's key prefix. - pub fn from_env(naming: KeyNaming) -> Result { - env::from_env(naming) + /// variables matching any required adapter's key prefix. + pub fn from_env(namings: &[KeyNaming]) -> Result { + env::from_env(namings) } /// macOS System keychain: one generic-password item per variable, @@ -121,9 +125,25 @@ impl KeyRing { pub fn from_keychain( service: &str, vars: &[String], - naming: KeyNaming, + namings: &[KeyNaming], ) -> Result { - keychain::from_keychain(service, vars, naming) + keychain::from_keychain(service, vars, namings) + } +} + +/// Human-readable empty-ring error for a naming set: a single naming +/// keeps its adapter-specific message; multiple namings join them. +fn empty_error(namings: &[KeyNaming]) -> String { + match namings { + [] => "no key material admitted (empty naming set)".to_string(), + [single] => single.empty_error(), + many => format!( + "no {}", + many.iter() + .map(|n| n.empty_error().trim_start_matches("no ").to_string()) + .collect::>() + .join(" or ") + ), } } @@ -352,7 +372,7 @@ pub mod tests { "POSTMASTER_KEY".to_string(), Zeroizing::new(TEST_SK_HEX.to_string()), )]; - KeyRing::from_pairs(pairs, KeyNaming::Bundle).unwrap() + KeyRing::from_pairs(pairs, &[KeyNaming::Bundle]).unwrap() } use std::io::Write; use std::path::Path; @@ -444,19 +464,61 @@ pub mod tests { Zeroizing::new(format!("{},{}", "22".repeat(32), "33".repeat(32))), ), ], - KeyNaming::Env, + &[KeyNaming::Env], ) .unwrap(); assert_eq!(ring.0.len(), 1); assert_eq!(ring.0["DOTENV_PRIVATE_KEY_PRODUCTION"].len(), 2); } + #[test] + fn from_pairs_admits_exactly_the_required_namings() { + // The bundle-ring gap fix: a config requiring both adapters must + // get both prefix families in the ring, and nothing else. + let pairs = || { + [ + ( + "DOTENV_PRIVATE_KEY".to_string(), + Zeroizing::new("22".repeat(32)), + ), + ( + "POSTMASTER_KEY".to_string(), + Zeroizing::new("33".repeat(32)), + ), + ("UNRELATED".to_string(), Zeroizing::new("44".repeat(32))), + ] + }; + + let both = KeyRing::from_pairs(pairs(), &[KeyNaming::Env, KeyNaming::Bundle]).unwrap(); + assert!(both.candidates("DOTENV_PRIVATE_KEY").is_some()); + assert!(both.candidates("POSTMASTER_KEY").is_some()); + assert_eq!(both.0.len(), 2, "UNRELATED must be dropped"); + + // Least privilege: a naming the config does not require is NOT + // admitted, even when the source provides it. + let env_only = KeyRing::from_pairs(pairs(), &[KeyNaming::Env]).unwrap(); + assert!(env_only.candidates("DOTENV_PRIVATE_KEY").is_some()); + assert!(env_only.candidates("POSTMASTER_KEY").is_none()); + + // A bundle-only requirement with only Env material present fails + // closed with the adapter's own empty message. + let err = KeyRing::from_pairs( + [( + "DOTENV_PRIVATE_KEY".to_string(), + Zeroizing::new("22".repeat(32)), + )], + &[KeyNaming::Bundle], + ) + .unwrap_err(); + assert_eq!(err, KeyNaming::Bundle.empty_error()); + } + #[test] fn from_pairs_empty_is_error() { assert!( KeyRing::from_pairs( [("A".to_string(), Zeroizing::new("b".to_string()))], - KeyNaming::Env + &[KeyNaming::Env] ) .is_err() ); diff --git a/src/keys/provisioning/mod.rs b/src/keys/provisioning/mod.rs index 77a873a..de31284 100644 --- a/src/keys/provisioning/mod.rs +++ b/src/keys/provisioning/mod.rs @@ -8,7 +8,6 @@ use std::fs; use std::io::Read; use std::path::{Path, PathBuf}; -use crate::adapter::KeyNaming; use crate::exec_config::{ExecConfig, KeySourceSpec}; use crate::server::log; @@ -373,21 +372,21 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> } KeySourceSpec::Environment => { checked += 1; - let env_prefix = KeyNaming::Env.key_prefix(); - let bundle_prefix = KeyNaming::Bundle.key_prefix(); + // Every naming the config's artifacts require must be + // present: accepting ANY single prefix let `POSTMASTER_KEY` + // satisfy verification for an env-files-only config (setup + // said OK, exec then failed) — and vice versa. + // // The SAME predicate KeyRing::from_env applies (audit // 2026-08-02 A16): a bare starts_with would count a // prefix-substring collision like DOTENV_PRIVATE_KEYFOO // as key material that from_env then refuses to load — // verification must not pass what resolution rejects. - let has_key = std::env::vars().any(|(k, _)| { - crate::keys::is_key_var_name(env_prefix, &k) - || crate::keys::is_key_var_name(bundle_prefix, &k) - }); - if !has_key { - return Err(format!( - "environment: no {env_prefix}* or {bundle_prefix}* variables set" - )); + for naming in cfg.required_namings() { + let prefix = naming.key_prefix(); + if !std::env::vars().any(|(k, _)| crate::keys::is_key_var_name(prefix, &k)) { + return Err(format!("environment: no {prefix}* variables set")); + } } found += 1; } @@ -408,6 +407,7 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> #[allow(clippy::unwrap_used, clippy::panic)] mod tests { use super::*; + use crate::adapter::KeyNaming; use crate::test_util::ENV_LOCK; fn env_only_cfg() -> ExecConfig { @@ -453,14 +453,97 @@ mod tests { // own environment (e.g. DOTENV_PRIVATE_KEY exported in CI): if // one is present, the negative leg is not observable — skip // rather than flake. A concurrent test cannot be the source: - // every env-mutating test holds the shared ENV_LOCK. - let any_valid = std::env::vars().any(|(k, _)| { - crate::keys::is_key_var_name(KeyNaming::Env.key_prefix(), &k) - || crate::keys::is_key_var_name(KeyNaming::Bundle.key_prefix(), &k) - }); + // every env-mutating test holds the shared ENV_LOCK. Only the + // Env prefix counts here: this config requires Env naming alone. + let any_valid = std::env::vars() + .any(|(k, _)| crate::keys::is_key_var_name(KeyNaming::Env.key_prefix(), &k)); if !any_valid { let err = res.expect_err("a prefix-substring variable must fail verification"); assert!(err.contains("environment:"), "{err}"); } } + + fn bundle_only_cfg() -> ExecConfig { + serde_json::from_str( + r#"{"mode":"env","keys":["environment"],"bundle_files":["/x/s.json"]}"#, + ) + .unwrap() + } + + fn mixed_cfg() -> ExecConfig { + serde_json::from_str( + r#"{"mode":"env","keys":["environment"],"env_files":["/x/.env"],"bundle_files":["/x/s.json"]}"#, + ) + .unwrap() + } + + /// True when a valid key var for `prefix` exists that this test did + /// NOT set itself (i.e. ambient in the runner's own environment). + fn ambient_key_var(prefix: &str, mine: &[&str]) -> bool { + std::env::vars() + .any(|(k, _)| !mine.contains(&k.as_str()) && crate::keys::is_key_var_name(prefix, &k)) + } + + #[test] + fn verify_key_sources_requires_each_required_naming() { + // The compounding half of the bundle-ring gap: verification used + // to accept EITHER prefix for the environment source, so an + // env-files-only config passed with only POSTMASTER_KEY present + // (then failed at exec), and a bundle-only config failed despite + // its POSTMASTER_KEY being right there. Every required naming + // must now be present. + // + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. + let _guard = ENV_LOCK.lock().unwrap(); + let dotenv = "DOTENV_PRIVATE_KEY_PMREQUIRED"; + let bundle = "POSTMASTER_KEY_PMREQUIRED"; + let key_hex = "aa".repeat(32); + unsafe { + std::env::remove_var(dotenv); + std::env::remove_var(bundle); + } + + // bundle-only config + its POSTMASTER_KEY present → passes. + unsafe { + std::env::set_var(bundle, &key_hex); + } + assert!( + verify_key_sources(&bundle_only_cfg(), &[]).is_ok(), + "a bundle config's own POSTMASTER_KEY must satisfy verification" + ); + + // env-only config + only bundle material → fails (the old lie). + let res = verify_key_sources(&env_only_cfg(), &[]); + if !ambient_key_var(KeyNaming::Env.key_prefix(), &[dotenv, bundle]) { + let err = res.expect_err("POSTMASTER_KEY must not satisfy an env-only config"); + assert!(err.contains("DOTENV_PRIVATE_KEY"), "{err}"); + } + + // mixed config with only ONE of the two required namings → fails. + unsafe { + std::env::remove_var(bundle); + std::env::set_var(dotenv, &key_hex); + } + let res = verify_key_sources(&mixed_cfg(), &[]); + if !ambient_key_var(KeyNaming::Bundle.key_prefix(), &[dotenv, bundle]) { + let err = res.expect_err("a mixed config requires POSTMASTER_KEY too"); + assert!(err.contains("POSTMASTER_KEY"), "{err}"); + } + + // mixed config with both required namings present → passes. + unsafe { + std::env::set_var(bundle, &key_hex); + } + assert!( + verify_key_sources(&mixed_cfg(), &[]).is_ok(), + "both required namings present must pass" + ); + + unsafe { + std::env::remove_var(dotenv); + std::env::remove_var(bundle); + } + } } diff --git a/src/keys/source.rs b/src/keys/source.rs index 3195423..e2dc16f 100644 --- a/src/keys/source.rs +++ b/src/keys/source.rs @@ -15,11 +15,20 @@ use crate::keys::KeyRing; /// Ordered key-source selection. `credential` is skippable (no /// $CREDENTIALS_DIRECTORY or file absent ⇒ try next source); every other /// source is terminal: once selected, its failure fails the launcher. +/// +/// `namings` is the adapter set the config's artifacts require +/// (`ExecConfig::required_namings`): the ring admits exactly those key +/// prefixes. Hardcoding a single naming here previously dropped +/// `POSTMASTER_KEY*` at parse time and broke bundle configs end-to-end. // `wanted_vars` is only consumed by the macOS keychain source; on other // targets the parameter is unused, so silence that leg's clippy warning // without touching the signature or source-selection semantics. #[cfg_attr(not(target_os = "macos"), allow(unused_variables))] -pub fn load_ring(specs: &[KeySourceSpec], wanted_vars: &[String]) -> Result { +pub fn load_ring( + specs: &[KeySourceSpec], + wanted_vars: &[String], + namings: &[KeyNaming], +) -> Result { for spec in specs { match spec { KeySourceSpec::Credential(name) => { @@ -39,7 +48,7 @@ pub fn load_ring(specs: &[KeySourceSpec], wanted_vars: &[String]) -> Result return KeyRing::load(&p, KeyNaming::Env), + Ok(md) if md.is_file() => return KeyRing::load(&p, namings), Ok(_) => { return Err(format!( "{}: credential source is not a regular file", @@ -58,17 +67,17 @@ pub fn load_ring(specs: &[KeySourceSpec], wanted_vars: &[String]) -> Result { #[cfg(target_os = "macos")] - return KeyRing::from_keychain(service, wanted_vars, KeyNaming::Env); + return KeyRing::from_keychain(service, wanted_vars, namings); #[cfg(not(target_os = "macos"))] return Err(format!( "key source keychain({service}) is only available on macOS" )); } - KeySourceSpec::Environment => return KeyRing::from_env(KeyNaming::Env), + KeySourceSpec::Environment => return KeyRing::from_env(namings), } } Err("no usable key source (configure keys=[…] or set DOTENV_PRIVATE_KEY*)".into()) @@ -100,7 +109,7 @@ mod tests { KeySourceSpec::Credential("nonexistent".to_string()), KeySourceSpec::Environment, ]; - let err = load_ring(&specs, &[]).unwrap_err(); + let err = load_ring(&specs, &[], &[KeyNaming::Env]).unwrap_err(); // The error should come from the environment source (terminal), // proving credential fell through rather than erroring. assert!( @@ -133,7 +142,7 @@ mod tests { std::env::set_var("CREDENTIALS_DIRECTORY", &cred_dir); } let specs = vec![KeySourceSpec::Credential("dotenv-private-key".to_string())]; - let err = load_ring(&specs, &[]).unwrap_err(); + let err = load_ring(&specs, &[], &[KeyNaming::Env]).unwrap_err(); unsafe { std::env::remove_var("CREDENTIALS_DIRECTORY"); } @@ -163,7 +172,7 @@ mod tests { std::env::set_var("CREDENTIALS_DIRECTORY", &cred_dir); } let specs = vec![KeySourceSpec::Credential("subdir".to_string())]; - let err = load_ring(&specs, &[]).unwrap_err(); + let err = load_ring(&specs, &[], &[KeyNaming::Env]).unwrap_err(); unsafe { std::env::remove_var("CREDENTIALS_DIRECTORY"); } @@ -187,7 +196,7 @@ mod tests { KeySourceSpec::File(ghost_path.clone()), KeySourceSpec::Environment, ]; - let err = load_ring(&specs, &[]).unwrap_err(); + let err = load_ring(&specs, &[], &[KeyNaming::Env]).unwrap_err(); assert!( err.contains("ghost.keys"), "file source should be terminal and error with the path; got: {err}" @@ -202,7 +211,7 @@ mod tests { KeySourceSpec::File(std::path::PathBuf::from("/nix/store/abc/.env.keys")), KeySourceSpec::Environment, ]; - let err = load_ring(&specs, &[]).unwrap_err(); + let err = load_ring(&specs, &[], &[KeyNaming::Env]).unwrap_err(); assert!( err.contains("Nix store"), "file source under /nix/store should be terminal and reject; got: {err}" @@ -232,7 +241,7 @@ mod tests { unsafe { std::env::remove_var("CREDENTIALS_DIRECTORY"); } - let err = load_ring(&specs, &[]).unwrap_err(); + let err = load_ring(&specs, &[], &[KeyNaming::Env]).unwrap_err(); // The error must be from environment (terminal), not "no usable key // source" (which would mean environment also fell through). assert!( @@ -240,4 +249,60 @@ mod tests { "environment should be terminal, not fall through; got: {err}" ); } + + #[test] + fn load_ring_admits_bundle_naming_when_required() { + // Regression for the bundle-ring gap: load_ring used to hardcode + // KeyNaming::Env at every source leg, so POSTMASTER_KEY material + // never entered the ring and every bundle config failed at + // resolve_bundle time. With Bundle in the required namings, the + // environment source must admit it. + // + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. + let _guard = ENV_LOCK.lock().unwrap(); + let var_name = "POSTMASTER_KEY_TESTLOADRING"; + unsafe { + std::env::set_var(var_name, "aa".repeat(32)); + } + let specs = vec![KeySourceSpec::Environment]; + let ring = load_ring(&specs, &[], &[KeyNaming::Bundle]); + unsafe { + std::env::remove_var(var_name); + } + let ring = + ring.expect("environment source must admit POSTMASTER_KEY* when Bundle is required"); + assert!(ring.candidates(var_name).is_some()); + } + + #[test] + fn load_ring_excludes_unrequired_namings() { + // Least privilege: a bundle config's ring must NOT carry + // DOTENV_PRIVATE_KEY* material just because the source provides + // it, and vice versa — the ring admits exactly the required set. + // + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. + let _guard = ENV_LOCK.lock().unwrap(); + let dotenv_var = "DOTENV_PRIVATE_KEY_TESTLOADRING"; + let bundle_var = "POSTMASTER_KEY_TESTLOADRING"; + unsafe { + std::env::set_var(dotenv_var, "bb".repeat(32)); + std::env::set_var(bundle_var, "cc".repeat(32)); + } + let specs = vec![KeySourceSpec::Environment]; + let ring = load_ring(&specs, &[], &[KeyNaming::Bundle]); + unsafe { + std::env::remove_var(dotenv_var); + std::env::remove_var(bundle_var); + } + let ring = ring.expect("bundle-required ring should load from POSTMASTER_KEY*"); + assert!(ring.candidates(bundle_var).is_some()); + assert!( + ring.candidates(dotenv_var).is_none(), + "an unrequired naming must not enter the ring" + ); + } } diff --git a/src/launcher.rs b/src/launcher.rs index 72e3a69..f6d9aa6 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -208,7 +208,7 @@ fn decrypt(cfg: &ExecConfig) -> Result<(Resolved, Vec<(String, String)>), String for f in &cfg.bundle_files { wanted.push(KeyNaming::Bundle.key_var_for(f)?); } - let ring = load_ring(&cfg.keys, &wanted)?; + let ring = load_ring(&cfg.keys, &wanted, &cfg.required_namings())?; // Resolve .env files (if any) via the env adapter. Values skipped // under strict:false are recorded in `failed` so --verify-keys can diff --git a/src/server.rs b/src/server.rs index ecbfd8a..f630e27 100644 --- a/src/server.rs +++ b/src/server.rs @@ -496,7 +496,10 @@ pub fn run(args: &Args) -> Result<(), String> { return Err("config maps no credentials; nothing to do".into()); } - let ring = Arc::new(KeyRing::load(&keys_path(&cfg.keys)?, KeyNaming::Env)?); + // The daemon's fetch contract is dotenvx-style env entries only; the + // bundle adapter is an exec-mode surface, so the ring requires Env + // naming alone here. + let ring = Arc::new(KeyRing::load(&keys_path(&cfg.keys)?, &[KeyNaming::Env])?); // Preflight: prove every credential is servable — and every peer_user // resolvable — before accepting anyone. diff --git a/tests/exec_conformance/bundle.rs b/tests/exec_conformance/bundle.rs index a9e427d..cabb95f 100644 --- a/tests/exec_conformance/bundle.rs +++ b/tests/exec_conformance/bundle.rs @@ -1,5 +1,125 @@ //! Bundle conformance tests. //! -//! The bundle adapter's conformance surface is currently covered by the -//! unit tests in `src/adapter/bundle.rs`; this module is the designated -//! home for end-to-end bundle exec conformance tests. +//! End-to-end bundle exec coverage: the actual binary, a real bundle +//! file, and key material loaded through `load_ring` — the seam where +//! the bundle-ring gap lived (unit tests build rings directly and never +//! saw it). + +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64; + +use crate::common; +use crate::{run_exec, write_config}; + +/// Encrypt `value` for the shared test key with AAD = the entry name, +/// exactly as the bundle adapter's suite requires. +fn enc_entry(name: &str, value: &str) -> String { + let pk = hex::decode(common::test_pk_hex()).unwrap(); + let ct = ecies::encrypt_with_aad(&pk, value.as_bytes(), name.as_bytes()).unwrap(); + BASE64.encode(ct) +} + +/// Write a v1 bundle file with the given (name, value) utf8 entries. +fn write_bundle(dir: &std::path::Path, entries: &[(&str, &str)]) -> std::path::PathBuf { + let entries: serde_json::Map = entries + .iter() + .map(|(name, value)| { + ( + name.to_string(), + serde_json::json!({ + "encoding": "utf8", + "ciphertext": enc_entry(name, value), + }), + ) + }) + .collect(); + let bundle = serde_json::json!({ + "format": "postmaster.bundle", + "version": 1, + "profile": "conformance", + "suite": "ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad", + "recipients": [{ "id": "test", "public_key": common::test_pk_hex() }], + "entries": entries, + }); + let p = dir.join("secrets.bundle.json"); + std::fs::write(&p, serde_json::to_vec_pretty(&bundle).unwrap()).unwrap(); + p +} + +/// A keys file carrying `POSTMASTER_KEY` (and optionally +/// `DOTENV_PRIVATE_KEY`), with the permissions `KeyRing::load` enforces. +fn write_keys(dir: &std::path::Path, with_dotenv: bool) -> std::path::PathBuf { + use std::os::unix::fs::PermissionsExt; + let mut content = format!("POSTMASTER_KEY=\"{}\"\n", common::TEST_SK_HEX); + if with_dotenv { + content.push_str(&format!("DOTENV_PRIVATE_KEY=\"{}\"\n", common::TEST_SK_HEX)); + } + let p = dir.join(".env.keys"); + std::fs::write(&p, content).unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600)).unwrap(); + p +} + +#[test] +fn bundle_exec_loads_postmaster_key_through_load_ring() { + // Regression for the bundle-ring gap: load_ring hardcoded + // KeyNaming::Env at every source leg, so POSTMASTER_KEY never entered + // the ring and EVERY bundle config failed at exec with "key ring has + // no POSTMASTER_KEY entry". This test drives the real binary through + // load_ring; it fails on the old code and passes on the fix. + let d = common::tmpdir("bundlee2e"); + let bundle = write_bundle(&d, &[("SECRET", "bundle-secret-value")]); + let keys = write_keys(&d, false); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"bundle_files":["{}"]}}"#, + keys.display(), + bundle.display() + ), + ); + let sh = format!("printf %s \"$SECRET\" > '{d}'/secret.out", d = d.display()); + let out = run_exec(&cfg, &sh, &[]); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!( + std::fs::read(d.join("secret.out")).unwrap(), + b"bundle-secret-value" + ); +} + +#[test] +fn mixed_env_and_bundle_exec_resolves_both_adapters() { + // A config with both env_files and bundle_files requires BOTH + // namings in one ring (the adapter-aware load_ring signature's + // multi-naming path). + let d = common::tmpdir("bundle-mixed"); + let val = "p@ss;|&`$(boom)\"'\nline2"; + let env = common::write_env_file(&d, ".env", &[format!("PLAIN=\"{}\"", common::enc(val))]); + let bundle = write_bundle(&d, &[("SECRET", "from-bundle")]); + let keys = write_keys(&d, true); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"env_files":["{}"],"bundle_files":["{}"]}}"#, + keys.display(), + env.display(), + bundle.display() + ), + ); + let sh = format!( + "printf %s \"$SECRET\" > '{d}'/secret.out && printf %s \"$PLAIN\" > '{d}'/plain.out", + d = d.display() + ); + let out = run_exec(&cfg, &sh, &[]); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(std::fs::read(d.join("secret.out")).unwrap(), b"from-bundle"); + assert_eq!(std::fs::read(d.join("plain.out")).unwrap(), val.as_bytes()); +} diff --git a/tests/exec_conformance/main.rs b/tests/exec_conformance/main.rs index ef3c5d9..cc4d9a4 100644 --- a/tests/exec_conformance/main.rs +++ b/tests/exec_conformance/main.rs @@ -51,7 +51,7 @@ fn wrapped_base64_ciphertext_decrypts() { let keys_path = d.join(".env.keys"); // Load the key ring - let ring = postmaster::keys::KeyRing::load(&keys_path, KeyNaming::Env).unwrap(); + let ring = postmaster::keys::KeyRing::load(&keys_path, &[KeyNaming::Env]).unwrap(); // Create a dummy env file path for error messages let dummy_env = d.join(".env"); From 86e5a6cf84a40e3a71a3eb161e7a05dbd660177f Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Thu, 6 Aug 2026 12:44:56 -0500 Subject: [PATCH 17/47] docs: single-tenant secrets_dir contract for hand-written configs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit prune_stale and the sibling monitor's cleanup delete files based on one service's key set, so two services sharing one secrets_dir lets one service's lifecycle delete the other's live files (availability, never confidentiality). The generated Nix modules already namespace per service — Linux units mount a namespace-private tmpfs each, the darwin module writes per-service subdirectories — so the rule binds hand-written configs only. Runtime enforcement via a service-identity sentinel is considered-and-deferred to the broker era. --- docs/src/architecture/threat-model.md | 14 ++++++++++++++ docs/src/reference/launcher-contract.md | 10 ++++++++++ 2 files changed, 24 insertions(+) diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index c0e3e12..6413840 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -495,6 +495,20 @@ the strongest backstop in the system. A monitor that dies before the service leaves the pre-existing backstops (`ExecStopPost`, teardown, `prune_stale`) — the same floor as before the monitor existed. +### Shared `secrets_dir` (multi-tenant misuse) — Documented contract + +`secrets_dir` is single-tenant per service: `prune_stale` and the +monitor's cleanup delete files based on one service's key set, so two +services sharing one directory lets one service's lifecycle delete the +other's live files. The impact is availability, not confidentiality — +no plaintext crosses services. The generated Nix modules comply by +construction (Linux: each unit mounts a namespace-private tmpfs at the +path; darwin: per-service subdirectory under the shared ramdisk), so +this binds hand-written configs only: one `secrets_dir` per service. +Runtime enforcement via a service-identity sentinel is a +considered-and-deferred hardening for the broker era, when multi-tenant +topologies become real by design. + ### Ramdisk mount verification (macOS) — Mitigated `verify_ramdisk` verifies the mount is RAM-backed by parsing diff --git a/docs/src/reference/launcher-contract.md b/docs/src/reference/launcher-contract.md index 42ceddc..cccc723 100644 --- a/docs/src/reference/launcher-contract.md +++ b/docs/src/reference/launcher-contract.md @@ -164,6 +164,16 @@ before a real launch: non-empty, it also requires `secrets_dir` and a socket mapping for every credential key. +**One `secrets_dir` per service.** postmaster treats `secrets_dir` as +single-tenant: `prune_stale` at launch and cleanup on every death path +delete files there based on one service's key set, so two services +sharing a directory lets one service's lifecycle delete the other's live +files (an availability failure — plaintext never crosses services). The +generated Nix modules comply by construction — each Linux unit mounts a +namespace-private tmpfs at the path, and the darwin module writes +per-service subdirectories under the ramdisk — so this rule binds +hand-written configs. + `--check` also validates env-file basenames, rejects private-key `file` sources under `/nix/store`, rejects path-like `credential` source names, and applies identifier validation to `passthrough` and From 9f970cb6ca9eeed8ec2a2bdf47fd0c9416267f0b Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 09:26:12 -0500 Subject: [PATCH 18/47] fix(keys): redact Debug on secret types; tighten source/verify parity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sweep 2026-08-07 (clean-sweep-audit) K1-K6, K8, K10, K12: - KeyRing/Resolution: manual redacting Debug impls (names only) — the derived impls printed private keys / decrypted plaintext verbatim through Zeroizing's pass-through Debug (K1, K2) - from_env and the verify environment leg use vars_os: vars() panics on non-Unicode inherited entries — an abort under panic=abort (K3) - verify credential leg mirrors load_ring: refuse symlinks, require a regular file, distinguish NotFound from other stat errors (K4) - keys-file load + File verify leg: NONBLOCK open + regular-file check — a FIFO hung open(); a directory passed the permission mask (Mode carries no S_IFMT bits) (K5) - from_pairs admits by the exact A16 predicate, not bare starts_with, so keys files no longer retain unreachable prefix-collision material (K6) - credential stat errors are terminal, not "absent" — a misconfigured credential dir no longer silently falls through to the next source (K8) - Recipient rustdoc: reserved routing metadata, not key selection (K10) - setup log reports the count, not an always-N/N fraction (K12) Regression tests: Debug redaction (both types), directory-as-keys-file, credential symlink verification, stat-error terminality, from_pairs predicate. 98 lib + 7 exec_check + 18 conformance green; clippy native/release/linux-target, deny, audit, mdbook all green. --- src/adapter/bundle.rs | 6 +- src/keys/env.rs | 8 ++- src/keys/load.rs | 30 ++++++++- src/keys/mod.rs | 115 ++++++++++++++++++++++++++++++++--- src/keys/provisioning/mod.rs | 101 ++++++++++++++++++++++++++---- src/keys/source.rs | 54 +++++++++++++++- 6 files changed, 287 insertions(+), 27 deletions(-) diff --git a/src/adapter/bundle.rs b/src/adapter/bundle.rs index 9aa9017..632dfab 100644 --- a/src/adapter/bundle.rs +++ b/src/adapter/bundle.rs @@ -45,8 +45,10 @@ pub struct Bundle { pub entries: std::collections::BTreeMap, } -/// A recipient in the bundle: public routing metadata used to select -/// local private key material. +/// A recipient in the bundle: public routing metadata reserved for +/// future recipient selection. Parsed and shape-validated only today — +/// resolution selects ring candidates by the fixed `POSTMASTER_KEY` +/// variable, never by recipient (sweep 2026-08-07 K10). #[derive(Deserialize, Debug)] #[serde(deny_unknown_fields)] pub struct Recipient { diff --git a/src/keys/env.rs b/src/keys/env.rs index f198b5e..da4d7d9 100644 --- a/src/keys/env.rs +++ b/src/keys/env.rs @@ -18,8 +18,14 @@ pub(crate) fn is_key_var_name(prefix: &str, name: &str) -> bool { /// Implementation of [`KeyRing::from_env`]; the contract is documented on /// the method. pub(super) fn from_env(namings: &[KeyNaming]) -> Result { + // vars_os + skip non-UTF-8 names/values: std::env::vars() PANICS during + // iteration if any inherited entry is not valid Unicode, which under + // panic=abort aborts the whole launcher on an arbitrary inherited + // variable (sweep 2026-08-07 K3). Key-var names match [A-Za-z0-9_] and + // key values are hex, so nothing admissible is lost. KeyRing::from_pairs( - std::env::vars() + std::env::vars_os() + .filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?))) .filter(|(k, _)| namings.iter().any(|n| is_key_var_name(n.key_prefix(), k))) .map(|(k, v)| (k, Zeroizing::new(v))), namings, diff --git a/src/keys/load.rs b/src/keys/load.rs index 63c6d57..817292d 100644 --- a/src/keys/load.rs +++ b/src/keys/load.rs @@ -10,8 +10,14 @@ use crate::adapter::KeyNaming; /// Implementation of [`KeyRing::load`]; the contract is documented on the /// method. pub(super) fn load(path: &Path, namings: &[KeyNaming]) -> Result { - let oflags = - rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC; + // NONBLOCK is inert on regular files; on a FIFO it turns the otherwise + // blocking open into an immediate success that the file-type check + // below rejects — a FIFO here must never hang the launcher at open + // (sweep 2026-08-07 K5). + let oflags = rustix::fs::OFlags::RDONLY + | rustix::fs::OFlags::NOFOLLOW + | rustix::fs::OFlags::CLOEXEC + | rustix::fs::OFlags::NONBLOCK; let fd = rustix::fs::open(path, oflags, rustix::fs::Mode::empty()).map_err(|e| { format!( "keys file {}: {e} (refusing to follow a symlink)", @@ -20,6 +26,15 @@ pub(super) fn load(path: &Path, namings: &[KeyNaming]) -> Result {} + other => panic!("expected not-a-regular-file error, got {other:?}"), + } + } + #[test] fn load_rejects_world_readable_keys_file() { use std::os::unix::fs::PermissionsExt; diff --git a/src/keys/mod.rs b/src/keys/mod.rs index b86be33..13dbeb1 100644 --- a/src/keys/mod.rs +++ b/src/keys/mod.rs @@ -28,17 +28,30 @@ mod verify; /// Re-exported so `crate::keys::verify_external_binary` keeps resolving. pub use verify::verify_external_binary; -/// The exact predicate `KeyRing::from_env` admits, re-exported so setup -/// verification accepts precisely the variables resolution would load -/// (audit 2026-08-02 A16). +/// The exact predicate `KeyRing::from_env` and `KeyRing::from_pairs` +/// admit, re-exported so setup verification accepts precisely the +/// variables resolution would load (audit 2026-08-02 A16; from_pairs +/// shares the predicate since sweep 2026-08-07 K6). pub(crate) use env::is_key_var_name; /// Full variable name (adapter-specific, e.g. DOTENV_PRIVATE_KEY[_]) /// → candidate secret keys. Multiple candidates per name come from /// comma-separated rotation convention; decryption tries each in order. -#[derive(Debug)] pub struct KeyRing(HashMap>>); +// Redacted Debug: variable names only, never key material. A derived impl +// would print every 32-byte key verbatim — zeroize's `Zeroizing` derives +// its own Debug pass-through to the inner value — a latent leak channel on +// a public type (sweep 2026-08-07 K1). Tests need *a* Debug impl for +// `Result::expect_err`; this keeps that working without the leak. +impl std::fmt::Debug for KeyRing { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("KeyRing") + .field("vars", &self.0.keys().collect::>()) + .finish() + } +} + impl KeyRing { /// Look up candidate keys for a given key variable name. /// Returns `None` if the variable has no candidates in the ring. @@ -63,8 +76,11 @@ impl KeyRing { load::load(path, namings) } - /// Core parser shared by every key source: keep keys matching any of - /// the required adapters' key prefixes, split comma-separated rotation + /// Core parser shared by every key source: keep keys exactly matching + /// the required adapters' key prefixes (`PREFIX` or `PREFIX_` — + /// the A16 predicate; a bare starts_with admitted unreachable + /// prefix-collision material like `DOTENV_PRIVATE_KEYFOO` from keys + /// files, sweep 2026-08-07 K6), split comma-separated rotation /// candidates, hex-decode to 32-byte zeroized keys. Empty result is an /// error (fail closed). Takes `Zeroizing` values so callers /// never hand key material as a plain heap String that drops without @@ -77,7 +93,10 @@ impl KeyRing { ) -> Result { let mut map: HashMap>> = HashMap::new(); for (name, mut value) in pairs { - if !namings.iter().any(|n| name.starts_with(n.key_prefix())) { + if !namings + .iter() + .any(|n| is_key_var_name(n.key_prefix(), &name)) + { value.zeroize(); continue; } @@ -249,7 +268,6 @@ pub fn resolve( pub type ResolvedVars = Vec<(String, Zeroizing>)>; /// Outcome of a [`resolve_all`] pass. -#[derive(Debug)] pub struct Resolution { /// Resolved (name, plaintext) pairs in injection order. pub resolved: ResolvedVars, @@ -261,6 +279,23 @@ pub struct Resolution { pub failed: Vec<(String, String)>, } +// Redacted Debug, same channel as K1 (sweep 2026-08-07 K2): names only — +// a derived impl would print the decrypted plaintext values themselves. +impl std::fmt::Debug for Resolution { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Resolution") + .field( + "resolved", + &self.resolved.iter().map(|(k, _)| k).collect::>(), + ) + .field( + "failed", + &self.failed.iter().map(|(k, _)| k).collect::>(), + ) + .finish() + } +} + /// Resolve every key across `files` per the precedence contract /// (see docs/src/launcher-contract.md): within one file the LAST assignment /// wins (dotenv semantics); across files the FIRST file defining a key wins @@ -624,4 +659,68 @@ pub mod tests { assert_eq!(out.failed.len(), 1); assert_eq!(out.failed[0].0, "A"); } + + #[test] + fn keyring_debug_redacts_key_material() { + // sweep 2026-08-07 K1: a derived Debug would print every 32-byte + // key verbatim (Zeroizing's Debug passes through to the inner + // value). Names only. + let ring = KeyRing::from_pairs( + [( + "DOTENV_PRIVATE_KEY".to_string(), + Zeroizing::new("11".repeat(32)), + )], + &[KeyNaming::Env], + ) + .unwrap(); + let dbg = format!("{ring:?}"); + assert!(dbg.contains("DOTENV_PRIVATE_KEY")); + assert!( + !dbg.contains("17, 17"), + "debug output must not contain raw key bytes: {dbg}" + ); + } + + #[test] + fn resolution_debug_redacts_plaintext() { + // sweep 2026-08-07 K2: same channel — a derived Debug would print + // the decrypted plaintext values themselves. + let r = Resolution { + resolved: vec![( + "MY_SECRET".to_string(), + Zeroizing::new(b"super-secret-plaintext".to_vec()), + )], + failed: vec![("OTHER".to_string(), "decrypt failed".to_string())], + }; + let dbg = format!("{r:?}"); + assert!(dbg.contains("MY_SECRET")); + assert!(dbg.contains("OTHER")); + assert!( + !dbg.contains("super-secret"), + "debug output must not contain plaintext: {dbg}" + ); + } + + #[test] + fn from_pairs_uses_the_exact_key_var_predicate() { + // sweep 2026-08-07 K6: bare starts_with admitted + // DOTENV_PRIVATE_KEYFOO from keys files as unreachable dead + // material; the A16 predicate drops it exactly as from_env does. + let ring = KeyRing::from_pairs( + [ + ( + "DOTENV_PRIVATE_KEYFOO".to_string(), + Zeroizing::new("22".repeat(32)), + ), + ( + "DOTENV_PRIVATE_KEY".to_string(), + Zeroizing::new("33".repeat(32)), + ), + ], + &[KeyNaming::Env], + ) + .unwrap(); + assert!(ring.candidates("DOTENV_PRIVATE_KEY").is_some()); + assert!(ring.candidates("DOTENV_PRIVATE_KEYFOO").is_none()); + } } diff --git a/src/keys/provisioning/mod.rs b/src/keys/provisioning/mod.rs index de31284..4540ea9 100644 --- a/src/keys/provisioning/mod.rs +++ b/src/keys/provisioning/mod.rs @@ -292,7 +292,6 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> #[cfg(not(target_os = "macos"))] let _ = wanted; let mut checked = 0_u32; - let mut found = 0_u32; for spec in &cfg.keys { match spec { @@ -301,13 +300,37 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> let dir = std::env::var_os("CREDENTIALS_DIRECTORY") .ok_or("$CREDENTIALS_DIRECTORY is not set")?; let p = Path::new(&dir).join(name); - if !p.exists() { - return Err(format!( - "{}: credential source not found under $CREDENTIALS_DIRECTORY", - p.display() - )); + // Mirror load_ring's discipline (sweep 2026-08-07 K4): + // verification must not pass what resolution rejects — + // exists() follows symlinks, but the loader refuses a + // symlinked credential outright. + match fs::symlink_metadata(&p) { + Ok(md) if md.file_type().is_symlink() => { + return Err(format!( + "{}: credential source is a symlink; refusing to follow", + p.display() + )); + } + Ok(md) if md.is_file() => {} + Ok(_) => { + return Err(format!( + "{}: credential source is not a regular file", + p.display() + )); + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return Err(format!( + "{}: credential source not found under $CREDENTIALS_DIRECTORY", + p.display() + )); + } + Err(e) => { + return Err(format!( + "{}: cannot stat credential source: {e}", + p.display() + )); + } } - found += 1; } KeySourceSpec::File(path) => { checked += 1; @@ -317,15 +340,26 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> path.display() )); } + // NONBLOCK is inert on regular files and prevents a FIFO + // from hanging verification at open; the file-type check + // then rejects anything that isn't a regular file (sweep + // 2026-08-07 K5). let oflags = rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW - | rustix::fs::OFlags::CLOEXEC; + | rustix::fs::OFlags::CLOEXEC + | rustix::fs::OFlags::NONBLOCK; let fd = rustix::fs::open(path, oflags, rustix::fs::Mode::empty()).map_err(|e| { format!("{}: {e} (refusing to follow a symlink)", path.display()) })?; let stat = rustix::fs::fstat(&fd) .map_err(|e| format!("{}: fstat: {e}", path.display()))?; + if !rustix::fs::FileType::from_raw_mode(stat.st_mode).is_file() { + return Err(format!( + "{}: not a regular file (fail closed)", + path.display() + )); + } let mode = rustix::fs::Mode::from_bits_truncate(stat.st_mode); if mode.intersects(rustix::fs::Mode::RWXG | rustix::fs::Mode::RWXO) { return Err(format!( @@ -342,7 +376,6 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> stat.st_uid )); } - found += 1; } KeySourceSpec::Keychain(service) => { #[cfg(target_os = "macos")] @@ -362,7 +395,6 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> } } } - found += 1; } #[cfg(not(target_os = "macos"))] { @@ -384,11 +416,16 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> // verification must not pass what resolution rejects. for naming in cfg.required_namings() { let prefix = naming.key_prefix(); - if !std::env::vars().any(|(k, _)| crate::keys::is_key_var_name(prefix, &k)) { + // vars_os: std::env::vars() panics during iteration on + // non-Unicode entries — an abort under panic=abort, not + // a clean verification failure (sweep 2026-08-07 K3). + if !std::env::vars_os().any(|(k, _)| { + k.to_str() + .is_some_and(|k| crate::keys::is_key_var_name(prefix, k)) + }) { return Err(format!("environment: no {prefix}* variables set")); } } - found += 1; } } } @@ -397,8 +434,11 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> return Err("no key sources configured (configure keys=[…])".into()); } + // Every per-source failure above early-returns, so reaching the log + // means checked == verified — report the count, not a fraction that + // is always N/N (sweep 2026-08-07 K12). log(&format!( - "setup: {found}/{checked} key source(s) verified — environment ready" + "setup: {checked} key source(s) verified — environment ready" )); Ok(()) } @@ -463,6 +503,41 @@ mod tests { } } + #[test] + fn verify_key_sources_credential_rejects_symlink() { + // sweep 2026-08-07 K4: verification must not pass what resolution + // rejects — exists() followed symlinks; the loader refuses them. + use std::os::unix::fs::PermissionsExt; + let d = std::env::temp_dir().join(format!("pm-verify-cred-symlink-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + let cred_dir = d.join("creds"); + fs::create_dir_all(&cred_dir).unwrap(); + let real = d.join("real-keys"); + fs::write(&real, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); + fs::set_permissions(&real, fs::Permissions::from_mode(0o600)).unwrap(); + std::os::unix::fs::symlink(&real, cred_dir.join("link-keys")).unwrap(); + + let cfg: ExecConfig = serde_json::from_str( + r#"{"mode":"env","keys":[{"credential":"link-keys"}],"env_files":["/x/.env"]}"#, + ) + .unwrap(); + + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. + let _guard = ENV_LOCK.lock().unwrap(); + unsafe { + std::env::set_var("CREDENTIALS_DIRECTORY", &cred_dir); + } + let res = verify_key_sources(&cfg, &[]); + unsafe { + std::env::remove_var("CREDENTIALS_DIRECTORY"); + } + let _ = fs::remove_dir_all(&d); + let err = res.expect_err("a symlinked credential must fail verification"); + assert!(err.contains("symlink"), "{err}"); + } + fn bundle_only_cfg() -> ExecConfig { serde_json::from_str( r#"{"mode":"env","keys":["environment"],"bundle_files":["/x/s.json"]}"#, diff --git a/src/keys/source.rs b/src/keys/source.rs index e2dc16f..84fd5d6 100644 --- a/src/keys/source.rs +++ b/src/keys/source.rs @@ -55,7 +55,19 @@ pub fn load_ring( p.display() )); } - Err(_) => { /* absent: fall through to next source */ } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + // absent: fall through to next source + } + // A permission-denied or malformed credential dir is + // NOT "absent" — it is misconfigured. Fail loudly + // rather than silently selecting a source the + // operator didn't expect (sweep 2026-08-07 K8). + Err(e) => { + return Err(format!( + "{}: cannot stat credential source: {e}", + p.display() + )); + } } } // absent credential: fall through to the next source @@ -152,6 +164,46 @@ mod tests { ); } + #[test] + fn load_ring_credential_stat_error_is_terminal() { + // sweep 2026-08-07 K8: a permission-denied credential dir is + // misconfigured, not "absent" — it must hard-error rather than + // fall through to the next source. + use std::os::unix::fs::PermissionsExt; + if rustix::process::geteuid().is_root() { + // chmod 000 does not exclude root; the EACCES leg is + // unobservable in a root test run. + return; + } + let d = std::env::temp_dir().join(format!("pm-keysource-eacces-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + let cred_dir = d.join("locked"); + fs::create_dir_all(&cred_dir).unwrap(); + fs::set_permissions(&cred_dir, fs::Permissions::from_mode(0o000)).unwrap(); + + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. + let _guard = ENV_LOCK.lock().unwrap(); + unsafe { + std::env::set_var("CREDENTIALS_DIRECTORY", &cred_dir); + } + let specs = vec![ + KeySourceSpec::Credential("keys".to_string()), + KeySourceSpec::Environment, + ]; + let err = load_ring(&specs, &[], &[KeyNaming::Env]).unwrap_err(); + unsafe { + std::env::remove_var("CREDENTIALS_DIRECTORY"); + } + fs::set_permissions(&cred_dir, fs::Permissions::from_mode(0o700)).unwrap(); + let _ = fs::remove_dir_all(&d); + assert!( + err.contains("cannot stat credential source"), + "stat failure must be terminal, not a fall-through; got: {err}" + ); + } + #[test] fn load_ring_credential_rejects_non_file() { // A directory as a credential source name should be rejected, From e26cce61dadfb1b5e84788836e1b1accef23033c Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 09:33:18 -0500 Subject: [PATCH 19/47] fix(provisioning): make --force real (re-seed, re-prompt) instead of a no-op MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sweep 2026-08-07 K7. Every provisioning leg documented --force as "re-create or re-seed even if already correct" and every leg ignored it — an operator rotating a key via setup --force got a silent no-op. - keychain: --force re-seeds EVERY wanted item, present or not (previously the seeding loop iterated only the missing ones, so force with zero missing items did nothing) - keys file: --force re-prompts for contents and replaces them in place (WRONLY|TRUNC|NOFOLLOW on the just-verified path, 0600 re-forced on the fd); declining keeps the existing file with a log line instead of erroring - force + unattended fails closed: there is no operator to paste contents (fail-closed beats silently skipping a requested re-create) - keys dir: force documented as having no directory effect — mode is already corrected whenever wrong; there is nothing to re-seed in a directory Regression test: force + unattended fails closed; non-force unattended verifies. 99 lib + 7 exec_check + 18 conformance green; clippy native/release/linux-target, deny, audit, mdbook all green. --- src/keys/provisioning/mod.rs | 174 ++++++++++++++++++++++++++--------- 1 file changed, 130 insertions(+), 44 deletions(-) diff --git a/src/keys/provisioning/mod.rs b/src/keys/provisioning/mod.rs index 4540ea9..1841816 100644 --- a/src/keys/provisioning/mod.rs +++ b/src/keys/provisioning/mod.rs @@ -37,8 +37,10 @@ fn default_keys_dir() -> PathBuf { } /// Create the keys directory with 0700 permissions if it doesn't exist. -/// If it exists, verify permissions and ownership are correct. Idempotent -/// — skips if already correct unless `force` is true. +/// If it exists, verify permissions and ownership are correct, correcting +/// the mode whenever wrong. `force` has no directory effect — there is +/// nothing to re-seed in a directory; force governs the keys file and the +/// keychain items (sweep 2026-08-07 K7). #[allow(clippy::print_stderr)] fn ensure_keys_dir(keys_dir: &Path, _force: bool) -> Result<(), String> { if keys_dir.exists() { @@ -118,8 +120,12 @@ fn ensure_keys_dir(keys_dir: &Path, _force: bool) -> Result<(), String> { /// euid). If the file doesn't exist, in interactive mode, prompt the /// operator to create it. In unattended mode, fail closed. If the file /// exists but has wrong permissions, fix them. +/// +/// `--force` re-prompts for the contents even when the file is already +/// correct (manual key rotation, sweep 2026-08-07 K7). Force requires +/// interactive mode: unattended has no operator to paste contents. #[allow(clippy::print_stderr)] -fn ensure_keys_file(path: &Path, _force: bool, unattended: bool) -> Result<(), String> { +fn ensure_keys_file(path: &Path, force: bool, unattended: bool) -> Result<(), String> { if path.exists() { // Verify permissions and ownership (same checks as setup_recheck) let oflags = @@ -145,7 +151,61 @@ fn ensure_keys_file(path: &Path, _force: bool, unattended: bool) -> Result<(), S stat.st_uid )); } - log(&format!("{}: keys file verified", path.display())); + drop(fd); + if !force { + log(&format!("{}: keys file verified", path.display())); + return Ok(()); + } + // --force: re-prompt for the contents even though the file is + // already correct (sweep 2026-08-07 K7). + if unattended { + return Err(format!( + "{}: --force re-prompts for key contents, which unattended mode cannot do (fail closed)", + path.display() + )); + } + eprintln!("{}: keys file exists and is valid.", path.display()); + eprintln!("--force given: replace its contents now? [y/N] "); + let mut input = String::new(); + if std::io::stdin().read_line(&mut input).is_err() { + return Err(format!("{}: cannot read input", path.display())); + } + if !input.trim().eq_ignore_ascii_case("y") { + log(&format!( + "{}: --force declined; existing keys file kept", + path.display() + )); + return Ok(()); + } + eprintln!("Paste the keys file contents (Ctrl+D to finish):"); + // Zeroizing: operator-pasted key material must not linger in freed + // heap pages (audit 2026-08-02 O4). + let mut contents = zeroize::Zeroizing::new(String::new()); + if std::io::stdin().read_to_string(&mut contents).is_err() { + return Err(format!("{}: cannot read key contents", path.display())); + } + // Overwrite in place: WRONLY|TRUNC|NOFOLLOW on the just-verified + // path, perms forced back to 0600 on the fd before the write. + let oflags = rustix::fs::OFlags::WRONLY + | rustix::fs::OFlags::TRUNC + | rustix::fs::OFlags::NOFOLLOW + | rustix::fs::OFlags::CLOEXEC; + let fd = rustix::fs::open(path, oflags, rustix::fs::Mode::empty()).map_err(|e| { + format!( + "{}: cannot open for replacement: {e} (refusing to follow a symlink)", + path.display() + ) + })?; + rustix::fs::fchmod(&fd, rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR) + .map_err(|e| format!("{}: cannot fix permissions: {e}", path.display()))?; + let mut file = fs::File::from(fd); + use std::io::Write; + file.write_all(contents.as_bytes()) + .map_err(|e| format!("{}: cannot write: {e}", path.display()))?; + log(&format!( + "{}: keys file contents replaced (--force)", + path.display() + )); return Ok(()); } @@ -207,7 +267,8 @@ fn ensure_keys_file(path: &Path, _force: bool, unattended: bool) -> Result<(), S /// Verify keychain items exist for the wanted key variables. If they /// don't exist and we're in interactive mode, offer to seed them. -/// On macOS only. +/// `--force` re-seeds EVERY wanted item, present or not (sweep +/// 2026-08-07 K7). On macOS only. #[cfg(target_os = "macos")] #[allow(clippy::print_stderr)] fn ensure_keychain_items( @@ -228,7 +289,15 @@ fn ensure_keychain_items( } } - if missing.is_empty() && !force { + // --force re-seeds every wanted item, present or not; without it + // only the missing ones are offered (sweep 2026-08-07 K7). + let to_seed: Vec<&str> = if force { + wanted.iter().map(String::as_str).collect() + } else { + missing + }; + + if to_seed.is_empty() { log(&format!( "keychain {service}: all {wanted_len} item(s) verified", wanted_len = wanted.len() @@ -236,50 +305,45 @@ fn ensure_keychain_items( return Ok(()); } - if unattended && !missing.is_empty() { + if unattended { return Err(format!( - "keychain {service}: {missing_len} item(s) missing (unattended mode — cannot prompt)", - missing_len = missing.len() + "keychain {service}: {seed_len} item(s) to seed (unattended mode — cannot prompt)", + seed_len = to_seed.len() )); } - // Interactive: offer to seed missing items - if !missing.is_empty() { - eprintln!( - "keychain {service}: missing items for: {}", - missing.join(", ") - ); - eprintln!("Seed them now? You will need to paste each key value. [y/N] "); - let mut input = String::new(); - if std::io::stdin().read_line(&mut input).is_err() { - return Err("cannot read input".into()); - } - if !input.trim().eq_ignore_ascii_case("y") { - return Err(format!( - "keychain {service}: operator declined to seed missing items" - )); - } + // Interactive: offer to seed + eprintln!("keychain {service}: items to seed: {}", to_seed.join(", ")); + eprintln!("Seed them now? You will need to paste each key value. [y/N] "); + let mut input = String::new(); + if std::io::stdin().read_line(&mut input).is_err() { + return Err("cannot read input".into()); + } + if !input.trim().eq_ignore_ascii_case("y") { + return Err(format!( + "keychain {service}: operator declined to seed items" + )); + } - for var in &missing { - eprint!("Paste value for {var}: "); - // Zeroizing: pasted key material must not linger in freed - // heap pages (audit 2026-08-02 O4). `trim()` borrows, no copy. - let mut value = zeroize::Zeroizing::new(String::new()); - if std::io::stdin().read_line(&mut value).is_err() { - return Err(format!("cannot read value for {var}")); - } - let value = value.trim(); - if value.is_empty() { - return Err(format!("{var}: empty value, refusing to seed")); - } - // Seed via the Security.framework API, not the security CLI: - // `add-generic-password -w ` exposes key material in - // the subprocess argv, readable by any local process via ps / - // proc_pidinfo (audit 2026-08-02 O3; F1 crate direction). - security_framework::passwords::set_generic_password(service, var, value.as_bytes()) - .map_err(|e| format!("keychain {service}: failed to seed {var}: {e}"))?; - log(&format!("keychain {service}: seeded {var}")); + for var in &to_seed { + eprint!("Paste value for {var}: "); + // Zeroizing: pasted key material must not linger in freed + // heap pages (audit 2026-08-02 O4). `trim()` borrows, no copy. + let mut value = zeroize::Zeroizing::new(String::new()); + if std::io::stdin().read_line(&mut value).is_err() { + return Err(format!("cannot read value for {var}")); } + let value = value.trim(); + if value.is_empty() { + return Err(format!("{var}: empty value, refusing to seed")); + } + // Seed via the Security.framework API, not the security CLI: + // `add-generic-password -w ` exposes key material in + // the subprocess argv, readable by any local process via ps / + // proc_pidinfo (audit 2026-08-02 O3; F1 crate direction). + security_framework::passwords::set_generic_password(service, var, value.as_bytes()) + .map_err(|e| format!("keychain {service}: failed to seed {var}: {e}"))?; + log(&format!("keychain {service}: seeded {var}")); } Ok(()) @@ -538,6 +602,28 @@ mod tests { assert!(err.contains("symlink"), "{err}"); } + #[test] + fn ensure_keys_file_force_unattended_fails_closed() { + // sweep 2026-08-07 K7: --force re-prompts for contents, which + // unattended mode cannot do — fail closed rather than silently + // skipping the re-create the operator asked for. + use std::os::unix::fs::PermissionsExt; + let d = std::env::temp_dir().join(format!("pm-force-unattended-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + let keys = d.join(".env.keys"); + fs::write(&keys, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); + fs::set_permissions(&keys, fs::Permissions::from_mode(0o600)).unwrap(); + + let err = + ensure_keys_file(&keys, true, true).expect_err("force + unattended must fail closed"); + assert!(err.contains("unattended"), "{err}"); + + // Non-force unattended with a valid file verifies fine. + ensure_keys_file(&keys, false, true).expect("valid file must verify without force"); + let _ = fs::remove_dir_all(&d); + } + fn bundle_only_cfg() -> ExecConfig { serde_json::from_str( r#"{"mode":"env","keys":["environment"],"bundle_files":["/x/s.json"]}"#, From 7d97882d3bcc14924c346d17f288efec5a9c78fb Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 09:39:39 -0500 Subject: [PATCH 20/47] fix(launcher): ramdisk containment, macOS guard failure path, bundle NUL parity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sweep 2026-08-07 (clean-sweep-audit) X1, X2, X3, X6, X7: - verify_ramdisk now requires secrets_dir lexically beneath the verified RAM-backed mount (path_beneath: component-wise, no '..' escape). The guard previously proved mount and dir independently — a hand-written config could land plaintext on persistent disk past every check. Module rustdoc no longer overclaims the invariant (X1) - macOS TerminationGuard mirrors the Linux leg: pthread_sigmask's return is checked; on failure the guard logs and restores nothing instead of installing an empty mask that would unblock signals the parent deliberately blocked (X2) - bundle Utf8 values with NUL in env mode are now an unconditional hard error, identical to the .env path in env_pairs — the strict:false skip-and-log diverged from both the contract doc and the other source path (X6) - fork SAFETY comment and monitor module doc now state the child performs the inherited-heap scrub (zeroize + free) before monitor::run, sound because the production fork parent is single-threaded at fork; monitor.md credits both guard legs (X3) - prune_stale logs non-UTF8 entry names instead of silently skipping them, matching every other branch in the loop (X7) Regression test: path_beneath containment (beneath, root, sibling, prefix-collision sibling, '..' escape). 100 lib + 7 exec_check + 18 conformance green; clippy native/release/linux-target, deny, audit, mdbook all green. --- docs/src/unsafe-code/monitor.md | 2 +- src/launcher.rs | 56 ++++++++++++++++++++++----------- src/monitor.rs | 23 ++++++++------ src/ramdisk.rs | 55 ++++++++++++++++++++++++++++++-- src/secret_files.rs | 6 ++++ 5 files changed, 111 insertions(+), 31 deletions(-) diff --git a/docs/src/unsafe-code/monitor.md b/docs/src/unsafe-code/monitor.md index d4ba6a3..1ac3c8f 100644 --- a/docs/src/unsafe-code/monitor.md +++ b/docs/src/unsafe-code/monitor.md @@ -4,7 +4,7 @@ ``` src/monitor.rs — the monitor loop, liveness watches, signal ops, exit -src/launcher.rs — the fork(2) site and the Linux TerminationGuard leg +src/launcher.rs — the fork(2) site and both TerminationGuard legs (macOS + Linux) Unsafe blocks: fork(2) (libc, both platforms); rustix `runtime` kernel_sigprocmask/kernel_sigwait (Linux); libc pthread_sigmask/ sigpending/sigwait/kqueue/kevent/_exit (macOS); diff --git a/src/launcher.rs b/src/launcher.rs index f6d9aa6..359ad89 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -41,7 +41,11 @@ use crate::server::{fetch_bytes, log, read_capped}; /// on Linux too, because the fork+monitor model runs there as well. #[cfg(target_os = "macos")] pub(crate) struct TerminationGuard { - old: libc::sigset_t, + /// `None` only if the block call failed (logged); restore then no-ops + /// rather than installing an empty mask that would unblock signals the + /// launcher's parent deliberately blocked — mirrors the Linux leg + /// (sweep 2026-08-07 X2). + old: Option, } #[cfg(target_os = "macos")] @@ -57,17 +61,25 @@ impl TerminationGuard { } let mut old: libc::sigset_t = std::mem::zeroed(); // pthread form: correct in single- and multi-threaded processes. - libc::pthread_sigmask(libc::SIG_BLOCK, &set, &mut old); - Self { old } + if libc::pthread_sigmask(libc::SIG_BLOCK, &set, &mut old) != 0 { + // Cannot realistically fail (bad arguments are impossible + // here) — but if it ever does, log and run unguarded + // rather than silently pretend the window is protected. + log("termination-guard: pthread_sigmask failed"); + return Self { old: None }; + } + Self { old: Some(old) } } } /// Restore the saved signal mask. The parent calls this before /// execvp — the child must not inherit blocked termination signals. pub(crate) fn restore_mask(&self) { - unsafe { - // SAFETY: restoring a previously saved valid mask. - libc::pthread_sigmask(libc::SIG_SETMASK, &self.old, std::ptr::null_mut()); + if let Some(old) = &self.old { + unsafe { + // SAFETY: restoring a previously saved valid mask. + libc::pthread_sigmask(libc::SIG_SETMASK, old, std::ptr::null_mut()); + } } } } @@ -250,18 +262,17 @@ fn decrypt(cfg: &ExecConfig) -> Result<(Resolved, Vec<(String, String)>), String if !cfg.overload && std::env::var_os(&name).is_some() { continue; } - // NUL check for utf8 entries that would become env vars + // NUL check for utf8 entries that would become env vars. + // One rule for every env-bound value (sweep 2026-08-07 X6): + // NUL is a hard error, identical to the .env path in + // env_pairs — no strict-gated skip. if matches!(cfg.mode, ExecMode::Env) && encoding == crate::bundle::Encoding::Utf8 && value.contains(&0) { - if cfg.strict { - return Err(format!( - "{name}: value contains a NUL byte; cannot be an environment variable (use files mode)" - )); - } - log(&format!("non-strict: skipping {name}: NUL byte in value")); - continue; + return Err(format!( + "{name}: value contains a NUL byte; cannot be an environment variable (use files mode)" + )); } resolved.push((name, value)); } @@ -451,11 +462,18 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() let service_pid = rustix::process::getpid(); // SAFETY: fork(2) in a single-threaded process (the exec path spawns // no threads; the daemon's worker threads exist only in serve mode). - // The fork-child executes only monitor::run — the async-signal-safe - // syscall set documented in monitor.rs: no allocation, no stdio - // locks, no destructors — and exits via _exit/exit_group. rustix - // deliberately has no fork wrapper; on Linux this is the one libc FFI - // call on the exec path, flagged in docs/src/unsafe-code/monitor.md. + // The fork-child first SCRUBS the inherited `extra` env pairs in + // place (monitor::wipe_pair: zeroize, then drop — destructors and + // free() in the child), then executes only monitor::run's + // async-signal-safe syscall set (no allocation, no stdio locks, no + // destructors — documented in monitor.rs) and exits via + // _exit/exit_group. The scrub's free()s are sound here because the + // production fork parent is single-threaded at fork, so no malloc + // lock can be held by another thread; under `cargo test` + // (multithreaded) test children fork with no `extra` to scrub. + // rustix deliberately has no fork wrapper; on Linux this is the one + // libc FFI call on the exec path, flagged in + // docs/src/unsafe-code/monitor.md. match unsafe { libc::fork() } { -1 => { // No monitor means no stop semantics and no cleanup on diff --git a/src/monitor.rs b/src/monitor.rs index 740a4a9..0e00d94 100644 --- a/src/monitor.rs +++ b/src/monitor.rs @@ -35,15 +35,20 @@ //! latency, never to the grace cap. //! //! Fork-child discipline (the soundness contract for `launcher.rs`'s -//! `fork`): the fork parent may be multithreaded (it is under -//! `cargo test`), so between fork and exit the monitor performs no -//! allocation and takes no stdio locks — only the async-signal-safe -//! syscall set: signal mask/wait ops, `pidfd_open`/`poll`/`kevent`, -//! `kill`/`pidfd_send_signal`, `unlinkat`, `nanosleep`, raw `write(2)` -//! for diagnostics, and `_exit`/`exit_group`. All inputs (`names`, the -//! dir fd) are allocated pre-fork and moved in. Exit never runs -//! destructors, atexit handlers, or stdio flushes (inherited buffers -//! must not flush twice). +//! `fork`): the production fork parent is single-threaded at fork time, +//! so between fork and exit the monitor performs one bounded exception +//! and otherwise only the async-signal-safe syscall set. The exception: +//! the inherited `extra` env pairs (plaintext in env mode) are scrubbed +//! first — `wipe_pair` zeroizes in place, then drops (destructors and +//! `free()` in the child) — sound only because no other thread exists to +//! hold a malloc lock; under `cargo test` (multithreaded) test children +//! fork with an empty `extra`, so no child ever frees there. Otherwise: +//! no allocation, no stdio locks — only signal mask/wait ops, +//! `pidfd_open`/`poll`/`kevent`, `kill`/`pidfd_send_signal`, `unlinkat`, +//! `nanosleep`, raw `write(2)` for diagnostics, and `_exit`/`exit_group`. +//! All inputs (`names`, the dir fd) are allocated pre-fork and moved in. +//! Exit never runs destructors, atexit handlers, or stdio flushes +//! (inherited buffers must not flush twice). use std::os::fd::{AsFd, OwnedFd}; use std::time::{Duration, Instant}; diff --git a/src/ramdisk.rs b/src/ramdisk.rs index 568103d..e129a6a 100644 --- a/src/ramdisk.rs +++ b/src/ramdisk.rs @@ -1,5 +1,7 @@ //! macOS ramdisk verification — ensures plaintext secret files land only -//! on a RAM-backed HFS disk image owned by the service user. +//! beneath a verified RAM-backed HFS mount: the mount proves RAM-backed +//! via hdiutil, and `secrets_dir` must be contained in it, real (not a +//! symlink), and owned by the service user (sweep 2026-08-07 X1). //! //! This module implements the `ramdiskGuard` invariant that was previously //! templated in `modules/darwin.nix`. On Linux the ramdisk check is not @@ -77,8 +79,21 @@ fn device_is_ram_backed(device: &str, hdiutil_out: &str) -> bool { false } +/// True when `dir` names a path lexically beneath `mount_point` +/// (component-wise, with no `..` escape). Lexical only — the caller has +/// already proven `dir` a real, non-symlink directory and `mount_point` +/// present in mount output (sweep 2026-08-07 X1). +fn path_beneath(dir: &Path, mount_point: &Path) -> bool { + match dir.strip_prefix(mount_point) { + Ok(rest) => !rest + .components() + .any(|c| matches!(c, std::path::Component::ParentDir)), + Err(_) => false, + } +} + /// darwin ramdisk guard (was ramdiskGuard in modules/darwin.nix): plaintext -/// lands only on the postmaster ramdisk, in a directory this user owns. +/// lands only beneath the postmaster ramdisk, in a directory this user owns. pub fn verify_ramdisk(mount_point: &Path, secrets_dir: &Path) -> Result<(), String> { // Trust boundary (audit 2026-08-02 O2): a compromised /sbin/mount or // hdiutil could report persistent disk as the RAM-backed postmaster @@ -140,6 +155,18 @@ pub fn verify_ramdisk(mount_point: &Path, secrets_dir: &Path) -> Result<(), Stri secrets_dir.display() )); } + // Containment (sweep 2026-08-07 X1): the checks above prove the mount + // is the RAM-backed postmaster ramdisk and, independently, that + // secrets_dir is a real euid-owned directory — nothing so far related + // the two. A hand-written config pointing secrets_dir at persistent + // disk would pass both and land plaintext off the ramdisk. + if !path_beneath(secrets_dir, mount_point) { + return Err(format!( + "{}: secrets_dir is not beneath the verified ramdisk mount {}; refusing to write plaintext outside the ramdisk", + secrets_dir.display(), + mount_point.display() + )); + } Ok(()) } @@ -204,4 +231,28 @@ image-type : read/write // Device not in hdiutil output at all assert!(!device_is_ram_backed("/dev/disk99", hdiutil)); } + + #[test] + fn path_beneath_enforces_containment() { + // sweep 2026-08-07 X1: the guard must relate secrets_dir to the + // verified mount, not check each independently. + let mp = Path::new("/private/var/run/postmaster"); + assert!(path_beneath( + Path::new("/private/var/run/postmaster/myapp"), + mp + )); + assert!(path_beneath(mp, mp), "the mount root itself is contained"); + assert!(!path_beneath(Path::new("/private/var/run/other"), mp)); + // Component-wise: a sibling whose name merely shares a prefix is + // NOT contained. + assert!(!path_beneath( + Path::new("/private/var/run/postmaster-evil"), + mp + )); + // `..` escape after a lexical prefix is rejected. + assert!(!path_beneath( + Path::new("/private/var/run/postmaster/../other"), + mp + )); + } } diff --git a/src/secret_files.rs b/src/secret_files.rs index c263f5d..770636c 100644 --- a/src/secret_files.rs +++ b/src/secret_files.rs @@ -212,6 +212,12 @@ pub fn prune_stale(dir: &Path, keep_keys: &[String]) -> Result<(), String> { } for name in &names { let Some(name_str) = name.to_str() else { + // Every other skip in this loop logs; a foreign file with a + // non-UTF8 name must not persist silently (sweep 2026-08-07 X7). + crate::server::log(&format!( + "{}: prune: skipping non-UTF8 entry name", + dir.display() + )); continue; }; // The sentinel is infrastructure, not a secret — never prune it. From 6d83eecf214575478dc3de97ef3323b2789bb86a Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 09:48:52 -0500 Subject: [PATCH 21/47] fix(server): peer_user ACL is never overridden; startup hardening gaps closed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sweep 2026-08-07 (clean-sweep-audit) D1, D2, D4, D8, D9, D10, D11, D14: - --allow-nonroot no longer disables a configured peer_user check: a configured ACL is ALWAYS enforced (root or that uid); the flag only has effect when no peer_user is configured (the dev loop it exists for). Startup logs a note when both are present. Verified no generated config on any platform passes the flag (D1) - bind mode refuses a symlinked socket parent unconditionally — the O_NOFOLLOW fd discipline previously ran only when privileged with a configured peer_user (D2) - preflight rejects empty resolved values naming the key: zero bytes means refusal on the wire, so an empty value could never be fetched — the daemon now fails at startup instead of looking healthy (D4) - socket and keys file paths must be absolute, as the type docs promise (D14) - rustdoc corrections: uid 0 not "PID 1" (D8), listener pairs not triples (D9), run() never returns after serving (D10) - WRITE_TIMEOUT renamed IO_TIMEOUT — fetch_bytes set its read timeout from the write constant (D11) Regression tests: preflight empty-value rejection, relative-path rejection (both legs). 102 lib + 7 exec_check + 18 conformance green; clippy native/release/linux-target, deny, audit, mdbook all green. --- docs/src/reference/cli.md | 2 +- src/cli/mod.rs | 5 +- src/server.rs | 191 +++++++++++++++++++++++++++++++++----- 3 files changed, 170 insertions(+), 28 deletions(-) diff --git a/docs/src/reference/cli.md b/docs/src/reference/cli.md index 19e39b3..7a82bfb 100644 --- a/docs/src/reference/cli.md +++ b/docs/src/reference/cli.md @@ -38,7 +38,7 @@ $ postmaster --config [--bind] [--allow-nonroot] | --- | --- | | `--config ` | Configuration file (required) | | `--bind` | Bind listener sockets even if not socket-activated (macOS) | -| `--allow-nonroot` | Allow non-root connections (dangerous) | +| `--allow-nonroot` | Allow non-root connections (dev escape hatch; never overrides a configured `peer_user` ACL) | On Linux, postmaster is socket-activated: the `postmaster-credd.socket` unit owns the sockets and the daemon inherits them via diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 4b811e0..1fbe643 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -47,7 +47,7 @@ pub struct Entry { pub key: String, /// Additionally allow this (non-root) user to fetch the credential. /// Used by the darwin module, where consumers are launchd daemons - /// connecting as their own service user rather than pid 1. + /// connecting as their own service user rather than uid 0 (root). #[serde(default)] pub peer_user: Option, } @@ -59,7 +59,8 @@ pub struct Args { pub config: PathBuf, /// Bind listener sockets even when not socket-activated. pub bind: bool, - /// Allow non-root peers to connect (dangerous, darwin only). + /// Allow non-root peers to connect (dev escape hatch; never overrides + /// a configured `peer_user` ACL — sweep 2026-08-07 D1). pub allow_nonroot: bool, } diff --git a/src/server.rs b/src/server.rs index f630e27..7c99d57 100644 --- a/src/server.rs +++ b/src/server.rs @@ -23,7 +23,9 @@ use crate::adapter::KeyNaming; use crate::config::{Args, Config, Entry, KeysSource}; use crate::keys::{KeyRing, resolve}; -const WRITE_TIMEOUT: Duration = Duration::from_secs(5); +/// Shared I/O deadline for socket reads and writes (sweep 2026-08-07 +/// D11 — one constant, so the two directions can't silently diverge). +const IO_TIMEOUT: Duration = Duration::from_secs(5); #[cfg(target_os = "linux")] const SD_LISTEN_FDS_START: RawFd = 3; @@ -36,12 +38,12 @@ pub fn log(msg: &str) { } /// Serve a single credential entry on a Unix socket. Handles one peer -/// at a time (thread-per-socket); each peer must be PID 1 or an allowed -/// service user. +/// at a time (thread-per-socket); each peer must be uid 0 (root) or the +/// configured peer_user (sweep 2026-08-07 D8). /// /// Connection limiting (audit 2026-08-02 A25, documented decision): the /// loop is serialized — one connection at a time, each accepted stream -/// closed at the end of its iteration, writes bounded by WRITE_TIMEOUT — +/// closed at the end of its iteration, writes bounded by IO_TIMEOUT — /// so per-connection FDs/threads never accumulate and pending connects /// are bounded by the kernel backlog. A trusted peer (root or the /// configured peer_user) can starve the listener with slow connections; @@ -63,7 +65,11 @@ pub fn serve( continue; } }; - if !allow_nonroot { + // Peer ACL (sweep 2026-08-07 D1): a configured peer_user is + // ALWAYS enforced — --allow-nonroot widens root→configured-user, + // never root→anyone. The flag skips verification only when no + // peer_user is configured (the dev loop it exists for). + if !allow_nonroot || peer_uid.is_some() { match peer_euid(&stream) { Ok(0) => {} Ok(uid) if peer_uid == Some(uid) => {} @@ -77,7 +83,7 @@ pub fn serve( } } } - let _ = stream.set_write_timeout(Some(WRITE_TIMEOUT)); + let _ = stream.set_write_timeout(Some(IO_TIMEOUT)); // Fresh resolution per request: rotation-friendly, nothing cached. match resolve(&entry, &ring, KeyNaming::Env) { Ok(value) => { @@ -129,7 +135,7 @@ pub(crate) fn read_capped(reader: R, path: &Path) -> Result, St pub fn fetch_bytes(path: &Path) -> Result>, String> { let stream = UnixStream::connect(path).map_err(|e| format!("{}: connect: {e}", path.display()))?; - let _ = stream.set_read_timeout(Some(WRITE_TIMEOUT)); + let _ = stream.set_read_timeout(Some(IO_TIMEOUT)); let buf = Zeroizing::new(read_capped(stream, path)?); if buf.is_empty() { return Err(format!( @@ -365,7 +371,8 @@ pub fn keys_path(source: &KeysSource) -> Result { } /// Bind and listen on all configured credential sockets. Returns -/// a vector of `(UnixListener, path, entry)` triples ready for serving. +/// a vector of `(UnixListener, path)` pairs ready for serving (the entry +/// is re-looked-up by the caller; sweep 2026-08-07 D9). pub fn acquire_listeners( cfg: &Config, bind: bool, @@ -378,6 +385,27 @@ pub fn acquire_listeners( for path in cfg.credentials.keys() { let expected = peer_uids.get(path).copied().flatten(); if let Some(parent) = path.parent() { + // Refuse a symlinked socket parent unconditionally in + // bind mode (sweep 2026-08-07 D2): create_dir_all, + // remove_file, and bind all follow a swapped parent, and + // the O_NOFOLLOW fd discipline below only runs when + // privileged with a configured peer_user. + match fs::symlink_metadata(parent) { + Ok(md) if md.file_type().is_symlink() => { + return Err(format!( + "{}: socket parent is a symlink; refusing to follow", + parent.display() + )); + } + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => { + return Err(format!( + "{}: cannot stat socket parent: {e}", + parent.display() + )); + } + } fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; // The parent directory is the filesystem half of the ACL: // owned by the consumer's user, execute-only-for-owner, so @@ -483,9 +511,65 @@ pub fn acquire_listeners( } } +/// Enforce the absoluteness the config type docs promise (sweep 2026-08-07 +/// D14): a CWD-relative socket or keys path would resolve against whatever +/// directory the daemon happened to start in. +fn validate_absolute_paths(cfg: &Config) -> Result<(), String> { + for path in cfg.credentials.keys() { + if !path.is_absolute() { + return Err(format!( + "{}: socket path must be absolute (fail closed)", + path.display() + )); + } + } + if let KeysSource::File(p) = &cfg.keys + && !p.is_absolute() + { + return Err(format!( + "{}: keys file path must be absolute (fail closed)", + p.display() + )); + } + Ok(()) +} + +/// Preflight: prove every credential is servable — and every peer_user +/// resolvable — before accepting anyone. An empty resolved value is +/// unservable (zero bytes means refusal on the wire, sweep 2026-08-07 +/// D4), so it fails here at startup naming the key rather than leaving +/// the daemon looking healthy while the credential permanently fails +/// with a misdiagnosing message. +fn preflight_credentials( + cfg: &Config, + ring: &KeyRing, +) -> Result>, String> { + let mut peer_uids: std::collections::HashMap> = + std::collections::HashMap::new(); + for (path, entry) in &cfg.credentials { + let value = resolve(entry, ring, KeyNaming::Env) + .map_err(|e| format!("preflight {}: {e}", path.display()))?; + if value.is_empty() { + return Err(format!( + "preflight {}: {} resolved to an empty value, which can never be served (zero bytes means refusal on the wire)", + path.display(), + entry.key + )); + } + let uid = entry + .peer_user + .as_deref() + .map(uid_of) + .transpose() + .map_err(|e| format!("preflight {}: {e}", path.display()))?; + peer_uids.insert(path.clone(), uid); + } + Ok(peer_uids) +} + /// Run the credential daemon: harden the process, load keys, bind -/// sockets, and serve credential requests. Returns on socket error -/// or after all connections are drained (if not socket-activated). +/// sockets, and serve credential requests. Runs until the process is +/// terminated; returns only on startup-path failure (sweep 2026-08-07 D10). pub fn run(args: &Args) -> Result<(), String> { let file = fs::File::open(&args.config).map_err(|e| format!("{}: {e}", args.config.display()))?; @@ -495,31 +579,25 @@ pub fn run(args: &Args) -> Result<(), String> { if cfg.credentials.is_empty() { return Err("config maps no credentials; nothing to do".into()); } + validate_absolute_paths(&cfg)?; // The daemon's fetch contract is dotenvx-style env entries only; the // bundle adapter is an exec-mode surface, so the ring requires Env // naming alone here. let ring = Arc::new(KeyRing::load(&keys_path(&cfg.keys)?, &[KeyNaming::Env])?); - // Preflight: prove every credential is servable — and every peer_user - // resolvable — before accepting anyone. - let mut peer_uids: std::collections::HashMap> = - std::collections::HashMap::new(); - for (path, entry) in &cfg.credentials { - resolve(entry, &ring, KeyNaming::Env) - .map_err(|e| format!("preflight {}: {e}", path.display()))?; - let uid = entry - .peer_user - .as_deref() - .map(uid_of) - .transpose() - .map_err(|e| format!("preflight {}: {e}", path.display()))?; - peer_uids.insert(path.clone(), uid); - } + let peer_uids = preflight_credentials(&cfg, &ring)?; log(&format!( "preflight ok: {} credential(s) decryptable", cfg.credentials.len() )); + // --allow-nonroot never overrides a configured peer_user (sweep + // 2026-08-07 D1); say so once at startup when both are present. + if args.allow_nonroot && peer_uids.values().any(Option::is_some) { + log( + "note: --allow-nonroot does not override configured peer_user ACLs — peer_user sockets still verify the connecting uid", + ); + } let listeners = acquire_listeners(&cfg, args.bind, &peer_uids)?; let mut handles = Vec::new(); @@ -610,4 +688,67 @@ mod tests { let id = verified_id_binary().unwrap(); assert!(id.starts_with('/')); } + + #[test] + fn preflight_rejects_empty_resolved_value() { + // sweep 2026-08-07 D4: zero bytes means refusal on the wire, so + // an empty value must fail at startup, not at first fetch. + let dir = std::env::temp_dir().join(format!("pm-preflight-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let env_file = dir.join(".env"); + fs::write(&env_file, "KEY=\n").unwrap(); + let mut credentials = std::collections::HashMap::new(); + credentials.insert( + PathBuf::from("/run/postmaster-credd/svc/KEY.sock"), + Entry { + env_file, + key: "KEY".to_string(), + peer_user: None, + }, + ); + let cfg = Config { + keys: KeysSource::File(dir.join(".env.keys")), + credentials, + }; + let ring = KeyRing::from_pairs( + [( + "DOTENV_PRIVATE_KEY".to_string(), + Zeroizing::new("11".repeat(32)), + )], + &[KeyNaming::Env], + ) + .unwrap(); + let err = preflight_credentials(&cfg, &ring).unwrap_err(); + assert!(err.contains("empty value"), "{err}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn validate_absolute_paths_rejects_relative() { + // sweep 2026-08-07 D14: socket and keys paths must be absolute. + let mut credentials = std::collections::HashMap::new(); + credentials.insert( + PathBuf::from("relative/key.sock"), + Entry { + env_file: PathBuf::from("/x/.env"), + key: "K".to_string(), + peer_user: None, + }, + ); + let cfg = Config { + keys: KeysSource::File(PathBuf::from("/abs/.env.keys")), + credentials, + }; + let err = validate_absolute_paths(&cfg).unwrap_err(); + assert!(err.contains("absolute"), "{err}"); + + // The keys-file leg: a relative keys path is caught too. + let cfg2 = Config { + keys: KeysSource::File(PathBuf::from("rel/.env.keys")), + credentials: std::collections::HashMap::new(), + }; + let err = validate_absolute_paths(&cfg2).unwrap_err(); + assert!(err.contains("absolute"), "{err}"); + } } From 850016b32c98c009188e6c181302c15c231e6bd1 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 09:57:53 -0500 Subject: [PATCH 22/47] refactor(cli): help/usage accuracy, flag-swallow guard, harden only secret paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sweep 2026-08-07 (clean-sweep-audit) D5, D6, D12, D13, D15, D16, D17, D18: - fetch takes --help/-h like every other subcommand (previously "--help" was treated as the socket path and failed at connect) (D5) - value-taking options reject a following flag as the value via a shared option_value helper — exec --config --check no longer parses "--check" as the config path (D6) - HELP_TOP lists cleanup; HELP_SETUP documents the --non-interactive alias (D12, D13) - dropped the dead crate::key_provisioning re-export (zero callers; the other aliases are load-bearing) and the unreferenced USAGE const (D15, D16) - harden_process moved into the dispatch arms: --help/--version and --check no longer harden or print hardening noise; secret-touching arms stay hardened before any decryption and before execvp (D17) - cli module doc covers CLI parsing + config types (D18) Parser regression tests: fetch help (both spellings + the real path), flag-as-value rejection. 104 lib + 7 exec_check + 18 conformance green; clippy native/release/linux-target, deny, audit, mdbook all green. --- src/cli/help.rs | 5 ++- src/cli/mod.rs | 87 +++++++++++++++++++++++++++--------- src/keys/provisioning/mod.rs | 8 ++-- src/lib.rs | 34 ++++++++++---- 4 files changed, 98 insertions(+), 36 deletions(-) diff --git a/src/cli/help.rs b/src/cli/help.rs index b72d5d1..13a4acf 100644 --- a/src/cli/help.rs +++ b/src/cli/help.rs @@ -7,15 +7,17 @@ postmaster --config [--bind] [--allow-nonroot]\n \ postmaster fetch \n \ postmaster exec --config [--check] [--verify-keys] -- [args…]\n \ postmaster setup --config [--recheck] [--unattended] [--force] [--keys-dir ]\n \ +postmaster cleanup --config \n \ postmaster help [subcommand]\n \ postmaster --version\n\n\ SUBCOMMANDS:\n \ exec Decrypt secrets and exec a child process with them injected\n \ fetch Fetch a single secret from a postmaster daemon socket\n \ setup Verify environment, create keys directory, seed keychain (idempotent)\n \ +cleanup Remove plaintext secret files from secrets_dir (ExecStopPost)\n \ help Show help for a subcommand or this message\n\n\ OPTIONS:\n \ ---config Configuration file (required for serve, exec, setup)\n \ +--config Configuration file (required for serve, exec, setup, cleanup)\n \ --bind (serve) Bind listener sockets even if not socket-activated\n \ --allow-nonroot (serve) Allow non-root connections (dangerous)\n \ --check (exec) Validate config shape only, no decryption or exec\n \ @@ -68,6 +70,7 @@ OPTIONS:\n \ --config Exec config JSON (required)\n \ --recheck Verification only — no creation or modification\n \ --unattended Non-interactive mode for automation (fail closed, no prompts)\n \ +--non-interactive Alias for --unattended\n \ --force Re-create or re-seed even if already correct\n \ --keys-dir Override the default keys directory\n\n\ Default keys directory: /var/lib/postmaster (Linux),\n\ diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 1fbe643..e30f65e 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -1,4 +1,5 @@ -//! Configuration parsing and data structures for postmaster. +//! CLI parsing (`Invocation`, `parse_args`, help text) and the +//! configuration data structures for postmaster's daemon and exec modes. //! //! The config is generated by the Nix module as JSON. It contains only //! public information (store paths for ciphertext + key *names*). @@ -128,8 +129,21 @@ pub enum Invocation { /// Crate version, resolved at compile time from `CARGO_PKG_VERSION`. pub const VERSION: &str = env!("CARGO_PKG_VERSION"); -/// Short usage string for error messages. -pub const USAGE: &str = "usage: postmaster --config [--bind] [--allow-nonroot]\n postmaster fetch \n postmaster exec --config [--check] [--verify-keys]\n postmaster exec --config [--verify-keys] -- [args…]\n postmaster setup --config [--recheck] [--unattended] [--force] [--keys-dir ]\n postmaster cleanup --config "; +/// Consume the value of a value-taking option, rejecting another flag as +/// the value (sweep 2026-08-07 D6): `--config --check` must not parse +/// `"--check"` as the config path. +fn option_value( + it: &mut std::iter::Peekable>, + flag: &str, +) -> Result { + match it.next() { + None => Err(format!("error: {flag} requires a path")), + Some(v) if v.starts_with('-') => Err(format!( + "error: {flag} requires a path, got flag `{v}` (missing value?)" + )), + Some(v) => Ok(v), + } +} /// Parse command-line arguments from `std::env::args()`. pub fn parse_args() -> Result { @@ -176,11 +190,19 @@ pub fn parse_args_from(args: impl IntoIterator) -> Result { it.next(); - let path = it.next().ok_or("error: fetch requires a socket path")?; - if it.next().is_some() { - return Err("error: fetch takes exactly one argument (the socket path)".into()); + match it.next() { + // Every subcommand takes --help/-h (sweep 2026-08-07 D5). + Some(a) if a == "--help" || a == "-h" => Ok(Invocation::Help(Some("fetch".into()))), + Some(path) => { + if it.next().is_some() { + return Err( + "error: fetch takes exactly one argument (the socket path)".into() + ); + } + Ok(Invocation::Fetch(PathBuf::from(path))) + } + None => Err("error: fetch requires a socket path".into()), } - Ok(Invocation::Fetch(PathBuf::from(path))) } Some("exec") => { it.next(); @@ -191,9 +213,7 @@ pub fn parse_args_from(args: impl IntoIterator) -> Result { - config = Some(PathBuf::from( - it.next().ok_or("error: --config requires a path")?, - )); + config = Some(PathBuf::from(option_value(&mut it, "--config")?)); } "--check" => check = true, "--verify-keys" => verify_keys = true, @@ -235,17 +255,13 @@ pub fn parse_args_from(args: impl IntoIterator) -> Result { - config = Some(PathBuf::from( - it.next().ok_or("error: --config requires a path")?, - )); + config = Some(PathBuf::from(option_value(&mut it, "--config")?)); } "--recheck" => recheck = true, "--unattended" | "--non-interactive" => unattended = true, "--force" => force = true, "--keys-dir" => { - keys_dir = Some(PathBuf::from( - it.next().ok_or("error: --keys-dir requires a path")?, - )); + keys_dir = Some(PathBuf::from(option_value(&mut it, "--keys-dir")?)); } "--help" | "-h" => return Ok(Invocation::Help(Some("setup".into()))), other => { @@ -270,9 +286,7 @@ pub fn parse_args_from(args: impl IntoIterator) -> Result { - config = Some(PathBuf::from( - it.next().ok_or("error: --config requires a path")?, - )); + config = Some(PathBuf::from(option_value(&mut it, "--config")?)); } "--help" | "-h" => return Ok(Invocation::Help(Some("cleanup".into()))), other => { @@ -294,9 +308,7 @@ pub fn parse_args_from(args: impl IntoIterator) -> Result { - config = Some(PathBuf::from( - it.next().ok_or("error: --config requires a path")?, - )); + config = Some(PathBuf::from(option_value(&mut it, "--config")?)); } "--bind" => bind = true, "--allow-nonroot" => allow_nonroot = true, @@ -527,4 +539,35 @@ mod tests { Ok(Invocation::Help(Some(s))) if s == "cleanup" )); } + + #[test] + fn parse_help_in_fetch_subcommand() { + // sweep 2026-08-07 D5: fetch takes --help/-h like every other + // subcommand (previously "--help" was treated as the socket path). + assert!(matches!( + parse(&["fetch", "--help"]), + Ok(Invocation::Help(Some(s))) if s == "fetch" + )); + assert!(matches!( + parse(&["fetch", "-h"]), + Ok(Invocation::Help(Some(s))) if s == "fetch" + )); + // The real path still parses. + assert!(matches!( + parse(&["fetch", "/run/pm/s.sock"]), + Ok(Invocation::Fetch(p)) if &*p == std::path::Path::new("/run/pm/s.sock") + )); + } + + #[test] + fn parse_rejects_flag_as_option_value() { + // sweep 2026-08-07 D6: a value-taking option must not swallow the + // following flag as its value. + let err = parse(&["exec", "--config", "--check"]).unwrap_err(); + assert!(err.contains("--config"), "{err}"); + assert!(err.contains("--check"), "{err}"); + let err = parse(&["setup", "--keys-dir", "--force", "--config", "/e.json"]).unwrap_err(); + assert!(err.contains("--keys-dir"), "{err}"); + assert!(parse(&["exec", "--config"]).is_err()); + } } diff --git a/src/keys/provisioning/mod.rs b/src/keys/provisioning/mod.rs index 1841816..3970181 100644 --- a/src/keys/provisioning/mod.rs +++ b/src/keys/provisioning/mod.rs @@ -14,11 +14,11 @@ use crate::server::log; mod cleanup; mod setup; -/// The `postmaster cleanup` command, re-exported so -/// `crate::key_provisioning::cleanup` keeps resolving. +/// The `postmaster cleanup` command, re-exported at the crate root for +/// `main()` via lib.rs. pub use cleanup::cleanup; -/// The `postmaster setup` command, re-exported so -/// `crate::key_provisioning::setup` keeps resolving. +/// The `postmaster setup` command, re-exported at the crate root for +/// `main()` via lib.rs. pub use setup::setup; /// Default keys directory path: `/var/lib/postmaster` on Linux, diff --git a/src/lib.rs b/src/lib.rs index d2310c6..00dff1f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,9 +32,6 @@ pub use adapter::bundle; /// The CLI module under its former name, so `crate::config` keeps resolving. pub use cli as config; pub use cli::{Invocation, parse_args, parse_args_from}; -/// Key provisioning under its former name, so `crate::key_provisioning` -/// keeps resolving. -pub use keys::provisioning as key_provisioning; pub use keys::provisioning::{cleanup, setup}; /// Key-source selection under its former name, so `crate::key_source` /// keeps resolving. @@ -43,10 +40,20 @@ pub use server::{fetch, harden_process, run}; /// Re-exported for binary use. The real main is here so tests can call into it. pub fn main() -> std::process::ExitCode { - harden_process(); + // Harden only the arms that can touch secret material (sweep + // 2026-08-07 D17): --help/--version and --check must not print + // hardening noise (e.g. an mlockall failure) for invocations that + // never decrypt. Serve/Exec/Fetch/Setup/Cleanup stay hardened BEFORE + // any decryption and before execvp, exactly as before. let result = match parse_args() { - Ok(Invocation::Serve(args)) => run(&args), - Ok(Invocation::Fetch(path)) => fetch(&path), + Ok(Invocation::Serve(args)) => { + harden_process(); + run(&args) + } + Ok(Invocation::Fetch(path)) => { + harden_process(); + fetch(&path) + } Ok(Invocation::Exec { config, check: true, @@ -57,15 +64,24 @@ pub fn main() -> std::process::ExitCode { check: false, verify_keys, argv, - }) => launcher::exec(&config, &argv, verify_keys), + }) => { + harden_process(); + launcher::exec(&config, &argv, verify_keys) + } Ok(Invocation::Setup { config, recheck, unattended, force, keys_dir, - }) => setup(&config, recheck, unattended, force, keys_dir), - Ok(Invocation::Cleanup { config }) => cleanup(&config), + }) => { + harden_process(); + setup(&config, recheck, unattended, force, keys_dir) + } + Ok(Invocation::Cleanup { config }) => { + harden_process(); + cleanup(&config) + } #[allow(clippy::print_stdout, clippy::print_stderr)] Ok(Invocation::Help(sub)) => { let text = match sub.as_deref() { From f907ff2f82e6ee9e967e32a7fd0fb35dbf221189 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 10:27:04 -0500 Subject: [PATCH 23/47] fix(schema): align exec.schema.json with the parser (bundle_files) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit T1: the public schema drifted from src/exec_config.rs — it pointed its $id at the envelope repo, required env_files for env/files modes, and had no bundle_files property at all, so valid bundle-mode configs failed schema validation. - $id now references beardedeagle/postmaster - add bundle_files property (array of strings, default []) - env/files then-clauses require keys (+ secrets_dir for files) and accept env_files and/or bundle_files non-empty via anyOf, matching validate_decrypting_mode - credentials then-clause rejects bundle_files, matching validate_mode_irrelevant_fields - add docs/examples/exec-bundle.json to the parse-and-validate set - add docs_exec_schema_covers_every_exec_config_field tripwire test so future ExecConfig fields cannot ship without schema coverage Battery: fmt, clippy (debug/release/linux-gnu), test (8 exec_check, full suite green), deny, audit, docs. --- docs/examples/exec-bundle.json | 11 ++++++++++ docs/schema/exec.schema.json | 40 ++++++++++++++++++++++++++++------ tests/exec_check.rs | 35 +++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+), 7 deletions(-) create mode 100644 docs/examples/exec-bundle.json diff --git a/docs/examples/exec-bundle.json b/docs/examples/exec-bundle.json new file mode 100644 index 0000000..29383cf --- /dev/null +++ b/docs/examples/exec-bundle.json @@ -0,0 +1,11 @@ +{ + "mode": "env", + "keys": [ + "environment" + ], + "bundle_files": [ + "/nix/store/example-postmaster-bundle-myapp/secrets.postmaster.bundle.json" + ], + "strict": true, + "overload": false +} diff --git a/docs/schema/exec.schema.json b/docs/schema/exec.schema.json index cefc76e..ebb116d 100644 --- a/docs/schema/exec.schema.json +++ b/docs/schema/exec.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://github.com/beardedeagle/envelope/docs/schema/exec.schema.json", + "$id": "https://github.com/beardedeagle/postmaster/docs/schema/exec.schema.json", "title": "postmaster exec.json", "description": "Public launcher configuration for the current dotenvx-shaped postmaster materialization ABI instance.", "type": "object", @@ -25,6 +25,13 @@ "type": "string" } }, + "bundle_files": { + "type": "array", + "default": [], + "items": { + "type": "string" + } + }, "strict": { "type": "boolean", "default": true @@ -73,16 +80,25 @@ "required": ["mode"] }, "then": { - "required": ["keys", "env_files"], + "required": ["keys"], "properties": { "keys": { "minItems": 1 }, - "env_files": { "minItems": 1 }, "secrets_dir": { "const": null }, "credential_keys": { "maxItems": 0 }, "sockets": { "maxProperties": 0 }, "verify_ramdisk": { "const": null }, "passthrough": { "maxItems": 0 } - } + }, + "anyOf": [ + { + "required": ["env_files"], + "properties": { "env_files": { "minItems": 1 } } + }, + { + "required": ["bundle_files"], + "properties": { "bundle_files": { "minItems": 1 } } + } + ] } }, { @@ -91,14 +107,23 @@ "required": ["mode"] }, "then": { - "required": ["keys", "env_files", "secrets_dir"], + "required": ["keys", "secrets_dir"], "properties": { "keys": { "minItems": 1 }, - "env_files": { "minItems": 1 }, "secrets_dir": { "type": "string" }, "credential_keys": { "maxItems": 0 }, "sockets": { "maxProperties": 0 } - } + }, + "anyOf": [ + { + "required": ["env_files"], + "properties": { "env_files": { "minItems": 1 } } + }, + { + "required": ["bundle_files"], + "properties": { "bundle_files": { "minItems": 1 } } + } + ] } }, { @@ -112,6 +137,7 @@ "credential_keys": { "minItems": 1 }, "keys": { "maxItems": 0 }, "env_files": { "maxItems": 0 }, + "bundle_files": { "maxItems": 0 }, "overload": { "const": false }, "passthrough": { "maxItems": 0 } } diff --git a/tests/exec_check.rs b/tests/exec_check.rs index 5b9c6e8..3a515b2 100644 --- a/tests/exec_check.rs +++ b/tests/exec_check.rs @@ -44,6 +44,7 @@ fn docs_exec_schema_is_valid_json() { fn docs_exec_examples_parse_and_validate() { for rel in [ "docs/examples/exec-env.json", + "docs/examples/exec-bundle.json", "docs/examples/exec-files.json", "docs/examples/exec-credentials-systemd.json", "docs/examples/exec-credentials-darwin.json", @@ -152,3 +153,37 @@ fn exec_check_rejects_path_like_credential_source_names() { let stderr = String::from_utf8_lossy(&out.stderr); assert!(stderr.contains("credential source"), "stderr: {stderr}"); } + +#[test] +fn docs_exec_schema_covers_every_exec_config_field() { + let raw = std::fs::read(fixture("docs/schema/exec.schema.json")).unwrap(); + let schema: serde_json::Value = serde_json::from_slice(&raw).unwrap(); + let properties = schema + .get("properties") + .and_then(serde_json::Value::as_object) + .unwrap(); + // Keep this list in sync with the fields on `ExecConfig` in + // src/exec_config.rs — it is the schema/parser drift tripwire (T1). + for field in [ + "mode", + "keys", + "env_files", + "bundle_files", + "strict", + "overload", + "secrets_dir", + "passthrough", + "credential_keys", + "sockets", + "verify_ramdisk", + ] { + assert!( + properties.contains_key(field), + "schema properties missing {field}" + ); + } + assert_eq!( + schema.get("additionalProperties"), + Some(&serde_json::Value::Bool(false)) + ); +} From 104752c8cde8b76df263e10d4497d3a532e28c91 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 10:44:15 -0500 Subject: [PATCH 24/47] test: regression coverage for audit seams (T3-T16) Close the test-value gaps found in the sweep: real legs that previously passed vacuously, hang guards, hermeticity, and boundary coverage. - T3: conformance fetch loop connects a dummy UnixStream on failure so a regression can't hang the suite on the mock's blocking accept - T4: read_capped boundary test (at-cap passes byte-exact, cap+1 fails) - T5: symlinked env file (unit) and bundle file (conformance) refused end-to-end (A13 O_NOFOLLOW) - T6: files-mode execvp failure leaves only the managed sentinel (A9) - T7: ensure_keys_dir/ensure_keys_file direct coverage (0700 create, mode correction, symlinked-prefix refusal, unattended fail-closed) - T8: conformance env_remove extended (GOOD/BAD/SECRET_GOOD/ DOTENV_PUBLIC_KEY_PRODUCTION/POSTMASTER_SECRETS_DIR) for hermeticity - T9: positive credential-source leg in load_ring - T10: bundle env-precedence, bundle NUL hard error under BOTH strict settings (X6 semantics), files-mode passthrough-NUL cleanup - T11: symlinked secrets_dir refused, target untouched - T12: rename resolve_plaintext_passthrough_with_empty_ring (no rotated keys were involved) - T13: consolidate key_var_for legs into adapter/mod.rs where the mapping lives; drop the keys/exec_config copies - T14: resolve_bundle/decrypt_value missing-ring-entry and invalid base64 legs exercised directly - T15: monitor exits immediately with cleanup when the service is already dead at watch start - T16: tighten credential-skippable assertion to the environment error only, with an ambient-key-var skip guard Battery: fmt, clippy (debug/release/linux-gnu), test (113 lib, 8 exec_check, 24 conformance), deny, audit, docs. --- src/adapter/bundle.rs | 32 +++++++ src/adapter/mod.rs | 13 +++ src/exec_config.rs | 9 -- src/keys/mod.rs | 76 ++++++++++----- src/keys/provisioning/mod.rs | 82 +++++++++++++++++ src/keys/source.rs | 51 ++++++++++- src/monitor.rs | 34 +++++++ src/server.rs | 15 +++ tests/exec_conformance/bundle.rs | 97 ++++++++++++++++++++ tests/exec_conformance/files_mode.rs | 132 +++++++++++++++++++++++++++ tests/exec_conformance/main.rs | 17 +++- 11 files changed, 520 insertions(+), 38 deletions(-) diff --git a/src/adapter/bundle.rs b/src/adapter/bundle.rs index 632dfab..a46c8d8 100644 --- a/src/adapter/bundle.rs +++ b/src/adapter/bundle.rs @@ -405,4 +405,36 @@ mod tests { assert_eq!(resolved[1].0, "KEY_B"); assert_eq!(&resolved[1].1[..], b"value2"); } + + #[test] + fn resolve_bundle_requires_a_postmaster_key_entry() { + // sweep 2026-08-07 T14: a ring built for a different naming (the + // bundle-ring gap's unit-test shape) must fail closed with the + // missing-entry error, never a silent skip or decrypt failure. + let ct = enc("SECRET", "unreachable"); + let bundle = make_bundle(vec![("SECRET", &ct, Encoding::Utf8)]); + let env_only_ring = KeyRing::from_pairs( + [( + "DOTENV_PRIVATE_KEY".to_string(), + zeroize::Zeroizing::new("22".repeat(32)), + )], + &[crate::adapter::KeyNaming::Env], + ) + .unwrap(); + let err = resolve_bundle(&bundle, &env_only_ring, Path::new("/test")).unwrap_err(); + assert!( + err.contains("key ring has no POSTMASTER_KEY entry"), + "{err}" + ); + } + + #[test] + fn resolve_bundle_rejects_invalid_base64() { + // sweep 2026-08-07 T14: malformed base64 in a ciphertext field is + // a hard parse error naming the entry, not a decrypt failure. + let bundle = make_bundle(vec![("SECRET", "!!!not-base64!!!", Encoding::Utf8)]); + let ring = crate::keys::tests::make_test_ring(); + let err = resolve_bundle(&bundle, &ring, Path::new("/test")).unwrap_err(); + assert!(err.contains("SECRET is not valid base64"), "{err}"); + } } diff --git a/src/adapter/mod.rs b/src/adapter/mod.rs index ffbca24..d505845 100644 --- a/src/adapter/mod.rs +++ b/src/adapter/mod.rs @@ -117,6 +117,19 @@ mod tests { .unwrap(), "DOTENV_PRIVATE_KEY_PRODUCTION" ); + assert_eq!( + KeyNaming::Env + .key_var_for(Path::new("/x/.env.staging_v2")) + .unwrap(), + "DOTENV_PRIVATE_KEY_STAGING_V2" + ); + } + + #[test] + fn key_var_for_requires_the_dot_env_convention() { + // Consolidated from the keys/exec_config test copies (sweep + // 2026-08-07 T13): the mapping lives here, so its legs do too. + assert!(KeyNaming::Env.key_var_for(Path::new("no-dot-env")).is_err()); } #[test] diff --git a/src/exec_config.rs b/src/exec_config.rs index bd2ecc3..6f042c7 100644 --- a/src/exec_config.rs +++ b/src/exec_config.rs @@ -278,15 +278,6 @@ fn default_true() -> bool { mod tests { use super::*; - #[test] - fn key_var_for_edge_cases() { - assert!( - KeyNaming::Env - .key_var_for(std::path::Path::new("no-dot-env")) - .is_err() - ); - } - #[test] fn exec_config_parses() { let json = r#"{ diff --git a/src/keys/mod.rs b/src/keys/mod.rs index 13dbeb1..3b8f925 100644 --- a/src/keys/mod.rs +++ b/src/keys/mod.rs @@ -441,29 +441,7 @@ pub mod tests { } #[test] - fn key_var_for_basic() { - assert_eq!( - KeyNaming::Env - .key_var_for(std::path::Path::new(".env")) - .unwrap(), - "DOTENV_PRIVATE_KEY" - ); - assert_eq!( - KeyNaming::Env - .key_var_for(std::path::Path::new(".env.production")) - .unwrap(), - "DOTENV_PRIVATE_KEY_PRODUCTION" - ); - assert_eq!( - KeyNaming::Env - .key_var_for(std::path::Path::new(".env.staging_v2")) - .unwrap(), - "DOTENV_PRIVATE_KEY_STAGING_V2" - ); - } - - #[test] - fn load_rotated_keys_and_plaintext_env() { + fn resolve_plaintext_passthrough_with_empty_ring() { // Create a real .env file with a plaintext value (simulating --plain) let env_dir = std::env::temp_dir(); let env_path = env_dir.join(format!( @@ -723,4 +701,56 @@ pub mod tests { assert!(ring.candidates("DOTENV_PRIVATE_KEY").is_some()); assert!(ring.candidates("DOTENV_PRIVATE_KEYFOO").is_none()); } + + #[test] + fn resolve_all_refuses_symlinked_env_file() { + // sweep 2026-08-07 T5: the O_NOFOLLOW ciphertext open (audit + // 2026-08-02 A13) — a planted symlink at a configured .env path + // is a hard error, never a read-through. + let d = tdir("symlink"); + std::fs::write(d.join(".env.real"), "A=plain\n").unwrap(); + std::os::unix::fs::symlink(d.join(".env.real"), d.join(".env")).unwrap(); + let ring = KeyRing(HashMap::new()); + let err = resolve_all( + &[d.join(".env")], + &ring, + false, + true, + &|_| false, + KeyNaming::Env, + ) + .unwrap_err(); + assert!(err.contains("symlink"), "{err}"); + } + + #[test] + fn decrypt_value_fails_closed_on_bad_base64_and_missing_ring_entry() { + // sweep 2026-08-07 T14: decrypt_value's two fail-closed legs, + // exercised directly (the resolve paths reach them only + // indirectly). + let env_file = Path::new(".env"); + let ring = KeyRing(HashMap::new()); + + // Malformed base64 after the encrypted: prefix → parse error + // naming the file and key, never a decrypt attempt. + let err = decrypt_value( + env_file, + "KEY", + "encrypted:!!!not-base64", + &ring, + KeyNaming::Env, + ) + .unwrap_err(); + assert!(err.contains("KEY is not valid base64"), "{err}"); + + // Well-formed base64 but the ring lacks the file's mapped key + // variable → missing-entry error. + let b64 = BASE64.encode(b"well-formed"); + let raw = format!("encrypted:{b64}"); + let err = decrypt_value(env_file, "KEY", &raw, &ring, KeyNaming::Env).unwrap_err(); + assert!( + err.contains("key ring has no DOTENV_PRIVATE_KEY entry"), + "{err}" + ); + } } diff --git a/src/keys/provisioning/mod.rs b/src/keys/provisioning/mod.rs index 3970181..e1e9bb3 100644 --- a/src/keys/provisioning/mod.rs +++ b/src/keys/provisioning/mod.rs @@ -707,4 +707,86 @@ mod tests { std::env::remove_var(bundle); } } + + #[test] + fn ensure_keys_dir_creates_0700_and_corrects_wide_modes() { + // sweep 2026-08-07 T7: the provisioning primitives had no direct + // coverage — create sets exactly 0700, and a pre-existing 0755 + // dir is corrected in place. + use std::os::unix::fs::PermissionsExt; + // Canonicalize the temp base: on macOS it sits under /var → + // /private/var, and the O5 prefix walk would (correctly) refuse + // the symlinked /var component for reasons unrelated to this test. + let d = fs::canonicalize(std::env::temp_dir()) + .unwrap() + .join(format!("pm-ensure-dir-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + + let created = d.join("new-keys"); + ensure_keys_dir(&created, false).expect("create should succeed"); + let mode = fs::metadata(&created).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o700, "fresh keys dir must be 0700, got {mode:o}"); + + let wide = d.join("wide-keys"); + fs::create_dir_all(&wide).unwrap(); + fs::set_permissions(&wide, fs::Permissions::from_mode(0o755)).unwrap(); + ensure_keys_dir(&wide, false).expect("verify/correct should succeed"); + let mode = fs::metadata(&wide).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o700, "a 0755 keys dir must be corrected to 0700"); + + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn ensure_keys_dir_refuses_a_symlinked_prefix() { + // sweep 2026-08-07 T7 (audit 2026-08-02 O5): create_dir_all + // follows intermediate symlinks, so the prefix walk must refuse + // them before anything is created. + // Canonicalize the temp base (macOS /var → /private/var) so the + // walk reaches OUR planted symlink instead of refusing the + // OS-provided /var component first. + let d = fs::canonicalize(std::env::temp_dir()) + .unwrap() + .join(format!("pm-ensure-dir-link-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + let real = d.join("real"); + fs::create_dir_all(&real).unwrap(); + std::os::unix::fs::symlink(&real, d.join("link")).unwrap(); + + let err = ensure_keys_dir(&d.join("link").join("keys"), false) + .expect_err("a symlinked path component must be refused"); + assert!(err.contains("symlink"), "{err}"); + assert!( + !real.join("keys").exists(), + "nothing may be created through the symlink" + ); + + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn ensure_keys_file_corrects_mode_and_missing_unattended_fails() { + // sweep 2026-08-07 T7: a 0644 keys file is corrected to 0600; a + // missing file in unattended mode fails closed (no prompt). + use std::os::unix::fs::PermissionsExt; + let d = std::env::temp_dir().join(format!("pm-ensure-file-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + let keys = d.join(".env.keys"); + fs::write(&keys, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); + fs::set_permissions(&keys, fs::Permissions::from_mode(0o644)).unwrap(); + + ensure_keys_file(&keys, false, true).expect("verify/correct should succeed"); + let mode = fs::metadata(&keys).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600, "a 0644 keys file must be corrected to 0600"); + + let missing = d.join("absent.keys"); + let err = ensure_keys_file(&missing, false, true) + .expect_err("missing file + unattended must fail closed"); + assert!(err.contains("unattended mode"), "{err}"); + + let _ = fs::remove_dir_all(&d); + } } diff --git a/src/keys/source.rs b/src/keys/source.rs index 84fd5d6..0b9ac87 100644 --- a/src/keys/source.rs +++ b/src/keys/source.rs @@ -117,15 +117,27 @@ mod tests { unsafe { std::env::remove_var("CREDENTIALS_DIRECTORY"); } + // Guard against an ambient valid key var in the test runner's own + // environment (e.g. DOTENV_PRIVATE_KEY exported in CI): with one + // present, the environment source SUCCEEDS and the terminal error + // is unobservable — skip rather than flake (sweep 2026-08-07 T16). + // Only the Env prefix counts here: these namings require Env alone. + let ambient = std::env::vars_os().any(|(k, _)| { + k.to_str() + .is_some_and(|k| crate::keys::is_key_var_name(KeyNaming::Env.key_prefix(), k)) + }); + if ambient { + return; + } let specs = vec![ KeySourceSpec::Credential("nonexistent".to_string()), KeySourceSpec::Environment, ]; let err = load_ring(&specs, &[], &[KeyNaming::Env]).unwrap_err(); - // The error should come from the environment source (terminal), + // The error must come from the environment source (terminal), // proving credential fell through rather than erroring. assert!( - err.contains("environment:") || err.contains("no usable key source"), + err.contains("environment:"), "credential should be skippable; got: {err}" ); } @@ -357,4 +369,39 @@ mod tests { "an unrequired naming must not enter the ring" ); } + + #[test] + fn load_ring_credential_loads_present_file() { + // sweep 2026-08-07 T9: the positive credential leg — a present, + // well-formed credential file loads through the same selection + // path the negative legs reject. + use std::os::unix::fs::PermissionsExt; + let d = std::env::temp_dir().join(format!("pm-keysource-load-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + let cred_dir = d.join("creds"); + fs::create_dir_all(&cred_dir).unwrap(); + let cred = cred_dir.join("dotenv-keys"); + fs::write(&cred, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); + fs::set_permissions(&cred, fs::Permissions::from_mode(0o600)).unwrap(); + + // SAFETY: set_var/remove_var are unsafe on edition 2024 (not + // thread-safe). Serialized via the process-wide ENV_LOCK + // (crate::test_util) shared by every env-mutating test. + let _guard = ENV_LOCK.lock().unwrap(); + unsafe { + std::env::set_var("CREDENTIALS_DIRECTORY", &cred_dir); + } + let ring = load_ring( + &[KeySourceSpec::Credential("dotenv-keys".to_string())], + &[], + &[KeyNaming::Env], + ); + unsafe { + std::env::remove_var("CREDENTIALS_DIRECTORY"); + } + let _ = fs::remove_dir_all(&d); + + let ring = ring.expect("a present credential file must load"); + assert!(ring.candidates("DOTENV_PRIVATE_KEY").is_some()); + } } diff --git a/src/monitor.rs b/src/monitor.rs index 0e00d94..5810768 100644 --- a/src/monitor.rs +++ b/src/monitor.rs @@ -760,4 +760,38 @@ mod tests { assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); } + + /// A service that is ALREADY dead when the monitor starts (death + /// observed on the first tick) must still trigger cleanup and an + /// immediate monitor exit — the monitor must never hang waiting on a + /// process that died before it began watching (sweep 2026-08-07 T15). + #[test] + fn pre_dead_service_triggers_immediate_cleanup_and_exit() { + let dir = tdir("predead"); + let names = write_dummies(&dir); + let mut service = Command::new("sleep").arg("30").spawn().unwrap(); + let service_pid = Pid::from_child(&service); + // Kill AND reap before the monitor starts: a zombie still answers + // kill(pid, 0), so the monitor would correctly see "alive". After + // the reap the pid is gone (ESRCH); reuse inside the test window + // is negligible. + kill_process(service_pid, Signal::KILL).unwrap(); + let status = service.wait().unwrap(); + assert_eq!(status.signal(), Some(libc::SIGKILL)); + + let monitor = fork_monitor( + service_pid, + Some(&dir), + names, + Duration::from_millis(50), + Duration::from_millis(10), + ); + + assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); + assert!( + !dir.join("A").exists() && !dir.join("B").exists(), + "cleanup must run even when the service died before the monitor started" + ); + let _ = fs::remove_dir_all(&dir); + } } diff --git a/src/server.rs b/src/server.rs index 7c99d57..ad200ef 100644 --- a/src/server.rs +++ b/src/server.rs @@ -751,4 +751,19 @@ mod tests { let err = validate_absolute_paths(&cfg2).unwrap_err(); assert!(err.contains("absolute"), "{err}"); } + + #[test] + fn read_capped_passes_at_cap_and_fails_over_cap() { + // sweep 2026-08-07 T4: the A6 cap boundary itself — an at-cap + // read passes byte-exact; one byte over fails rather than + // truncates (a truncated secret must never be served whole). + let at_cap = std::io::repeat(0x41).take(MAX_READ_BYTES); + let got = read_capped(at_cap, Path::new("/test")).unwrap(); + assert_eq!(got.len() as u64, MAX_READ_BYTES); + assert!(got.iter().all(|b| *b == 0x41)); + + let over_cap = std::io::repeat(0x41).take(MAX_READ_BYTES + 1); + let err = read_capped(over_cap, Path::new("/test")).unwrap_err(); + assert!(err.contains("size cap"), "{err}"); + } } diff --git a/tests/exec_conformance/bundle.rs b/tests/exec_conformance/bundle.rs index cabb95f..a5c64bf 100644 --- a/tests/exec_conformance/bundle.rs +++ b/tests/exec_conformance/bundle.rs @@ -123,3 +123,100 @@ fn mixed_env_and_bundle_exec_resolves_both_adapters() { assert_eq!(std::fs::read(d.join("secret.out")).unwrap(), b"from-bundle"); assert_eq!(std::fs::read(d.join("plain.out")).unwrap(), val.as_bytes()); } + +#[test] +fn bundle_exec_refuses_symlinked_bundle_file() { + // sweep 2026-08-07 T5: the O_NOFOLLOW open on bundle ciphertext + // (audit 2026-08-02 A13) must hold end-to-end — a planted symlink at + // a configured bundle path is a hard error, never a read-through. + let d = common::tmpdir("bundle-symlink"); + let bundle = write_bundle(&d, &[("SECRET", "unreachable")]); + let keys = write_keys(&d, false); + let link = d.join("linked.bundle.json"); + std::os::unix::fs::symlink(&bundle, &link).unwrap(); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"bundle_files":["{}"]}}"#, + keys.display(), + link.display() + ), + ); + let out = run_exec(&cfg, "true", &[]); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("symlink"), "stderr: {stderr}"); +} + +#[test] +fn bundle_env_precedence_matches_env_adapter() { + // sweep 2026-08-07 T10: bundle entries follow the same precedence + // contract as .env values — the process environment wins unless + // overload. + let d = common::tmpdir("bundle-prec"); + let bundle = write_bundle(&d, &[("SECRET", "from-bundle")]); + let keys = write_keys(&d, false); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"bundle_files":["{}"],"overload":false}}"#, + keys.display(), + bundle.display() + ), + ); + let sh = format!("printf %s \"$SECRET\" > '{d}'/out1", d = d.display()); + let out = run_exec(&cfg, &sh, &[("SECRET", "preset")]); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(std::fs::read(d.join("out1")).unwrap(), b"preset"); + + let cfg_overload = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"bundle_files":["{}"],"overload":true}}"#, + keys.display(), + bundle.display() + ), + ); + let sh2 = format!("printf %s \"$SECRET\" > '{d}'/out2", d = d.display()); + let out2 = run_exec(&cfg_overload, &sh2, &[("SECRET", "preset")]); + assert!( + out2.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out2.stderr) + ); + assert_eq!(std::fs::read(d.join("out2")).unwrap(), b"from-bundle"); +} + +#[test] +fn bundle_nul_value_is_a_hard_error_under_any_strictness() { + // sweep 2026-08-07 T10 (X6): an env-bound bundle value containing NUL + // is a HARD error — one rule for every env-bound value. strict:false + // must NOT skip it the way it skips undecryptable values. + let d = common::tmpdir("bundle-nul"); + let bundle = write_bundle(&d, &[("SECRET", "before\0after")]); + let keys = write_keys(&d, false); + for strict in [true, false] { + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"env","keys":[{{"file":"{}"}}],"bundle_files":["{}"],"strict":{strict}}}"#, + keys.display(), + bundle.display() + ), + ); + let out = run_exec(&cfg, "true", &[]); + assert!( + !out.status.success(), + "strict:{strict} must still fail closed on a NUL value" + ); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("NUL byte"), + "strict:{strict} stderr: {stderr}" + ); + } +} diff --git a/tests/exec_conformance/files_mode.rs b/tests/exec_conformance/files_mode.rs index 906fc92..05783bd 100644 --- a/tests/exec_conformance/files_mode.rs +++ b/tests/exec_conformance/files_mode.rs @@ -139,6 +139,13 @@ fn credentials_mode_fetch_loop() { sd = secrets_dir.display() ); let out = run_exec(&cfg, &sh, &[]); + if !out.status.success() { + // Hang guard (sweep 2026-08-07 T3): a regression that fails + // before connecting would leave the mock parked in accept() and + // the join below would hang the whole suite. Nudge the listener + // with a dummy connection so the thread can finish. + let _ = std::os::unix::net::UnixStream::connect(&sock); + } server.join().unwrap(); assert!( out.status.success(), @@ -158,3 +165,128 @@ fn credentials_mode_fetch_loop() { "the sibling monitor must remove plaintext files on service death" ); } + +#[test] +fn files_mode_exec_failure_leaves_only_the_sentinel() { + // sweep 2026-08-07 T6: an execvp failure (audit 2026-08-02 A9) must + // unwind the plaintext writes — after a failed exec the secrets dir + // holds ONLY the managed sentinel, never secret files. + let d = common::tmpdir("files-execfail"); + let secrets_dir = d.join("secrets"); + std::fs::create_dir_all(&secrets_dir).unwrap(); + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + format!("SECRET=\"{}\"", common::enc("exec-fail-secret")), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"files","keys":[{{"file":"{}"}}],"env_files":["{}"],"secrets_dir":"{}"}}"#, + keys.display(), + env.display(), + secrets_dir.display() + ), + ); + let mut c = Command::new(env!("CARGO_BIN_EXE_postmaster")); + c.args(["exec", "--config"]) + .arg(&cfg) + .args(["--", "/nonexistent-pm-binary"]) + .env_remove("SECRET"); + let out = c.output().unwrap(); + assert!(!out.status.success()); + + let leftovers: Vec = std::fs::read_dir(&secrets_dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!( + leftovers, + vec![postmaster::secret_files::MANAGED_SENTINEL.to_string()], + "only the managed sentinel may survive a failed exec" + ); +} + +#[test] +fn files_mode_passthrough_nul_fails_closed_with_cleanup() { + // sweep 2026-08-07 T10: a passthrough value containing NUL cannot + // become an env var — fail closed AND unwind the secret file that + // was already written for it. + let d = common::tmpdir("files-ptnul"); + let secrets_dir = d.join("secrets"); + std::fs::create_dir_all(&secrets_dir).unwrap(); + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + format!("SECRET=\"{}\"", common::enc("before\0after")), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"files","keys":[{{"file":"{}"}}],"env_files":["{}"],"secrets_dir":"{}","passthrough":["SECRET"]}}"#, + keys.display(), + env.display(), + secrets_dir.display() + ), + ); + let out = run_exec(&cfg, "true", &[]); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("passthrough value contains NUL"), + "stderr: {stderr}" + ); + assert!( + !secrets_dir.join("SECRET").exists(), + "the written secret file must be unwound on the passthrough-NUL failure" + ); +} + +#[test] +fn files_mode_refuses_symlinked_secrets_dir() { + // sweep 2026-08-07 T11: a symlinked secrets_dir is a hard error + // before any plaintext is written — and the link target stays + // untouched. + let d = common::tmpdir("files-dirlink"); + let real = d.join("real-secrets"); + std::fs::create_dir_all(&real).unwrap(); + let link = d.join("linked-secrets"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + format!("SECRET=\"{}\"", common::enc("unreachable")), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + let cfg = write_config( + &d, + &format!( + r#"{{"mode":"files","keys":[{{"file":"{}"}}],"env_files":["{}"],"secrets_dir":"{}"}}"#, + keys.display(), + env.display(), + link.display() + ), + ); + let out = run_exec(&cfg, "true", &[]); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("secrets_dir is a symlink"), + "stderr: {stderr}" + ); + assert!( + std::fs::read_dir(&real).unwrap().next().is_none(), + "the symlink target must stay untouched" + ); +} diff --git a/tests/exec_conformance/main.rs b/tests/exec_conformance/main.rs index cc4d9a4..b6a8f6c 100644 --- a/tests/exec_conformance/main.rs +++ b/tests/exec_conformance/main.rs @@ -70,12 +70,21 @@ fn run_exec(config: &Path, sh: &str, envs: &[(&str, &str)]) -> std::process::Out c.args(["exec", "--config"]) .arg(config) .args(["--", "/bin/sh", "-c", sh]) - // Hermeticity: an ambient SECRET/PLAIN/A in the test runner's own - // environment would flip the precedence-test outcomes below, since - // these are exactly the value-variable names the suite asserts on. + // Hermeticity: an ambient SECRET/PLAIN/A/GOOD/BAD/SECRET_GOOD in + // the test runner's own environment would flip the precedence-test + // outcomes below, since these are exactly the value-variable names + // the suite asserts on. DOTENV_PUBLIC_KEY_PRODUCTION and + // POSTMASTER_SECRETS_DIR are asserted ABSENT in the child; an + // ambient copy would be inherited and flake those assertions + // (sweep 2026-08-07 T8). .env_remove("SECRET") .env_remove("PLAIN") - .env_remove("A"); + .env_remove("A") + .env_remove("GOOD") + .env_remove("BAD") + .env_remove("SECRET_GOOD") + .env_remove("DOTENV_PUBLIC_KEY_PRODUCTION") + .env_remove("POSTMASTER_SECRETS_DIR"); for (k, v) in envs { c.env(k, v); } From 866883a942e0a0ac11181e6ebef5b59b4659c6f3 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 11:33:18 -0500 Subject: [PATCH 25/47] fix(server): darwin socket perms via bind-time umask (T2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The T2 daemon end-to-end conformance test caught a real Darwin breakage: acquire_listeners fchmod()s the freshly bound socket fd (audit finding #7's anti-TOCTOU fix), but fchmod(2) rejects socket fds with EINVAL on Darwin — every --bind startup failed. A path chmod was not an option: it would reopen the #7 window (a swapped-in symlink redirecting the chmod to an attacker-chosen file). On darwin, flip the process umask around the bind instead (RAII UmaskGuard): the socket is born with the intended mode (0600, or 0666 with a configured peer_user), so there is no window at all. The flip is race-free — run() spawns the serve threads only after acquire_listeners returns, so the process is single-threaded at bind time. Linux keeps the fd-based fchmod unchanged. New tests/exec_conformance/daemon.rs drives the real binary: - daemon_serves_a_real_fetch_roundtrip: --bind --allow-nonroot as the test user, live-connect probe, socket mode asserted 0600, real roundtrip byte-exact - daemon_preflight_refuses_an_empty_credential_at_startup: D4's empty-value refusal happens before any socket is bound Battery: fmt, clippy (debug/release/linux-gnu), test (113 lib, 8 exec_check, 26 conformance), deny, audit, docs. --- src/server.rs | 52 ++++++++++- tests/exec_conformance/daemon.rs | 150 +++++++++++++++++++++++++++++++ tests/exec_conformance/main.rs | 1 + 3 files changed, 201 insertions(+), 2 deletions(-) create mode 100644 tests/exec_conformance/daemon.rs diff --git a/src/server.rs b/src/server.rs index ad200ef..fae3670 100644 --- a/src/server.rs +++ b/src/server.rs @@ -370,6 +370,42 @@ pub fn keys_path(source: &KeysSource) -> Result { } } +/// RAII guard that sets the process umask so a bound unix socket is born +/// with `mode` (sockets are created `0777 & ~umask`) and restores the +/// prior mask on drop. Darwin-only: Linux fchmod()s the already-bound +/// socket fd (audit finding #7), which Darwin cannot do — fchmod(2) +/// rejects socket fds with EINVAL (found by the T2 end-to-end +/// conformance test, sweep 2026-08-07) — and a path chmod would reopen +/// the #7 TOCTOU (a swapped-in symlink redirecting the chmod to an +/// attacker-chosen file). Being born with the right mode has no window +/// at all. +#[cfg(target_os = "macos")] +#[derive(Debug)] +struct UmaskGuard(libc::mode_t); + +#[cfg(target_os = "macos")] +impl UmaskGuard { + fn around_bind(mode: u32) -> Self { + let mask = (!mode & 0o777) as libc::mode_t; + // SAFETY: umask(2) cannot fail and has no memory-safety surface. + // The call site is single-threaded (run() spawns the serve + // threads only after acquire_listeners returns), so the + // process-wide flip cannot race. + Self(unsafe { libc::umask(mask) }) + } +} + +#[cfg(target_os = "macos")] +impl Drop for UmaskGuard { + fn drop(&mut self) { + // SAFETY: restoring the mask captured at construction; same + // single-threaded window and no-failure contract as above. + unsafe { + libc::umask(self.0); + } + } +} + /// Bind and listen on all configured credential sockets. Returns /// a vector of `(UnixListener, path)` pairs ready for serving (the entry /// is re-looked-up by the caller; sweep 2026-08-07 D9). @@ -378,6 +414,7 @@ pub fn acquire_listeners( bind: bool, peer_uids: &std::collections::HashMap>, ) -> Result, String> { + #[cfg(not(target_os = "macos"))] use std::os::fd::AsFd; if bind { let am_root = rustix::process::geteuid().is_root(); @@ -438,17 +475,28 @@ pub fn acquire_listeners( } } let _ = fs::remove_file(path); - let l = - UnixListener::bind(path).map_err(|e| format!("{}: bind: {e}", path.display()))?; // connect(2) needs write on the socket inode; the reachability // gate is the 0500 parent dir plus the peer-credential check. let mode = if expected.is_some() { 0o666 } else { 0o600 }; + // Darwin has no fchmod(2) for socket fds (EINVAL — found by + // the T2 end-to-end conformance test, sweep 2026-08-07), and + // a path chmod would reopen the audit-#7 TOCTOU the fchmod + // below closes. Flip the process umask around the bind + // instead: the socket is born with `mode`, so there is no + // window at all. The process is single-threaded here — run() + // spawns the serve threads only after acquire_listeners + // returns — so the process-wide flip is race-free. + #[cfg(target_os = "macos")] + let _umask_guard = UmaskGuard::around_bind(mode); + let l = + UnixListener::bind(path).map_err(|e| format!("{}: bind: {e}", path.display()))?; // Audit finding #7: use fchmod on the socket fd instead of // set_permissions on the path to eliminate a TOCTOU between // bind and chmod. Between those two path operations an attacker // with directory write access could unlink the socket and // create a symlink. fchmod operates on the already-bound fd, // which is the socket inode we just created. + #[cfg(not(target_os = "macos"))] rustix::fs::fchmod(l.as_fd(), rustix::fs::Mode::from_bits_truncate(mode)) .map_err(|e| format!("{}: fchmod: {e}", path.display()))?; out.push((l, path.clone())); diff --git a/tests/exec_conformance/daemon.rs b/tests/exec_conformance/daemon.rs new file mode 100644 index 0000000..846fbaa --- /dev/null +++ b/tests/exec_conformance/daemon.rs @@ -0,0 +1,150 @@ +//! Daemon end-to-end conformance (sweep 2026-08-07 T2): the real binary +//! in serve mode, a real bound socket, and the real fetch client — the +//! serve/fetch roundtrip and the startup preflight refusal, which the +//! unit tests only exercise in-process. + +use std::process::Command; +use std::time::{Duration, Instant}; + +use crate::common; + +/// Kill the daemon on drop (panic paths included) so a failed assertion +/// can't leak a serving process. +struct KillOnDrop(Option); + +impl Drop for KillOnDrop { + fn drop(&mut self) { + if let Some(mut c) = self.0.take() { + let _ = c.kill(); + let _ = c.wait(); + } + } +} + +/// Wait for the daemon's socket to accept connections (the file existing +/// is not enough — a dead daemon leaves the socket file behind), bailing +/// early with the daemon's stderr if the process exits first. +fn wait_for_socket( + daemon: &mut std::process::Child, + sock: &std::path::Path, + timeout: Duration, +) -> Result<(), String> { + use std::io::Read as _; + let deadline = Instant::now() + timeout; + while Instant::now() < deadline { + // A successful connect means a live listener. The probe is itself + // served like a fetch (one serialized connection) and dropped. + if std::os::unix::net::UnixStream::connect(sock).is_ok() { + return Ok(()); + } + if let Some(status) = daemon.try_wait().map_err(|e| e.to_string())? { + let mut stderr = String::new(); + if let Some(mut h) = daemon.stderr.take() { + let _ = h.read_to_string(&mut stderr); + } + return Err(format!("daemon exited before binding ({status}): {stderr}")); + } + std::thread::sleep(Duration::from_millis(10)); + } + Err(format!( + "daemon did not accept on {} within {timeout:?}", + sock.display() + )) +} + +#[test] +fn daemon_serves_a_real_fetch_roundtrip() { + let d = common::tmpdir("daemon"); + let env = common::write_env_file( + &d, + ".env.production", + &[ + format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), + format!("DB_URL=\"{}\"", common::enc("postgres://real-roundtrip")), + ], + ); + let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); + // Bound directly under the tmpdir: unix socket paths are length-capped + // (104 bytes on darwin), and the tmpdir path is already long. + let sock = d.join("DB_URL.sock"); + let cfg = d.join("daemon.json"); + std::fs::write( + &cfg, + format!( + r#"{{"keys":{{"file":"{}"}},"credentials":{{"{}":{{"env_file":"{}","key":"DB_URL"}}}}}}"#, + keys.display(), + sock.display(), + env.display() + ), + ) + .unwrap(); + + // The suite runs as the test user: --bind (no systemd activation + // here) and --allow-nonroot (the peer ACL's root-only default would + // refuse our own fetch otherwise; no peer_user is configured). + let daemon = Command::new(env!("CARGO_BIN_EXE_postmaster")) + .args(["--config"]) + .arg(&cfg) + .args(["--bind", "--allow-nonroot"]) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let mut guard = KillOnDrop(Some(daemon)); + wait_for_socket(guard.0.as_mut().unwrap(), &sock, Duration::from_secs(10)).unwrap(); + + // The bind-time permission contract (audit finding #7; umask-borne on + // darwin, fchmod on Linux): no peer_user configured → owner-only. + use std::os::unix::fs::PermissionsExt as _; + let mode = std::fs::metadata(&sock).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600, "socket must be owner-only, got {mode:o}"); + + let out = Command::new(env!("CARGO_BIN_EXE_postmaster")) + .arg("fetch") + .arg(&sock) + .output() + .unwrap(); + assert!( + out.status.success(), + "fetch stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(out.stdout, b"postgres://real-roundtrip"); +} + +#[test] +fn daemon_preflight_refuses_an_empty_credential_at_startup() { + // sweep 2026-08-07 D4 end-to-end: an empty resolved value can never + // be served (zero bytes means refusal on the wire), so the daemon + // must fail at STARTUP naming the key, not look healthy while every + // fetch comes back empty. + let d = common::tmpdir("daemonpre"); + let env = common::write_env_file(&d, ".env", &["EMPTY=".to_string()]); + let keys = common::write_keys_file(&d, "", &[common::TEST_SK_HEX]); + let sock = d.join("EMPTY.sock"); + let cfg = d.join("daemon.json"); + std::fs::write( + &cfg, + format!( + r#"{{"keys":{{"file":"{}"}},"credentials":{{"{}":{{"env_file":"{}","key":"EMPTY"}}}}}}"#, + keys.display(), + sock.display(), + env.display() + ), + ) + .unwrap(); + + // Startup fails before any bind, so output() returns promptly. + let out = Command::new(env!("CARGO_BIN_EXE_postmaster")) + .args(["--config"]) + .arg(&cfg) + .args(["--bind", "--allow-nonroot"]) + .output() + .unwrap(); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("empty value"), "stderr: {stderr}"); + assert!( + !sock.exists(), + "a preflight refusal must happen before any socket is bound" + ); +} diff --git a/tests/exec_conformance/main.rs b/tests/exec_conformance/main.rs index b6a8f6c..f1c10e1 100644 --- a/tests/exec_conformance/main.rs +++ b/tests/exec_conformance/main.rs @@ -3,6 +3,7 @@ mod bundle; #[path = "../common/mod.rs"] mod common; +mod daemon; mod env_mode; mod files_mode; mod keys_verify; From a2f2318dc3d36aea4fabb0999032aab2a1a9d7c5 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 11:35:39 -0500 Subject: [PATCH 26/47] refactor(monitor): extract tests to src/monitor/tests.rs (X8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit monitor.rs was 797 lines with the test half inline — the production half (the async-signal-safe code under the LOC watch) was hard to read end-to-end. The tests move verbatim to src/monitor/tests.rs under the same module path (monitor::tests) with the same crate-internal visibility; monitor.rs drops to 503 lines. No test content changed beyond dedent. Battery: fmt, clippy (debug/release/linux-gnu), test (113 lib, 8 exec_check, 26 conformance), deny, audit, docs. --- src/monitor.rs | 303 +------------------------------------------ src/monitor/tests.rs | 301 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 305 insertions(+), 299 deletions(-) create mode 100644 src/monitor/tests.rs diff --git a/src/monitor.rs b/src/monitor.rs index 5810768..28534db 100644 --- a/src/monitor.rs +++ b/src/monitor.rs @@ -495,303 +495,8 @@ fn take_pending_stop(set: &libc::sigset_t) -> Option { #[cfg(not(any(target_os = "linux", target_os = "macos")))] compile_error!("postmaster's sibling monitor supports Linux and macOS only"); +// Tests live in monitor/tests.rs (sweep 2026-08-07 X8): the +// production half stays readable at ~500 lines; the test half keeps +// the same module path (monitor::tests) and crate-internal access. #[cfg(test)] -#[allow(clippy::unwrap_used, clippy::panic)] -mod tests { - use super::*; - use std::fs; - use std::os::unix::process::ExitStatusExt; - use std::path::{Path, PathBuf}; - use std::process::Command; - - use rustix::process::{WaitOptions, waitpid}; - - use crate::launcher::TerminationGuard; - use crate::secret_files::open_secrets_dir; - - fn tdir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("pm-monitor-{tag}-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); - d - } - - /// Fork a monitor watching `service_pid`, mirroring the production - /// launcher: the calling thread blocks the stop signals first (the - /// child is born with them blocked — no ready-race between fork and - /// the monitor's own block), the fork-child runs the REAL monitor - /// loop with test-scaled timing, the parent restores its mask and - /// returns the monitor's pid. - fn fork_monitor( - service_pid: Pid, - dir: Option<&Path>, - names: Vec, - grace: Duration, - poll_interval: Duration, - ) -> Pid { - let guard = TerminationGuard::block(); - let dir_fd = dir.map(|d| open_secrets_dir(d).unwrap()); - // SAFETY: fork(2) in the test process. The child executes only - // run_inner — documented async-signal-safe discipline: no - // allocation, no stdio locks, raw syscalls only — and then exits - // via _exit/exit_group, so the multithreaded test harness's - // malloc locks and output buffers are never touched in the child. - match unsafe { libc::fork() } { - -1 => panic!("fork: {}", std::io::Error::last_os_error()), - 0 => { - // Never returns (`-> !`), so the guard is never dropped - // and the mask stays blocked for the monitor's life - // (run_inner re-asserts it regardless). - run_inner(service_pid, dir_fd, names, grace, poll_interval); - } - child => { - guard.restore_mask(); - Pid::from_raw(child).unwrap() - } - } - } - - /// Reap the monitor, asserting it exits 0 within `timeout`. On - /// timeout the monitor is SIGKILLed and reaped so a regression fails - /// the test instead of hanging the suite. - fn wait_monitor_exit(pid: Pid, timeout: Duration) -> i32 { - let deadline = Instant::now() + timeout; - loop { - match waitpid(Some(pid), WaitOptions::NOHANG).unwrap() { - Some((_, status)) => { - if let Some(sig) = status.terminating_signal() { - panic!("monitor died by signal {sig}"); - } - return status.exit_status().unwrap_or(-1); - } - None => { - if Instant::now() >= deadline { - let _ = kill_process(pid, Signal::KILL); - let _ = waitpid(Some(pid), WaitOptions::empty()); - panic!("monitor did not exit within {timeout:?}"); - } - std::thread::sleep(Duration::from_millis(5)); - } - } - } - } - - fn write_dummies(dir: &Path) -> Vec { - fs::write(dir.join("A"), b"secret-a").unwrap(); - fs::write(dir.join("B"), b"secret-b").unwrap(); - vec!["A".to_string(), "B".to_string()] - } - - /// Reaps a forked/spawned pid on drop (SIGKILL first) so a failed - /// assertion can't leak a stray service process — important for the - /// TERM-ignoring service, which would otherwise outlive the test - /// binary indefinitely. - struct ReapOnDrop(Pid); - - impl Drop for ReapOnDrop { - fn drop(&mut self) { - let _ = kill_process(self.0, Signal::KILL); - let _ = waitpid(Some(self.0), WaitOptions::empty()); - } - } - - /// Fork a "service" that ignores SIGTERM until SIGKILLed: a - /// fork-child that sets TERM to SIG_IGN and pause()s forever. This - /// exercises the grace → SIGKILL escalation deterministically, unlike - /// a shell `trap` — macOS /bin/sh resets TERM for exec'd commands, - /// so the disposition doesn't survive into `sleep` there. - fn fork_term_ignoring_service() -> Pid { - // SAFETY: fork(2) in the test process; the child executes only - // async-signal-safe calls (signal(2), pause(2)) and never returns - // into the test harness — no allocation, no stdio, no locks. - match unsafe { libc::fork() } { - -1 => panic!("fork: {}", std::io::Error::last_os_error()), - 0 => unsafe { - // SAFETY: plain single-threaded signal op on this - // process; SIG_IGN is the documented ignore-disposition - // constant. pause(2) suspends until a caught signal - // arrives; TERM is ignored, so only SIGKILL ends the loop. - libc::signal(libc::SIGTERM, libc::SIG_IGN); - loop { - libc::pause(); - } - }, - child => Pid::from_raw(child).unwrap(), - } - } - - /// Service death NOT mediated by the monitor (kill -9 / crash - /// stand-in) must still trigger cleanup and monitor exit. - #[test] - fn natural_service_death_triggers_cleanup_and_monitor_exit() { - let dir = tdir("natural"); - let names = write_dummies(&dir); - let mut service = Command::new("sleep").arg("30").spawn().unwrap(); - let service_pid = Pid::from_child(&service); - let _reap = ReapOnDrop(service_pid); - let monitor = fork_monitor( - service_pid, - Some(&dir), - names, - Duration::from_millis(50), - Duration::from_millis(10), - ); - - assert!(dir.join("A").exists()); - kill_process(service_pid, Signal::KILL).unwrap(); - let status = service.wait().unwrap(); - assert_eq!(status.signal(), Some(libc::SIGKILL)); - - assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); - assert!( - !dir.join("A").exists() && !dir.join("B").exists(), - "monitor must remove the plaintext files on service death" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// A stop signal to the monitor is forwarded to the service; death - /// follows within the grace (no SIGKILL escalation needed), then - /// cleanup runs and the monitor exits 0. The monitor is born with - /// the signal blocked, so the TERM pends until its first tick — - /// no settle sleep is needed. - #[test] - fn stop_signal_is_forwarded_then_grace_then_cleanup() { - let dir = tdir("forward"); - let names = write_dummies(&dir); - let mut service = Command::new("sleep").arg("30").spawn().unwrap(); - let service_pid = Pid::from_child(&service); - let _reap = ReapOnDrop(service_pid); - let monitor = fork_monitor( - service_pid, - Some(&dir), - names, - Duration::from_millis(500), - Duration::from_millis(10), - ); - - kill_process(monitor, Signal::TERM).unwrap(); - - assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); - let status = service.wait().unwrap(); - assert_eq!( - status.signal(), - Some(libc::SIGTERM), - "the service must die by the forwarded TERM, not by an escalated SIGKILL" - ); - assert!( - !dir.join("A").exists() && !dir.join("B").exists(), - "cleanup must run before the monitor exits" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// A service that ignores SIGTERM is SIGKILLed only after the grace - /// elapses; cleanup still runs and the monitor exits 0. - #[test] - fn term_ignoring_service_is_sigkilled_after_grace() { - let dir = tdir("grace"); - let names = write_dummies(&dir); - let service_pid = fork_term_ignoring_service(); - let _reap = ReapOnDrop(service_pid); - let grace = Duration::from_millis(50); - let monitor = fork_monitor( - service_pid, - Some(&dir), - names, - grace, - Duration::from_millis(10), - ); - - let start = Instant::now(); - kill_process(monitor, Signal::TERM).unwrap(); - - assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); - let Some((_, status)) = waitpid(Some(service_pid), WaitOptions::empty()).unwrap() else { - panic!("blocking waitpid returned no status"); - }; - assert_eq!( - status.terminating_signal(), - Some(libc::SIGKILL), - "a TERM-ignoring service must be SIGKILLed" - ); - assert!( - start.elapsed() >= grace, - "SIGKILL must not come before the grace elapses" - ); - assert!( - !dir.join("A").exists() && !dir.join("B").exists(), - "cleanup must run after the SIGKILL path" - ); - let _ = fs::remove_dir_all(&dir); - } - - /// The inherited-heap scrub (threat model): both buffers of an env - /// pair must come back fully wiped. - #[test] - fn wipe_pair_scrubs_both_buffers() { - let (k, v) = wipe_pair( - std::ffi::OsString::from("SECRET_NAME"), - std::ffi::OsString::from("s3cr3t-value"), - ); - assert!(k.iter().all(|b| *b == 0), "name buffer not wiped"); - assert!(v.iter().all(|b| *b == 0), "value buffer not wiped"); - } - - /// Uniform semantics (design decision 4): the monitor runs even in - /// env mode — no dir fd, an empty name list, cleanup a no-op — and - /// still exits when the service dies. - #[test] - fn env_mode_monitor_with_no_files_exits_on_service_death() { - let mut service = Command::new("sleep").arg("30").spawn().unwrap(); - let service_pid = Pid::from_child(&service); - let _reap = ReapOnDrop(service_pid); - let monitor = fork_monitor( - service_pid, - None, - Vec::new(), - Duration::from_millis(50), - Duration::from_millis(10), - ); - - kill_process(service_pid, Signal::TERM).unwrap(); - let status = service.wait().unwrap(); - assert_eq!(status.signal(), Some(libc::SIGTERM)); - - assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); - } - - /// A service that is ALREADY dead when the monitor starts (death - /// observed on the first tick) must still trigger cleanup and an - /// immediate monitor exit — the monitor must never hang waiting on a - /// process that died before it began watching (sweep 2026-08-07 T15). - #[test] - fn pre_dead_service_triggers_immediate_cleanup_and_exit() { - let dir = tdir("predead"); - let names = write_dummies(&dir); - let mut service = Command::new("sleep").arg("30").spawn().unwrap(); - let service_pid = Pid::from_child(&service); - // Kill AND reap before the monitor starts: a zombie still answers - // kill(pid, 0), so the monitor would correctly see "alive". After - // the reap the pid is gone (ESRCH); reuse inside the test window - // is negligible. - kill_process(service_pid, Signal::KILL).unwrap(); - let status = service.wait().unwrap(); - assert_eq!(status.signal(), Some(libc::SIGKILL)); - - let monitor = fork_monitor( - service_pid, - Some(&dir), - names, - Duration::from_millis(50), - Duration::from_millis(10), - ); - - assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); - assert!( - !dir.join("A").exists() && !dir.join("B").exists(), - "cleanup must run even when the service died before the monitor started" - ); - let _ = fs::remove_dir_all(&dir); - } -} +mod tests; diff --git a/src/monitor/tests.rs b/src/monitor/tests.rs new file mode 100644 index 0000000..971d7f9 --- /dev/null +++ b/src/monitor/tests.rs @@ -0,0 +1,301 @@ +//! Tests for the sibling monitor, extracted from monitor.rs (sweep +//! 2026-08-07 X8). Same module path (`monitor::tests`), same +//! crate-internal visibility — nothing here changed but location. +#![allow(clippy::unwrap_used, clippy::panic)] + +use super::*; +use std::fs; +use std::os::unix::process::ExitStatusExt; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use rustix::process::{WaitOptions, waitpid}; + +use crate::launcher::TerminationGuard; +use crate::secret_files::open_secrets_dir; + +fn tdir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("pm-monitor-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d +} + +/// Fork a monitor watching `service_pid`, mirroring the production +/// launcher: the calling thread blocks the stop signals first (the +/// child is born with them blocked — no ready-race between fork and +/// the monitor's own block), the fork-child runs the REAL monitor +/// loop with test-scaled timing, the parent restores its mask and +/// returns the monitor's pid. +fn fork_monitor( + service_pid: Pid, + dir: Option<&Path>, + names: Vec, + grace: Duration, + poll_interval: Duration, +) -> Pid { + let guard = TerminationGuard::block(); + let dir_fd = dir.map(|d| open_secrets_dir(d).unwrap()); + // SAFETY: fork(2) in the test process. The child executes only + // run_inner — documented async-signal-safe discipline: no + // allocation, no stdio locks, raw syscalls only — and then exits + // via _exit/exit_group, so the multithreaded test harness's + // malloc locks and output buffers are never touched in the child. + match unsafe { libc::fork() } { + -1 => panic!("fork: {}", std::io::Error::last_os_error()), + 0 => { + // Never returns (`-> !`), so the guard is never dropped + // and the mask stays blocked for the monitor's life + // (run_inner re-asserts it regardless). + run_inner(service_pid, dir_fd, names, grace, poll_interval); + } + child => { + guard.restore_mask(); + Pid::from_raw(child).unwrap() + } + } +} + +/// Reap the monitor, asserting it exits 0 within `timeout`. On +/// timeout the monitor is SIGKILLed and reaped so a regression fails +/// the test instead of hanging the suite. +fn wait_monitor_exit(pid: Pid, timeout: Duration) -> i32 { + let deadline = Instant::now() + timeout; + loop { + match waitpid(Some(pid), WaitOptions::NOHANG).unwrap() { + Some((_, status)) => { + if let Some(sig) = status.terminating_signal() { + panic!("monitor died by signal {sig}"); + } + return status.exit_status().unwrap_or(-1); + } + None => { + if Instant::now() >= deadline { + let _ = kill_process(pid, Signal::KILL); + let _ = waitpid(Some(pid), WaitOptions::empty()); + panic!("monitor did not exit within {timeout:?}"); + } + std::thread::sleep(Duration::from_millis(5)); + } + } + } +} + +fn write_dummies(dir: &Path) -> Vec { + fs::write(dir.join("A"), b"secret-a").unwrap(); + fs::write(dir.join("B"), b"secret-b").unwrap(); + vec!["A".to_string(), "B".to_string()] +} + +/// Reaps a forked/spawned pid on drop (SIGKILL first) so a failed +/// assertion can't leak a stray service process — important for the +/// TERM-ignoring service, which would otherwise outlive the test +/// binary indefinitely. +struct ReapOnDrop(Pid); + +impl Drop for ReapOnDrop { + fn drop(&mut self) { + let _ = kill_process(self.0, Signal::KILL); + let _ = waitpid(Some(self.0), WaitOptions::empty()); + } +} + +/// Fork a "service" that ignores SIGTERM until SIGKILLed: a +/// fork-child that sets TERM to SIG_IGN and pause()s forever. This +/// exercises the grace → SIGKILL escalation deterministically, unlike +/// a shell `trap` — macOS /bin/sh resets TERM for exec'd commands, +/// so the disposition doesn't survive into `sleep` there. +fn fork_term_ignoring_service() -> Pid { + // SAFETY: fork(2) in the test process; the child executes only + // async-signal-safe calls (signal(2), pause(2)) and never returns + // into the test harness — no allocation, no stdio, no locks. + match unsafe { libc::fork() } { + -1 => panic!("fork: {}", std::io::Error::last_os_error()), + 0 => unsafe { + // SAFETY: plain single-threaded signal op on this + // process; SIG_IGN is the documented ignore-disposition + // constant. pause(2) suspends until a caught signal + // arrives; TERM is ignored, so only SIGKILL ends the loop. + libc::signal(libc::SIGTERM, libc::SIG_IGN); + loop { + libc::pause(); + } + }, + child => Pid::from_raw(child).unwrap(), + } +} + +/// Service death NOT mediated by the monitor (kill -9 / crash +/// stand-in) must still trigger cleanup and monitor exit. +#[test] +fn natural_service_death_triggers_cleanup_and_monitor_exit() { + let dir = tdir("natural"); + let names = write_dummies(&dir); + let mut service = Command::new("sleep").arg("30").spawn().unwrap(); + let service_pid = Pid::from_child(&service); + let _reap = ReapOnDrop(service_pid); + let monitor = fork_monitor( + service_pid, + Some(&dir), + names, + Duration::from_millis(50), + Duration::from_millis(10), + ); + + assert!(dir.join("A").exists()); + kill_process(service_pid, Signal::KILL).unwrap(); + let status = service.wait().unwrap(); + assert_eq!(status.signal(), Some(libc::SIGKILL)); + + assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); + assert!( + !dir.join("A").exists() && !dir.join("B").exists(), + "monitor must remove the plaintext files on service death" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// A stop signal to the monitor is forwarded to the service; death +/// follows within the grace (no SIGKILL escalation needed), then +/// cleanup runs and the monitor exits 0. The monitor is born with +/// the signal blocked, so the TERM pends until its first tick — +/// no settle sleep is needed. +#[test] +fn stop_signal_is_forwarded_then_grace_then_cleanup() { + let dir = tdir("forward"); + let names = write_dummies(&dir); + let mut service = Command::new("sleep").arg("30").spawn().unwrap(); + let service_pid = Pid::from_child(&service); + let _reap = ReapOnDrop(service_pid); + let monitor = fork_monitor( + service_pid, + Some(&dir), + names, + Duration::from_millis(500), + Duration::from_millis(10), + ); + + kill_process(monitor, Signal::TERM).unwrap(); + + assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); + let status = service.wait().unwrap(); + assert_eq!( + status.signal(), + Some(libc::SIGTERM), + "the service must die by the forwarded TERM, not by an escalated SIGKILL" + ); + assert!( + !dir.join("A").exists() && !dir.join("B").exists(), + "cleanup must run before the monitor exits" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// A service that ignores SIGTERM is SIGKILLed only after the grace +/// elapses; cleanup still runs and the monitor exits 0. +#[test] +fn term_ignoring_service_is_sigkilled_after_grace() { + let dir = tdir("grace"); + let names = write_dummies(&dir); + let service_pid = fork_term_ignoring_service(); + let _reap = ReapOnDrop(service_pid); + let grace = Duration::from_millis(50); + let monitor = fork_monitor( + service_pid, + Some(&dir), + names, + grace, + Duration::from_millis(10), + ); + + let start = Instant::now(); + kill_process(monitor, Signal::TERM).unwrap(); + + assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); + let Some((_, status)) = waitpid(Some(service_pid), WaitOptions::empty()).unwrap() else { + panic!("blocking waitpid returned no status"); + }; + assert_eq!( + status.terminating_signal(), + Some(libc::SIGKILL), + "a TERM-ignoring service must be SIGKILLed" + ); + assert!( + start.elapsed() >= grace, + "SIGKILL must not come before the grace elapses" + ); + assert!( + !dir.join("A").exists() && !dir.join("B").exists(), + "cleanup must run after the SIGKILL path" + ); + let _ = fs::remove_dir_all(&dir); +} + +/// The inherited-heap scrub (threat model): both buffers of an env +/// pair must come back fully wiped. +#[test] +fn wipe_pair_scrubs_both_buffers() { + let (k, v) = wipe_pair( + std::ffi::OsString::from("SECRET_NAME"), + std::ffi::OsString::from("s3cr3t-value"), + ); + assert!(k.iter().all(|b| *b == 0), "name buffer not wiped"); + assert!(v.iter().all(|b| *b == 0), "value buffer not wiped"); +} + +/// Uniform semantics (design decision 4): the monitor runs even in +/// env mode — no dir fd, an empty name list, cleanup a no-op — and +/// still exits when the service dies. +#[test] +fn env_mode_monitor_with_no_files_exits_on_service_death() { + let mut service = Command::new("sleep").arg("30").spawn().unwrap(); + let service_pid = Pid::from_child(&service); + let _reap = ReapOnDrop(service_pid); + let monitor = fork_monitor( + service_pid, + None, + Vec::new(), + Duration::from_millis(50), + Duration::from_millis(10), + ); + + kill_process(service_pid, Signal::TERM).unwrap(); + let status = service.wait().unwrap(); + assert_eq!(status.signal(), Some(libc::SIGTERM)); + + assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); +} + +/// A service that is ALREADY dead when the monitor starts (death +/// observed on the first tick) must still trigger cleanup and an +/// immediate monitor exit — the monitor must never hang waiting on a +/// process that died before it began watching (sweep 2026-08-07 T15). +#[test] +fn pre_dead_service_triggers_immediate_cleanup_and_exit() { + let dir = tdir("predead"); + let names = write_dummies(&dir); + let mut service = Command::new("sleep").arg("30").spawn().unwrap(); + let service_pid = Pid::from_child(&service); + // Kill AND reap before the monitor starts: a zombie still answers + // kill(pid, 0), so the monitor would correctly see "alive". After + // the reap the pid is gone (ESRCH); reuse inside the test window + // is negligible. + kill_process(service_pid, Signal::KILL).unwrap(); + let status = service.wait().unwrap(); + assert_eq!(status.signal(), Some(libc::SIGKILL)); + + let monitor = fork_monitor( + service_pid, + Some(&dir), + names, + Duration::from_millis(50), + Duration::from_millis(10), + ); + + assert_eq!(wait_monitor_exit(monitor, Duration::from_secs(5)), 0); + assert!( + !dir.join("A").exists() && !dir.join("B").exists(), + "cleanup must run even when the service died before the monitor started" + ); + let _ = fs::remove_dir_all(&dir); +} From 0341debdd4a61f657fd8c4f51f89fc99ca58a2f1 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 12:03:40 -0500 Subject: [PATCH 27/47] docs: factual corrections across the book and README (O-group) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every claim below verified against the code at HEAD before editing: - O1: drop 'security add-generic-password -w ' (argv exposure); recommend 'postmaster setup' interactive seeding or -w-less prompt - O2: exit-code table — no exit code 2 exists; all failures exit 1 - O3: 'env' is not a default; mode is required - O4: Strategy B example used a /nix/store key file the parser hard-rejects; now the credential form + LoadCredentialEncrypted wiring - O5: 'does not supervise the child' contradicted the sibling monitor; qualified to no lifecycle POLICY vs plaintext supervision - O6: stale 'one unsafe block on Linux' count; point at the unsafe registry instead - O8: document POSTMASTER_KEY (rotation candidates, _ predicate, profile selection) in abi/contract/provisioning/README - O9: trim abi conformance-vector claims to the tests that exist - O10/O11/O16: launcher-contract bundle_files requirement/rejection rows and the dangling 'both' - O12/O13: re-count env-mutation sites; add keys/provisioning/mod.rs to the unsafe registry - O14: metacharacter inertness is tested in env mode only; say so - O15: 0o077 sentence garbled; the check is mode & 0o077 == 0 - O17: bare postmaster prints help and exits 1; serve has no subcommand keyword - O18: document the 16 MiB read cap (contract fail-closed list + fetch) - O19: examples refresh envelope/dotenvx naming to postmaster - O20: 'System keychain' -> default keychain search list - O21: stray systemd-mandatory sentence moved under Strategy B - O22: root-owned keys files fail the euid check; ownership notes at the install/colmena examples - O23: macOS default keys dir HOME-unset fallback noted - O28-O31: per-subcommand --help; --check silently ignores --verify-keys - O32: 'this docs' typo - signal-deferral: both guard legs are Option-shaped now (X2), not just Linux - keychain wanted-vars derivation covers bundle_files too; abi vector list says what the tampering tests actually cover Battery: fmt, clippy (debug/release/linux-gnu), test (113 lib, 8 exec_check, 26 conformance), deny, audit, docs. --- README.md | 5 +-- docs/examples/exec-credentials-darwin.json | 8 ++--- docs/examples/exec-env.json | 4 +-- docs/examples/exec-files.json | 6 ++-- docs/src/architecture/materialization-abi.md | 9 +++-- docs/src/architecture/postmaster.md | 22 +++++++----- docs/src/architecture/threat-model.md | 5 +-- docs/src/getting-started/injection-modes.md | 4 +-- docs/src/getting-started/key-provisioning.md | 37 +++++++++++++++----- docs/src/getting-started/quick-start.md | 15 ++++++-- docs/src/introduction.md | 9 +++-- docs/src/reference/cli.md | 22 +++++++----- docs/src/reference/launcher-contract.md | 35 ++++++++++++------ docs/src/unsafe-code/index.md | 2 +- docs/src/unsafe-code/signal-deferral.md | 2 +- docs/src/unsafe-code/test-env-mutation.md | 9 ++--- 16 files changed, 128 insertions(+), 66 deletions(-) diff --git a/README.md b/README.md index c77981a..e834629 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ $ postmaster --help ## Injection modes -**`mode = "env"` (default).** Decrypted values are exported into the +**`mode = "env"`.** Decrypted values are exported into the process environment and the wrapper `exec`s your binary. Correct for 12-factor apps. @@ -103,7 +103,8 @@ fetches from remote systems: - **macOS Keychain** — key material stored as generic-password items, read natively by postmaster via the Security.framework API - **Environment** — `DOTENV_PRIVATE_KEY*` variables in the process - environment (set by the service manager) + environment (set by the service manager); bundle configs use + `POSTMASTER_KEY` instead ## Integration diff --git a/docs/examples/exec-credentials-darwin.json b/docs/examples/exec-credentials-darwin.json index afd8af0..5bb46ab 100644 --- a/docs/examples/exec-credentials-darwin.json +++ b/docs/examples/exec-credentials-darwin.json @@ -4,10 +4,10 @@ "DATABASE_URL", "REDIS_URL" ], - "secrets_dir": "/private/var/run/dotenvx/myapp", + "secrets_dir": "/private/var/run/postmaster/myapp", "sockets": { - "DATABASE_URL": "/private/var/run/dotenvx-credd/myapp/DATABASE_URL.sock", - "REDIS_URL": "/private/var/run/dotenvx-credd/myapp/REDIS_URL.sock" + "DATABASE_URL": "/private/var/run/postmaster-credd/myapp/DATABASE_URL.sock", + "REDIS_URL": "/private/var/run/postmaster-credd/myapp/REDIS_URL.sock" }, - "verify_ramdisk": "/private/var/run/dotenvx" + "verify_ramdisk": "/private/var/run/postmaster" } diff --git a/docs/examples/exec-env.json b/docs/examples/exec-env.json index 0c99dd6..4accaa1 100644 --- a/docs/examples/exec-env.json +++ b/docs/examples/exec-env.json @@ -2,12 +2,12 @@ "mode": "env", "keys": [ { - "credential": "dotenvx-myapp" + "credential": "postmaster-myapp" }, "environment" ], "env_files": [ - "/nix/store/example-dotenvx-env-myapp/.env.production" + "/nix/store/example-postmaster-env-myapp/.env.production" ], "strict": true, "overload": false diff --git a/docs/examples/exec-files.json b/docs/examples/exec-files.json index 73bf56e..5f0c64c 100644 --- a/docs/examples/exec-files.json +++ b/docs/examples/exec-files.json @@ -2,15 +2,15 @@ "mode": "files", "keys": [ { - "file": "/run/envelope/myapp.env.keys" + "file": "/var/lib/postmaster/myapp.env.keys" } ], "env_files": [ - "/nix/store/example-dotenvx-env-myapp/.env.production" + "/nix/store/example-postmaster-env-myapp/.env.production" ], "strict": true, "overload": false, - "secrets_dir": "/run/dotenvx/myapp", + "secrets_dir": "/run/postmaster/myapp", "passthrough": [ "RUST_LOG" ] diff --git a/docs/src/architecture/materialization-abi.md b/docs/src/architecture/materialization-abi.md index 32b38db..034c345 100644 --- a/docs/src/architecture/materialization-abi.md +++ b/docs/src/architecture/materialization-abi.md @@ -181,6 +181,11 @@ The design constraints are: - `profile` is optional public selection metadata; it is not a secret. - `recipients[*].id` is public routing metadata used to select local private key material. +- Private key material comes from the `POSTMASTER_KEY` variable: + comma-separated rotation candidates are admitted, and + `POSTMASTER_KEY_` variants match by the same predicate as + `DOTENV_PRIVATE_KEY_*`. There is no per-environment filename mapping — + `profile` handles selection. - `entries` keys must use the same identifier rule as `.env`-derived keys: `[A-Za-z_][A-Za-z0-9_]*`. - `encoding` is either `utf8` or `bytes`. `env` projection rejects bytes that @@ -197,11 +202,9 @@ launch, and the same output projection semantics as `.env` values. The implementation ships with conformance vectors for: - minimal valid bundle -- multiple recipients -- binary value projected to files - invalid key name - unknown version -- tampered authenticated metadata +- tampered `format`/`version`/`suite` values (fail-closed parsing) - wrong local private key - replayed ciphertext under a different entry name diff --git a/docs/src/architecture/postmaster.md b/docs/src/architecture/postmaster.md index 53afc28..659d951 100644 --- a/docs/src/architecture/postmaster.md +++ b/docs/src/architecture/postmaster.md @@ -88,10 +88,14 @@ artifact exists or after the child process starts: SaltStack, Puppet — these tools render the deployment artifacts and wire the service manager. Postmaster does not deploy. -- **Service supervision.** Postmaster does not supervise the child - process. The service manager (systemd on Linux, launchd on macOS) - starts, monitors, and stops the service. Postmaster's job is done - the moment `execvp` fires. +- **Service supervision policy.** Postmaster owns no lifecycle policy + — no restarts, no health checks. The service manager (systemd on + Linux, launchd on macOS) starts, monitors, and stops the service. + What postmaster does run is a secretless sibling monitor alongside + the exec'd service: it forwards stop signals, escalates to SIGKILL + after a bounded grace, and removes plaintext secret files on every + death path (see "The secret pipeline" below) — supervision of + plaintext, not of the service's health. - **Child behavior.** What the child process does with its secrets — reading from environment variables, files, or credentials — is the @@ -221,11 +225,11 @@ monitor. The ramdisk is destroyed when the launchd job stops (macOS). `postmaster/` contains a dependency-lean Rust binary (edition 2024; pure-Rust crypto, no openssl; no async runtime; syscalls via -rustix's `linux_raw` backend rather than libc FFI on Linux, leaving -one `unsafe` block for the fd-ownership assertion at the systemd -socket-activation boundary; on macOS, `libc` is used for `getpeereid` -and `PT_DENY_ATTACH` hardening — each `unsafe` site carries a SAFETY -comment) that materializes decrypted secret values as systemd +rustix's `linux_raw` backend rather than libc FFI on Linux; on macOS, +`libc` is used for `getpeereid` and `PT_DENY_ATTACH` hardening — each +`unsafe` site carries a SAFETY comment and is catalogued in the +[unsafe-code registry](../unsafe-code/index.md)) that materializes +decrypted secret values as systemd `LoadCredential=` AF_UNIX sources or directly injects them via `execvp`. systemd's documented contract for socket credential sources is minimal — the manager connects once at process invocation and reads diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index 6413840..16d6715 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -162,8 +162,9 @@ read or written: - **Key files** are opened with `O_NOFOLLOW` — a symlinked `.env.keys` file is rejected at the kernel level. The file descriptor is then - `fstat`-ed to verify that permissions are `0o077` (no group or world - access) and that the owner matches the current effective user ID. + `fstat`-ed to verify that no group/world permission bits are set + (`mode & 0o077 == 0`) and that the owner matches the current + effective user ID. This fd-based approach eliminates the TOCTOU window between open and permission check. - **Credential source paths** are checked with `symlink_metadata` diff --git a/docs/src/getting-started/injection-modes.md b/docs/src/getting-started/injection-modes.md index 29cad6e..04a465b 100644 --- a/docs/src/getting-started/injection-modes.md +++ b/docs/src/getting-started/injection-modes.md @@ -11,7 +11,7 @@ environment variables, as files, or as systemd credentials. | Mode | Best for | Secrets in environ? | Hygiene | | --- | --- | --- | --- | -| `env` (default) | 12-factor apps, simple services | Yes | Lowest — same-UID processes can read `/proc/PID/environ` | +| `env` | 12-factor apps, simple services | Yes | Lowest — same-UID processes can read `/proc/PID/environ` | | `files` | Apps that read `KEY_FILE` pointers (Docker secrets convention) | No — only `_FILE` pointers | Medium — secrets absent from environ, `ps`, crash dumps | | `credentials` | systemd services wanting strongest isolation | No — reads `$CREDENTIALS_DIRECTORY` | Highest — unit-private unswappable ramfs | @@ -33,7 +33,7 @@ flowchart TB end ``` -## `mode = "env"` (default) +## `mode = "env"` Decrypted values are exported into the process environment and the wrapper `exec`s your binary. Correct for 12-factor apps. diff --git a/docs/src/getting-started/key-provisioning.md b/docs/src/getting-started/key-provisioning.md index 85942a1..4d95678 100644 --- a/docs/src/getting-started/key-provisioning.md +++ b/docs/src/getting-started/key-provisioning.md @@ -43,8 +43,10 @@ DOTENV_PRIVATE_KEY_PRODUCTION="<64-hex from your local .env.keys>" EOF ``` -systemd treats an absolute-path credential as mandatory: missing file -means the unit fails to start. Fail-closed. +Ownership matters: `KeyRing::load` requires the keys file to be owned +by the effective uid of the loading process, so `chown` it to the +service user (or run the file-owning step as that user) — a root-owned +keys file fails closed for a service running as a normal user. ## Strategy B: TPM2 / host-sealed blob @@ -60,16 +62,21 @@ EOF # copy myapp-myhost.cred back into the repo ``` -Reference the sealed blob in your config: +Wire the sealed blob to the launcher's unit with +`LoadCredentialEncrypted=postmaster-myapp:` and reference +the credential name in your config: ```json { "keys": [ - {"file": "/nix/store/...-myapp.cred"} + {"credential": "postmaster-myapp"} ] } ``` +systemd treats the credential as mandatory: a missing or undecryptable +blob means the unit fails to start. Fail-closed. + Blobs are per-host. Without a TPM, `--with-key=host` binds to `/var/lib/systemd/credential.secret`. @@ -85,22 +92,34 @@ deployment.keys."myapp.env.keys" = { }; ``` +As with any keys file, `user` must be the service's own user — +`KeyRing::load` requires the file owner to match the loading process's +effective uid, so `root` here only works for services that run as root. + ## Strategy D: macOS Keychain +The recommended path is `postmaster setup`, which seeds the wanted +keychain items interactively. By hand, use `security +add-generic-password` *without* `-w` so it prompts for the value: + ```console $ security add-generic-password -a DOTENV_PRIVATE_KEY_PRODUCTION \ - -s postmaster -w "<64-hex>" + -s postmaster ``` -No file on disk — keys live as generic-password items in the System -keychain. Postmaster reads them natively via the Security.framework -API (`security-framework` crate). +Avoid `-w ""`: it puts the private key in the process argv, +visible to every process on the host via `ps`. + +No file on disk — keys live as generic-password items in the default +keychain search list. Postmaster reads them natively via the +Security.framework API (`security-framework` crate). ## Rotation No `rotate` subcommand exists. The flow is manual, but `DOTENV_PRIVATE_KEY*` accepts **comma-separated keys** for a -zero-downtime window: +zero-downtime window (the bundle adapter's `POSTMASTER_KEY` variable — +no per-environment suffix — follows the same convention): ```mermaid flowchart TD diff --git a/docs/src/getting-started/quick-start.md b/docs/src/getting-started/quick-start.md index bf73d7c..57ae6d6 100644 --- a/docs/src/getting-started/quick-start.md +++ b/docs/src/getting-started/quick-start.md @@ -63,13 +63,24 @@ DOTENV_PRIVATE_KEY_PRODUCTION="a1b2c3d4e5f6..." EOF ``` -On macOS, you can also use the keychain: +Ownership matters: `KeyRing::load` requires the keys file to be owned +by the effective uid of the loading process, so `chown` it to the +service user (or run the file-owning step as that user) — a root-owned +keys file fails closed for a service running as a normal user. + +On macOS, you can also use the keychain. The recommended path is +`postmaster setup`, which seeds keychain items interactively; the +equivalent by hand is `security add-generic-password` *without* `-w`, +which prompts for the value: ```console $ security add-generic-password -a DOTENV_PRIVATE_KEY_PRODUCTION \ - -s postmaster -w "a1b2c3d4e5f6..." + -s postmaster ``` +Avoid `-w ""`: it puts the private key in the process argv, +visible to every process on the host via `ps`. + ## Step 3: Create exec.json Postmaster reads an `exec.json` config that specifies what to decrypt, diff --git a/docs/src/introduction.md b/docs/src/introduction.md index 6d3be87..1804042 100644 --- a/docs/src/introduction.md +++ b/docs/src/introduction.md @@ -16,7 +16,7 @@ holds secrets in memory. ### Who this is for -| Reader | What to take from this docs | +| Reader | What to take from this doc | | -------- | ------------------------------ | | New user / junior engineer | The introduction and [Quick start](./getting-started/quick-start.md); then [Injection modes](./getting-started/injection-modes.md) | | Platform / SRE | [Key provisioning](./getting-started/key-provisioning.md) and the [Threat model](./architecture/threat-model.md) | @@ -137,8 +137,11 @@ flowchart LR | 5. Launch | execvp | Process image replaced; child binary is MainPID | Postmaster does not participate in stages 1-3. It does not fetch from -remote systems, does not deploy infrastructure, and does not supervise -the child process. It decrypts, injects, and gets out of the way. +remote systems, does not deploy infrastructure, and owns no service +lifecycle policy — no restarts, no health checks (a secretless sibling +monitor forwards stop signals and cleans up plaintext; the service +manager supervises the service itself). It decrypts, injects, and gets +out of the way. ## Capability Horizon diff --git a/docs/src/reference/cli.md b/docs/src/reference/cli.md index 7a82bfb..cdb60ee 100644 --- a/docs/src/reference/cli.md +++ b/docs/src/reference/cli.md @@ -26,9 +26,10 @@ $ postmaster --help ## Default mode (serve) -When no subcommand is given, postmaster enters daemon (serve) mode. This -is the credential server used in credentials injection mode — -socket-activated on Linux, self-binding on macOS. +Serve mode has no subcommand keyword — invoke it with the serve flags +directly. This is the credential server used in credentials injection +mode — socket-activated on Linux, self-binding on macOS. (Bare +`postmaster` with no arguments prints the top-level help and exits 1.) ```console $ postmaster --config [--bind] [--allow-nonroot] @@ -64,6 +65,8 @@ $ postmaster exec --config [--check] [--verify-keys] -- [a returns. - On failure the error is logged and the process exits non-zero. - `--check` does not accept a command after `--`. +- `--check` combined with `--verify-keys` silently ignores verification — + check validates the config shape and never decrypts. - `--verify-keys` performs a preflight check: after loading and decrypting, if any value was skipped because the key ring could not decrypt it, the keys are stale and the exec aborts naming the key. @@ -75,8 +78,7 @@ Exit codes: | Code | Meaning | | --- | --- | | 0 | `--check` passed (or exec succeeded — but exec replaces the process) | -| 1 | Config error, parse failure, decryption failure | -| 2 | Missing arguments, bad usage | +| 1 | Any failure — usage errors, config errors, parse failure, decryption failure | ## setup @@ -99,7 +101,8 @@ $ postmaster setup --config [--recheck] [--unattended] [--force] [-- Default keys directory: - Linux: `/var/lib/postmaster` -- macOS: `~/Library/Application Support/postmaster` +- macOS: `~/Library/Application Support/postmaster` (falls back to + `/var/lib/postmaster` when `HOME` is unset) ## cleanup @@ -127,7 +130,8 @@ stops. ## fetch macOS credential fetch client — connects to a postmaster socket and -reads the decrypted value to EOF. +reads the decrypted value to EOF. Reads are hard-capped at 16 MiB; +an oversize stream fails rather than truncates. ```console $ postmaster fetch /run/postmaster-credd/myapp/DATABASE_URL.sock @@ -138,7 +142,9 @@ typically called directly. ## help -Print help text for a subcommand or the top-level help. +Print help text for a subcommand or the top-level help. Every +subcommand also accepts `--help`/`-h` directly (`postmaster exec +--help`). ```console $ postmaster help # top-level help diff --git a/docs/src/reference/launcher-contract.md b/docs/src/reference/launcher-contract.md index cccc723..23041b6 100644 --- a/docs/src/reference/launcher-contract.md +++ b/docs/src/reference/launcher-contract.md @@ -113,7 +113,8 @@ $ postmaster cleanup --config is verification-only. `--unattended` fails closed without prompting. `--force` re-creates/re-seeds even if correct. `--keys-dir` overrides the default path (`/var/lib/postmaster` on Linux, - `~/Library/Application Support/postmaster` on macOS). + `~/Library/Application Support/postmaster` on macOS — falling back to + `/var/lib/postmaster` when `HOME` is unset). **`--check` validates config shape only, not key source accessibility:** a config can pass `--check` in CI but fail at runtime because the key file is missing, the keychain item is absent, or the credential source @@ -140,8 +141,8 @@ Every field except `mode` has a default, so a minimal config is just | Field | Type | Default | Meaning | |---|---|---|---| | `mode` | `"env" \| "files" \| "credentials"` | — (required) | Injection mode; see below. | -| `keys` | array of key-source specs | `[]` | Ordered list of where to obtain `DOTENV_PRIVATE_KEY*` material. Unused in `credentials` mode. | -| `env_files` | array of paths | `[]` | Encrypted `.env[.]` files, in precedence order (first file wins unless `overload`). Required (non-empty) for `env`/`files` modes. | +| `keys` | array of key-source specs | `[]` | Ordered list of where to obtain `DOTENV_PRIVATE_KEY*` / `POSTMASTER_KEY` material. Unused in `credentials` mode. | +| `env_files` | array of paths | `[]` | Encrypted `.env[.]` files, in precedence order (first file wins unless `overload`). `env`/`files` modes require at least one of `env_files` or `bundle_files` non-empty. | | `bundle_files` | array of paths | `[]` | Encrypted `postmaster_bundle` JSON containers, in precedence order. Entries are merged with `env_files`; bundle keys use the same identifier rule and injection modes. | | `strict` | bool | **`true`** | Any value that fails to decrypt aborts the whole exec before the child runs. | | `overload` | bool | `false` | File-derived values override the process environment; later files override earlier ones. | @@ -157,9 +158,10 @@ match it exactly. Mode-required fields are enforced by `postmaster exec --check` and again before a real launch: -- `env` requires non-empty `keys` and non-empty `env_files`. -- `files` requires non-empty `keys`, non-empty `env_files`, and - `secrets_dir`. +- `env` requires non-empty `keys` and at least one of `env_files` or + `bundle_files` non-empty. +- `files` requires non-empty `keys`, at least one of `env_files` or + `bundle_files` non-empty, and `secrets_dir`. - `credentials` requires non-empty `credential_keys`. If `sockets` is non-empty, it also requires `secrets_dir` and a socket mapping for every credential key. @@ -191,7 +193,7 @@ serde fills those in even when the generator omits the field. |---|---| | `env` | `secrets_dir`, `credential_keys`, `sockets`, `verify_ramdisk`, `passthrough` | | `files` | `credential_keys`, `sockets` | -| `credentials` | `keys`, `env_files`, `overload`, `passthrough` | +| `credentials` | `keys`, `env_files`, `bundle_files`, `overload`, `passthrough` | ## Key-source list (`keys`) @@ -201,8 +203,16 @@ Each entry in `keys` is one externally-tagged JSON shape: |---|---| | `{"credential": ""}` | `$CREDENTIALS_DIRECTORY/` (the launcher's *own* `LoadCredential`, i.e. `.env.keys` handed to it the same way postmaster's daemon receives its own). `` must be a single relative path component, not `.`, `..`, an absolute path, or a slash-containing path. | | `{"file": ""}` | An out-of-store `.env.keys`-format file read directly. Rejected outright if the path starts with `/nix/store` — private keys must never live in the world-readable store. | -| `{"keychain": ""}` | macOS System keychain; one generic-password item per `DOTENV_PRIVATE_KEY[_]` account, service name as given. Only the variables actually needed (derived from `env_files`) are fetched. Any other target: error, "only available on macOS". | -| `"environment"` | The unit-variant source — note it is a bare JSON string, not an object, because it carries no data. Reads `DOTENV_PRIVATE_KEY*` straight from postmaster's own process environment. | +| `{"keychain": ""}` | macOS keychain (the default keychain search list); one generic-password item per `DOTENV_PRIVATE_KEY[_]` account, service name as given. Only the variables actually needed (derived from `env_files` and `bundle_files`) are fetched. Any other target: error, "only available on macOS". | +| `"environment"` | The unit-variant source — note it is a bare JSON string, not an object, because it carries no data. Reads `DOTENV_PRIVATE_KEY*` (and `POSTMASTER_KEY` when `bundle_files` are configured) straight from postmaster's own process environment. | + +**Bundle key variable.** With `bundle_files` configured, the ring admits +`POSTMASTER_KEY` material in the same sources: comma-separated rotation +candidates are admitted, and `POSTMASTER_KEY_` variants match by +the same predicate as `DOTENV_PRIVATE_KEY_*`. There is no +per-environment filename mapping — every bundle file resolves against +the one `POSTMASTER_KEY` variable, and the bundle's `profile` field +handles environment selection. **Selection contract**, evaluated in list order: @@ -326,7 +336,7 @@ this mode — it dispatches on whether `sockets` is empty: each key, looks up its socket in `sockets` (missing entry is an error), connects and reads to EOF via the same client path `postmaster fetch` uses, writes the bytes to `/` at `0600`, and exports - `_FILE`. After all keys, exports **both** + `_FILE`. After all keys, also exports `CREDENTIALS_DIRECTORY` set to `secrets_dir` — unlike the systemd branch, there is no real `LoadCredential` mechanism on darwin, so the launcher has to tell the consumer that @@ -348,6 +358,9 @@ this mode — it dispatches on whether `sockets` is empty: serve, and fails closed with `": server sent zero bytes (refused to serve); failing closed"` rather than writing an empty credential file. +- **16 MiB read cap.** Every single read — secret, bundle, config, and + fetch payloads — is hard-capped at 16 MiB (`read_capped`); an oversize + payload fails rather than truncates. - **Missing `$CREDENTIALS_DIRECTORY`** in `credentials` mode's systemd branch fails closed rather than silently exporting nothing. - **Private keys never come from the Nix store.** A `{"file": …}` key @@ -431,7 +444,7 @@ with external secret-management tooling that materializes a ## Conformance `tests/exec_conformance/main.rs` is the executable form of this document: -metacharacter-laden values stay inert across all three modes, +metacharacter-laden values stay inert in `env` mode, process-env-wins-without-overload and overload-reverses-it, rotation with a bogus first key, strict failure refuses to exec, `0600` pointer files and `passthrough`, both `credentials` branches (systemd pointer-only and diff --git a/docs/src/unsafe-code/index.md b/docs/src/unsafe-code/index.md index 4e4d019..6488f26 100644 --- a/docs/src/unsafe-code/index.md +++ b/docs/src/unsafe-code/index.md @@ -28,7 +28,7 @@ Every `unsafe` block requires: | `server.rs` (`peer_euid`) | macOS | Peer credential check via `getpeereid(2)` | [macos-libc-boundary](./macos-libc-boundary.md) | | `server.rs` (`harden_process`) | macOS, release only | `PT_DENY_ATTACH` anti-debug hardening | [macos-libc-boundary](./macos-libc-boundary.md) | | `server.rs` (socket activation) | Linux | `UnixListener::from_raw_fd` on systemd-inherited sockets | [systemd-fd-ownership](./systemd-fd-ownership.md) | -| `keys/source.rs`, `keys/env.rs` (test modules) | all, test-only | `set_var`/`remove_var` (unsafe on edition 2024) | [test-env-mutation](./test-env-mutation.md) | +| `keys/source.rs`, `keys/env.rs`, `keys/provisioning/mod.rs` (test modules) | all, test-only | `set_var`/`remove_var` (unsafe on edition 2024) | [test-env-mutation](./test-env-mutation.md) | Note what is NOT in the inventory: `mlockall`, `setrlimit(Core, 0)`, and `set_dumpable(NotDumpable)` hardening all use **safe** rustix wrappers. diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md index fad81eb..d71033d 100644 --- a/docs/src/unsafe-code/signal-deferral.md +++ b/docs/src/unsafe-code/signal-deferral.md @@ -56,7 +56,7 @@ holds only standard signals no libc reserves. | Dangling pointers | set/old must outlive each call | Locals live for the full block; no pointers escape | | Thread-model mismatch | `sigprocmask` is unspecified in multithreaded processes | `pthread_sigmask` form on Darwin; on Linux the launcher is single-threaded at this point (worker threads exist only in serve mode) | | libc-reserved signals | Masking a signal a libc reserves is UB (rustix `runtime` safety note) | The set holds only TERM/INT/HUP/QUIT — none reserved (glibc reserves 32/33) | -| Mask clobber | Restoring a mask never captured | The Linux leg stores `None` on block failure (logged); restore then no-ops | +| Mask clobber | Restoring a mask never captured | Both legs are Option-shaped and store `None` on block failure (logged); restore then no-ops | | Mask leak to the service | Service inheriting blocked termination signals | Mask restored before `execvp` on every path (explicit + `Drop` on early-Err) — the monitor *wants* the mask and is the only inheritor | ## Remaining Risks diff --git a/docs/src/unsafe-code/test-env-mutation.md b/docs/src/unsafe-code/test-env-mutation.md index aec22b3..2a1da7e 100644 --- a/docs/src/unsafe-code/test-env-mutation.md +++ b/docs/src/unsafe-code/test-env-mutation.md @@ -4,9 +4,9 @@ ``` src/test_util.rs — the shared ENV_LOCK itself -src/keys/source.rs (test module) — 4 sites -src/keys/env.rs (test module) — 1 test, 2 set/remove pairs -src/keys/provisioning/mod.rs (test module) — 1 test, 2 set/remove pairs + a full vars() scan +src/keys/source.rs (test module) — 8 tests, 17 set/remove calls +src/keys/env.rs (test module) — 2 tests, 8 set/remove calls +src/keys/provisioning/mod.rs (test module) — 3 tests, 14 set/remove calls + ambient vars() scans ``` ## Purpose @@ -15,7 +15,8 @@ Edition 2024 marks `std::env::set_var`/`remove_var` `unsafe`: mutating the process environment is a data race in a multithreaded process, and the Rust test harness runs tests in parallel threads of one process. Several key-source tests must set or clear `DOTENV_PRIVATE_KEY*` / -`CREDENTIALS_DIRECTORY` to exercise source selection. +`POSTMASTER_KEY*` / `CREDENTIALS_DIRECTORY` to exercise source +selection. ## UB Vectors and Mitigations From 547550579e3e608bb1d49c48745331d495ac21c8 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 16:29:29 -0500 Subject: [PATCH 28/47] chore(repo): justfile gates, toolchain targets, nix naming, ignore cleanup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - R2: clippy-release and clippy-linux recipes (the house battery's two cross-profile gates) wired into ci-rust, so hooks and CI run the same clippy matrix the battery does - R12: pin x86_64-unknown-linux-gnu in rust-toolchain.toml targets so rustup installs the cross target automatically - R3: nixpkgs-package.nix made buildable-shaped — repo=postmaster, root Cargo.lock, no stale sourceRoot, postmaster homepage and prefetch URL; package.nix homepage; deny.toml header comment - R10/R11: drop the dead /postmaster/target/ gitignore line and the inert docs/book/ gitattributes pattern (no dir-recursion syntax) R4 reversed by author: patches/ stays local-only, unchanged. R7 deferred: no nix on this machine to run nix flake lock. Battery: fmt, clippy (debug/release/linux-gnu), test (113 lib, 8 exec_check, 26 conformance), deny, audit, docs. --- .gitattributes | 1 - .gitignore | 1 - Justfile | 11 ++++++++++- deny.toml | 2 +- nixpkgs-package.nix | 12 +++++------- package.nix | 2 +- rust-toolchain.toml | 1 + 7 files changed, 18 insertions(+), 12 deletions(-) diff --git a/.gitattributes b/.gitattributes index 8eb7cfd..67d9aa7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -19,4 +19,3 @@ *.ico binary *.exe binary *.zip binary -docs/book/ binary diff --git a/.gitignore b/.gitignore index 5f8189b..0f8f735 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ # Rust build output -/postmaster/target/ target/ # Ignore build outputs from performing a nix-build or `nix build` command diff --git a/Justfile b/Justfile index 080dd80..1a5eccb 100644 --- a/Justfile +++ b/Justfile @@ -18,6 +18,15 @@ fmt-check: clippy: cargo +{{stable_toolchain}} clippy --all-targets -- -D warnings +# Release-profile clippy (house battery gate; sweep 2026-08-07 R2) +clippy-release: + cargo +{{stable_toolchain}} clippy --all-targets --release -- -D warnings + +# Linux-target clippy (house battery gate; sweep 2026-08-07 R2). The +# target is pinned in rust-toolchain.toml, so rustup installs it. +clippy-linux: + cargo +{{stable_toolchain}} clippy --all-targets --target x86_64-unknown-linux-gnu -- -D warnings + build: cargo +{{stable_toolchain}} build --locked @@ -68,7 +77,7 @@ audit: # Aggregate # ============================================================================= -ci-rust: fmt-check clippy build test +ci-rust: fmt-check clippy clippy-release clippy-linux build test ci: ci-rust flake-check # ============================================================================= diff --git a/deny.toml b/deny.toml index 769800f..cb9e17e 100644 --- a/deny.toml +++ b/deny.toml @@ -1,4 +1,4 @@ -# cargo-deny configuration for envelope / postmaster. +# cargo-deny configuration for postmaster. # https://embarkstudios.github.io/cargo-deny/ [graph] diff --git a/nixpkgs-package.nix b/nixpkgs-package.nix index fd699c4..545ce30 100644 --- a/nixpkgs-package.nix +++ b/nixpkgs-package.nix @@ -7,14 +7,14 @@ # Steps before real submission: # 1. Tag a release in this repo (e.g. v0.1.0) that matches Cargo.toml version. # 2. Replace the placeholder hash with the real one: -# nix-prefetch-url --unpack https://github.com/beardedeagle/envelope/archive/refs/tags/v0.1.0.tar.gz +# nix-prefetch-url --unpack https://github.com/beardedeagle/postmaster/archive/refs/tags/v0.1.0.tar.gz # (or use nix-update / pkgs/by-name update machinery later) # 3. Add yourself to maintainers/maintainer-list.nix if not present. # 4. Set meta.maintainers appropriately. # 5. Run nixpkgs-review and ensure ofborg builds on linux + darwin. # # Notes: -# - The Rust crate lives in the "postmaster/" subdirectory of the repo. +# - The Rust crate lives at the repository root. # - We use cargoLock (preferred when a lockfile exists and there are no git deps). # - No native build inputs needed (pure Rust + rustix; "pure" feature on ecies avoids openssl). @@ -29,15 +29,13 @@ rustPlatform.buildRustPackage rec { src = fetchFromGitHub { owner = "beardedeagle"; - repo = "envelope"; + repo = "postmaster"; rev = "v${version}"; hash = "sha256-PLACEHOLDER"; # update after tagging }; - sourceRoot = "${src.name}/postmaster"; - cargoLock = { - lockFile = src + "/postmaster/Cargo.lock"; + lockFile = src + "/Cargo.lock"; # While ecies is git-pinned via [patch.crates-io] (audit 2026-08-02 A7): # the git dep's fetch hash. Drop once the upstream ecies PR (ecies/rs#159) # ships on crates.io and the patch section is removed. @@ -46,7 +44,7 @@ rustPlatform.buildRustPackage rec { meta = { description = "postmaster credential bridge: serves decrypted secret values as systemd LoadCredential AF_UNIX sources"; - homepage = "https://github.com/beardedeagle/envelope"; + homepage = "https://github.com/beardedeagle/postmaster"; license = lib.licenses.mit; maintainers = with lib.maintainers; [ ]; # replace when you have an entry mainProgram = "postmaster"; diff --git a/package.nix b/package.nix index 2787fd9..92dac51 100644 --- a/package.nix +++ b/package.nix @@ -42,7 +42,7 @@ rustPlatform.buildRustPackage { guaranteeing that plaintext secrets only ever appear inside unit-private unswappable credential ramfs. ''; - homepage = "https://github.com/beardedeagle/envelope"; + homepage = "https://github.com/beardedeagle/postmaster"; license = lib.licenses.mit; mainProgram = "postmaster"; platforms = lib.platforms.linux ++ lib.platforms.darwin; diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 05e6ca1..da44fa7 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -2,3 +2,4 @@ channel = "stable" profile = "minimal" components = ["rustfmt", "clippy"] +targets = ["x86_64-unknown-linux-gnu"] From 15c50729bc5ce9e81d575c32e46f3b7a27072cef Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 16:34:44 -0500 Subject: [PATCH 29/47] chore(ci): pin tool versions, wire lint-md, gate deny/audit in hooks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - R1 (interim): lefthook pre-push now runs deny + audit alongside ci-rust while GitHub Actions stay budget-disabled (the 'if: false' flags are untouched; re-enabling CI is the author's call) - R5: setup-rust gains install-mdbook (+ mdbook/mdbook-mermaid version inputs pinned 0.5.4/0.17.0); the docs job would have failed the moment CI is re-enabled — nothing installed mdbook - R6: just lint-md (pinned markdownlint-cli2 0.23.2) wired into lefthook pre-commit. cli2 never read .markdownlintignore, so rules and ignores are consolidated into .markdownlint-cli2.jsonc (one source of truth) and the two dead files deleted. Prose sweep: 6 missing fence-language tags, 2 long lines wrapped; CODE_OF_CONDUCT (verbatim upstream) and the PR template (## Summary by design) ignored - R8: cargo-deny/cargo-audit installs pinned (0.20.2/0.22.2, matching the local toolchain) via new version inputs - R9: deny job dropped from ci.yml (security.yml owns it); security.yml path filters now include the workflow file itself Battery: fmt, clippy (debug/release/linux-gnu), test (113 lib, 8 exec_check, 26 conformance), deny, audit, docs, lint-md (0 issues). --- .github/ISSUE_TEMPLATE/bug_report.md | 3 +- .github/actions/setup-rust/action.yml | 42 +++++++++++++++++++- .github/workflows/ci.yml | 20 +--------- .github/workflows/docs.yml | 4 +- .github/workflows/security.yml | 2 + .markdownlint-cli2.jsonc | 34 ++++++++++++++++ .markdownlint.jsonc | 16 -------- .markdownlintignore | 9 ----- Justfile | 5 +++ docs/src/unsafe-code/index.md | 5 ++- docs/src/unsafe-code/macos-libc-boundary.md | 4 +- docs/src/unsafe-code/monitor.md | 2 +- docs/src/unsafe-code/signal-deferral.md | 2 +- docs/src/unsafe-code/systemd-fd-ownership.md | 2 +- docs/src/unsafe-code/test-env-mutation.md | 2 +- lefthook.yml | 6 +++ 16 files changed, 104 insertions(+), 54 deletions(-) create mode 100644 .markdownlint-cli2.jsonc delete mode 100644 .markdownlint.jsonc delete mode 100644 .markdownlintignore diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index ad8ecf3..81655b4 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -16,7 +16,8 @@ A clear description of the bug and what you expected instead. 2. 3. -A minimal repro (failing postmaster command, unit test, or exec.json config) is the fastest path to a fix. +A minimal repro (failing postmaster command, unit test, or exec.json +config) is the fastest path to a fix. ## Environment diff --git a/.github/actions/setup-rust/action.yml b/.github/actions/setup-rust/action.yml index 5aa7b49..9edc86f 100644 --- a/.github/actions/setup-rust/action.yml +++ b/.github/actions/setup-rust/action.yml @@ -22,6 +22,26 @@ inputs: description: Whether to install cargo-audit. required: false default: "false" + cargo-deny-version: + description: cargo-deny version to install. + required: false + default: "0.20.2" + cargo-audit-version: + description: cargo-audit version to install. + required: false + default: "0.22.2" + install-mdbook: + description: Whether to install mdbook and the mdbook-mermaid preprocessor (docs builds). + required: false + default: "false" + mdbook-version: + description: mdbook version to install. + required: false + default: "0.5.4" + mdbook-mermaid-version: + description: mdbook-mermaid preprocessor version to install. + required: false + default: "0.17.0" install-target-dir: description: Cargo target directory for tool installation builds. required: false @@ -88,20 +108,38 @@ runs: if: ${{ inputs.install-cargo-deny == 'true' }} shell: bash env: + CARGO_DENY_VERSION: ${{ inputs.cargo-deny-version }} CARGO_INSTALL_TARGET_DIR: ${{ inputs.install-target-dir }} run: | set -euo pipefail if ! command -v cargo-deny >/dev/null 2>&1; then - cargo install cargo-deny --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" + cargo install cargo-deny --version "$CARGO_DENY_VERSION" --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" fi - name: Install cargo-audit if: ${{ inputs.install-cargo-audit == 'true' }} shell: bash env: + CARGO_AUDIT_VERSION: ${{ inputs.cargo-audit-version }} CARGO_INSTALL_TARGET_DIR: ${{ inputs.install-target-dir }} run: | set -euo pipefail if ! command -v cargo-audit >/dev/null 2>&1; then - cargo install cargo-audit --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" + cargo install cargo-audit --version "$CARGO_AUDIT_VERSION" --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" + fi + + - name: Install mdbook + if: ${{ inputs.install-mdbook == 'true' }} + shell: bash + env: + MDBOOK_VERSION: ${{ inputs.mdbook-version }} + MDBOOK_MERMAID_VERSION: ${{ inputs.mdbook-mermaid-version }} + CARGO_INSTALL_TARGET_DIR: ${{ inputs.install-target-dir }} + run: | + set -euo pipefail + if ! command -v mdbook >/dev/null 2>&1; then + cargo install mdbook --version "$MDBOOK_VERSION" --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" + fi + if ! command -v mdbook-mermaid >/dev/null 2>&1; then + cargo install mdbook-mermaid --version "$MDBOOK_MERMAID_VERSION" --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" fi diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 53acb5d..edba7b5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,21 +42,5 @@ jobs: - name: Quality gate (fmt, clippy, build, test) run: just ci-rust - deny: - name: Dependency policy - runs-on: ubuntu-latest - if: false - timeout-minutes: 15 - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - with: - persist-credentials: false - - - name: Setup Rust, just, and cargo-deny - uses: ./.github/actions/setup-rust - with: - install-cargo-deny: "true" - - - name: Dependency policy - run: just deny +# The dependency-policy (cargo deny) job lives in security.yml — do not +# duplicate it here (sweep 2026-08-07 R9). diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 2dc71a0..a33cf6b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -36,8 +36,10 @@ jobs: - name: Install Nix uses: ./.github/actions/setup-nix - - name: Install just + - name: Install just and mdbook uses: ./.github/actions/setup-rust + with: + install-mdbook: "true" - name: Build book run: just docs diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 9ac1e32..b8005b5 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -12,11 +12,13 @@ on: - 'Cargo.toml' - 'Cargo.lock' - 'deny.toml' + - '.github/workflows/security.yml' pull_request: paths: - 'Cargo.toml' - 'Cargo.lock' - 'deny.toml' + - '.github/workflows/security.yml' workflow_dispatch: permissions: diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc new file mode 100644 index 0000000..56e0d7c --- /dev/null +++ b/.markdownlint-cli2.jsonc @@ -0,0 +1,34 @@ +{ + // markdownlint-cli2 configuration (sweep 2026-08-07 R6): one file, one + // source of truth — the old .markdownlint.jsonc (rules) and + // .markdownlintignore (never read by cli2) were consolidated here. + "config": { + // Prose is wrapped at 80; tables and code blocks legitimately exceed any fixed + // width (a multi-column row or a CLI line can't be 80 chars) and render fine. + "MD013": { "line_length": 80, "tables": false, "code_blocks": false }, + // Keep a Changelog repeats `### Added`/`### Changed` etc. under each release; + // allow same-named headings that are not siblings. + "MD024": { "siblings_only": true }, + // CLI blocks with `$` prompts that show expected output are fine. + "MD014": false, + // Mermaid blocks don't have a language tag. + "MD040": { "allowed_languages": ["mermaid", "", "text", "json", "nix", "console", "ini", "sh", "bash"] }, + // SUMMARY.md uses multiple `#` section headers for mdBook navigation. + "MD025": false, + // Table column style — reference docs use compact tables. + "MD060": false + }, + "ignores": [ + // mdBook build output. + "docs/book/", + // Generated at docs-build time from the root CHANGELOG.md. + "docs/src/changelog.md", + // SUMMARY.md uses mdBook-required syntax (multiple `#` section headers and + // 4-space-nested entries) that MD025/MD007 flag but mdBook needs. + "docs/src/SUMMARY.md", + // Verbatim upstream Contributor Covenant — not house prose. + ".github/CODE_OF_CONDUCT.md", + // PR templates intentionally start with "## Summary" — MD041 is wrong for them. + ".github/pull_request_template.md" + ] +} diff --git a/.markdownlint.jsonc b/.markdownlint.jsonc deleted file mode 100644 index e4140c4..0000000 --- a/.markdownlint.jsonc +++ /dev/null @@ -1,16 +0,0 @@ -{ - // Prose is wrapped at 80; tables and code blocks legitimately exceed any fixed - // width (a multi-column row or a CLI line can't be 80 chars) and render fine. - "MD013": { "line_length": 80, "tables": false, "code_blocks": false }, - // Keep a Changelog repeats `### Added`/`### Changed` etc. under each release; - // allow same-named headings that are not siblings. - "MD024": { "siblings_only": true }, - // CLI blocks with `$` prompts that show expected output are fine. - "MD014": false, - // Mermaid blocks don't have a language tag. - "MD040": { "allowed_languages": ["mermaid", "", "text", "json", "nix", "console", "ini", "sh", "bash"] }, - // SUMMARY.md uses multiple `#` section headers for mdBook navigation. - "MD025": false, - // Table column style — reference docs use compact tables. - "MD060": false -} diff --git a/.markdownlintignore b/.markdownlintignore deleted file mode 100644 index f4a6958..0000000 --- a/.markdownlintignore +++ /dev/null @@ -1,9 +0,0 @@ -# mdBook build output. -docs/book/ - -# Generated at docs-build time from the root CHANGELOG.md. -docs/src/changelog.md - -# SUMMARY.md uses mdBook-required syntax (multiple `#` section headers and -# 4-space-nested entries) that MD025/MD007 flag but mdBook needs. -docs/src/SUMMARY.md diff --git a/Justfile b/Justfile index 1a5eccb..e8a9bc5 100644 --- a/Justfile +++ b/Justfile @@ -63,6 +63,11 @@ docs-serve: trap 'rm -f docs/src/changelog.md' EXIT (cd docs && mdbook serve --open) +# Markdown prose lint (sweep 2026-08-07 R6; rules + ignores in +# .markdownlint-cli2.jsonc). markdownlint-cli2 version pinned. +lint-md: + npx --yes markdownlint-cli2@0.23.2 "**/*.md" + # ============================================================================= # Dependency policy # ============================================================================= diff --git a/docs/src/unsafe-code/index.md b/docs/src/unsafe-code/index.md index 6488f26..35fd50d 100644 --- a/docs/src/unsafe-code/index.md +++ b/docs/src/unsafe-code/index.md @@ -43,4 +43,7 @@ Note what is NOT in the inventory: `mlockall`, `setrlimit(Core, 0)`, and 6. **Write tests** — verify the mitigations work (or document why untestable) 7. **Get review** — unsafe requires explicit approval -The bar is intentionally high. Postmaster's design keeps plaintext custody to microseconds — decrypt at the last instant, zeroize immediately, never persist. A memory-safety bug is one of the few things that can silently break that invariant. +The bar is intentionally high. Postmaster's design keeps plaintext +custody to microseconds — decrypt at the last instant, zeroize +immediately, never persist. A memory-safety bug is one of the few +things that can silently break that invariant. diff --git a/docs/src/unsafe-code/macos-libc-boundary.md b/docs/src/unsafe-code/macos-libc-boundary.md index 34c046a..c053759 100644 --- a/docs/src/unsafe-code/macos-libc-boundary.md +++ b/docs/src/unsafe-code/macos-libc-boundary.md @@ -12,7 +12,7 @@ pages ([signal deferral](./signal-deferral.md), ### Location -``` +```text src/server.rs — fn peer_euid (macOS cfg only) ``` @@ -40,7 +40,7 @@ wrapper. ### Location -``` +```text src/server.rs — fn harden_process (macOS cfg, release builds only) ``` diff --git a/docs/src/unsafe-code/monitor.md b/docs/src/unsafe-code/monitor.md index 1ac3c8f..560ad53 100644 --- a/docs/src/unsafe-code/monitor.md +++ b/docs/src/unsafe-code/monitor.md @@ -2,7 +2,7 @@ ## Location -``` +```text src/monitor.rs — the monitor loop, liveness watches, signal ops, exit src/launcher.rs — the fork(2) site and both TerminationGuard legs (macOS + Linux) Unsafe blocks: fork(2) (libc, both platforms); rustix `runtime` diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md index d71033d..24d7ab4 100644 --- a/docs/src/unsafe-code/signal-deferral.md +++ b/docs/src/unsafe-code/signal-deferral.md @@ -2,7 +2,7 @@ ## Location -``` +```text src/launcher.rs — struct TerminationGuard (macOS and Linux legs) Blocks: block() (sigmask), restore_mask() (sigmask), Drop (restore) ``` diff --git a/docs/src/unsafe-code/systemd-fd-ownership.md b/docs/src/unsafe-code/systemd-fd-ownership.md index 85dd000..a4557e7 100644 --- a/docs/src/unsafe-code/systemd-fd-ownership.md +++ b/docs/src/unsafe-code/systemd-fd-ownership.md @@ -2,7 +2,7 @@ ## Location -``` +```text src/server.rs — socket-activation path (Linux cfg only) ``` diff --git a/docs/src/unsafe-code/test-env-mutation.md b/docs/src/unsafe-code/test-env-mutation.md index 2a1da7e..9f1cf94 100644 --- a/docs/src/unsafe-code/test-env-mutation.md +++ b/docs/src/unsafe-code/test-env-mutation.md @@ -2,7 +2,7 @@ ## Location -``` +```text src/test_util.rs — the shared ENV_LOCK itself src/keys/source.rs (test module) — 8 tests, 17 set/remove calls src/keys/env.rs (test module) — 2 tests, 8 set/remove calls diff --git a/lefthook.yml b/lefthook.yml index 9ba3fd3..9abbeda 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -8,8 +8,14 @@ pre-commit: run: just fmt-check lint: run: just clippy + lint-md: + run: just lint-md pre-push: commands: ci-rust: run: just ci-rust + deny: + run: just deny + audit: + run: just audit From 1860d84f03a82a3e6a8ce05dd9af495193e25465 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 16:38:35 -0500 Subject: [PATCH 30/47] docs: at-a-glance layer, monitor lifecycle diagram, pipeline dedup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - O24: monitor lifecycle as a mermaid sequence diagram in unsafe-code/monitor.md — fork/scrub/watch, stop forwarding with bounded grace, SIGKILL escalation, cleanup on every death path - O25: at-a-glance intros on the four unsafe-code pages that jumped straight into Location (signal-deferral, monitor, systemd-fd-ownership, test-env-mutation); the overview, cli.md, and macos-libc-boundary already open with plain-language framing - O26: the 5-stage pipeline stated in three places drifted once already (O5). postmaster.md keeps the canonical diagram + per-stage detail; introduction.md slims to the one-liner + link; README's one-liner gains the targeted link Battery: fmt, clippy (debug/release/linux-gnu), test (113 lib, 8 exec_check, 26 conformance), deny, audit, docs, lint-md. --- README.md | 4 +- docs/src/introduction.md | 41 +++----------------- docs/src/unsafe-code/monitor.md | 35 +++++++++++++++++ docs/src/unsafe-code/signal-deferral.md | 5 +++ docs/src/unsafe-code/systemd-fd-ownership.md | 5 +++ docs/src/unsafe-code/test-env-mutation.md | 5 +++ 6 files changed, 59 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index e834629..18993db 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,9 @@ Postmaster is the local secret materialization stage in a 5-stage pipeline: custody (Vault/SSM/1Password/TPM2) → rendering (Nix/Terraform/ CDK/Ansible/Salt/Puppet) → delivery (credentials/files/keychain/env) → materialization (postmaster) → launch (execvp). Each stage is owned by a -different system; postmaster owns exactly materialization. +different system; postmaster owns exactly materialization. The +stage-by-stage breakdown lives in +[The secret pipeline](docs/src/architecture/postmaster.md#the-secret-pipeline). The `exec.json` contract and `postmaster exec --check` conformance suite are the interface between postmaster and every integration. An diff --git a/docs/src/introduction.md b/docs/src/introduction.md index 1804042..7abbd23 100644 --- a/docs/src/introduction.md +++ b/docs/src/introduction.md @@ -100,41 +100,12 @@ stops being an adversary. The entire secret surface collapses to one ## The Secret Pipeline -Postmaster owns exactly one stage in a 5-stage pipeline. Understanding -which stage each system owns is the key to understanding what postmaster -is (and is not). - -```mermaid -flowchart LR - subgraph s1["1. Custody"] - vault["Vault / SSM /\n1Password / TPM2"] - end - subgraph s2["2. Rendering"] - nix["Nix / Terraform /\nCDK / Ansible"] - end - subgraph s3["3. Delivery"] - cred["systemd cred /\nfile / keychain"] - end - subgraph s4["4. Materialization"] - pm["postmaster\ndecrypt + inject"] - end - subgraph s5["5. Launch"] - exec["execvp\nchild = MainPID"] - end - - vault --> nix - nix --> cred - cred --> pm - pm --> exec -``` - -| Stage | Who owns it | What happens | -| ----- | ----------- | ------------ | -| 1. Custody | Vault, AWS SSM, 1Password, TPM2 | Private keys live in a source/custody system | -| 2. Rendering | Nix, Terraform, CDK, Ansible, Salt, Puppet | Encrypted artifacts + key material + service wiring get onto the host | -| 3. Delivery | systemd, files, keychain, env | Key material reaches postmaster at runtime via local sources | -| 4. Materialization | **postmaster** | Postmaster decrypts and injects — this is the only stage it owns | -| 5. Launch | execvp | Process image replaced; child binary is MainPID | +Postmaster owns exactly one stage in a 5-stage pipeline: custody +(Vault/SSM/1Password/TPM2) → rendering (Nix/Terraform/CDK/Ansible) → +delivery (systemd credentials/files/keychain/env) → **materialization +(postmaster)** → launch (execvp). The stage diagram, table, and +per-stage detail live in +[postmaster — the secret pipeline](./architecture/postmaster.md#the-secret-pipeline). Postmaster does not participate in stages 1-3. It does not fetch from remote systems, does not deploy infrastructure, and owns no service diff --git a/docs/src/unsafe-code/monitor.md b/docs/src/unsafe-code/monitor.md index 560ad53..b83c754 100644 --- a/docs/src/unsafe-code/monitor.md +++ b/docs/src/unsafe-code/monitor.md @@ -1,5 +1,40 @@ # Sibling Launch Monitor +> **At a glance:** a tiny forked sibling — born after every secret has +> been zeroized — watches the service for its whole life. It forwards +> stop signals, escalates to SIGKILL after a short grace, and deletes +> plaintext secret files on every death path, including `kill -9`. + +## Lifecycle + +```mermaid +sequenceDiagram + participant L as Launcher (parent) + participant M as Monitor (fork-child) + participant S as Service (exec'd parent) + + L->>L: zeroize plaintext; block stop signals + L->>M: fork() + Note over M: scrub inherited env pairs (wipe_pair); mask stays blocked for life + L->>S: restore mask; execvp becomes service + loop poll tick + M->>S: liveness (pidfd+poll / kqueue NOTE_EXIT) + M->>M: stop signal pending? (sigpending then sigwait) + end + alt stop signal (TERM/INT/HUP/QUIT) + M->>S: forward the signal + Note over M,S: bounded grace (250 ms) + alt service exits within the grace + M->>M: cleanup plaintext files; exit 0 + else grace expires + M->>S: SIGKILL + M->>M: cleanup plaintext files; exit 0 + end + else service death (exit, crash, kill -9) + M->>M: cleanup plaintext files; exit 0 + end +``` + ## Location ```text diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md index 24d7ab4..2d4ae35 100644 --- a/docs/src/unsafe-code/signal-deferral.md +++ b/docs/src/unsafe-code/signal-deferral.md @@ -1,5 +1,10 @@ # Signal Deferral (TerminationGuard) +> **At a glance:** while postmaster decrypts and injects, termination +> signals are blocked so a well-timed `Ctrl-C` or `systemctl stop` +> cannot strand half-written plaintext. The original mask is captured +> and restored before launch — the service never inherits it. + ## Location ```text diff --git a/docs/src/unsafe-code/systemd-fd-ownership.md b/docs/src/unsafe-code/systemd-fd-ownership.md index a4557e7..2ac8db1 100644 --- a/docs/src/unsafe-code/systemd-fd-ownership.md +++ b/docs/src/unsafe-code/systemd-fd-ownership.md @@ -1,5 +1,10 @@ # systemd fd Ownership (Linux) +> **At a glance:** on Linux, systemd hands postmaster ready-made +> sockets as inherited file descriptors. Adopting them is the one +> `unsafe` act on the serving path — valid exactly because systemd's +> `sd_listen_fds(3)` contract says which descriptors they are. + ## Location ```text diff --git a/docs/src/unsafe-code/test-env-mutation.md b/docs/src/unsafe-code/test-env-mutation.md index 9f1cf94..2744828 100644 --- a/docs/src/unsafe-code/test-env-mutation.md +++ b/docs/src/unsafe-code/test-env-mutation.md @@ -1,5 +1,10 @@ # Test-Only env Mutation +> **At a glance:** some tests must change the process environment, +> which Rust 2024 marks `unsafe` because it can race other threads. +> Every such test holds one shared process-wide lock, so env-mutating +> tests can never run — or race — concurrently. + ## Location ```text From 1bbe63d4c9b8dba553600c04b1cb53cf485fbd23 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 16:40:01 -0500 Subject: [PATCH 31/47] docs: executive overview page for leadership and PM audiences One page, no code: what postmaster is, the plaintext-lifetime problem it collapses, what it guarantees (no plaintext at rest, publishable ciphertext, small audited surface, fail closed), what it does not do, operational footprint, and assurance posture. Registered in SUMMARY.md after the introduction; the introduction's audience table now routes management/ELT and product/project management to it. Battery: fmt, clippy (debug/release/linux-gnu), test (113 lib, 8 exec_check, 26 conformance), deny, audit, docs, lint-md. --- docs/src/SUMMARY.md | 2 + docs/src/executive-overview.md | 84 ++++++++++++++++++++++++++++++++++ docs/src/introduction.md | 2 +- 3 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 docs/src/executive-overview.md diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index f0c9368..37fe6ec 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -2,6 +2,8 @@ [Introduction](./introduction.md) +[Executive overview](./executive-overview.md) + # Getting Started - [Quick start](./getting-started/quick-start.md) diff --git a/docs/src/executive-overview.md b/docs/src/executive-overview.md new file mode 100644 index 0000000..dec2cdf --- /dev/null +++ b/docs/src/executive-overview.md @@ -0,0 +1,84 @@ +# Executive overview + +A one-page briefing on postmaster for engineering leadership and +product/project management. No code, no commands — what it is, why it +exists, and what it does and does not promise. + +## What it is + +postmaster is a small, single-purpose Unix tool that decrypts a +service's secrets at launch time and hands them directly to the +service — then removes itself from the picture. It replaces the common +practice of shell scripts or long-lived helper processes holding +plaintext secrets in memory for the service's entire lifetime. + +## The problem it solves + +Most deployments get secrets to production one of a few ways, and each +leaves plaintext somewhere an incident can reach it: + +- **Plaintext files on disk** — readable by any process, any backup + job, any accidental `cat` in a debugging session. +- **Deploy-time environment variables** — visible in process listings, + unit files, and crash dumps. +- **Wrapper scripts and parent processes** — keep decrypted secrets in + a long-lived process's memory for as long as the service runs. + +The common thread is plaintext with a long lifetime and a wide blast +radius. postmaster's entire design is collapsing that lifetime to +microseconds and that radius to one process. + +## What it guarantees + +- **No plaintext at rest.** Decrypted secrets exist only in memory, + in the moments between decryption and launch. Where a deployment + mode needs files, they live on a ramdisk and are deleted on every + service-death path — including `kill -9` — by a dedicated monitor + process. +- **Ciphertext is safe to publish.** Encrypted secret files can live + in git or a world-readable artifact store; only one 64-character + private key per environment needs protection, and it can itself be + sealed to the host (TPM2) or held in the macOS keychain. +- **Small, auditable surface.** One dependency-lean Rust binary, no + network client, no plugin system, no shell in the runtime path. + Every `unsafe` block is catalogued with its justification and + mitigations. +- **Fail closed.** A missing key, a stale key, or a malformed config + stops the launch loudly and names the problem — a service never + starts with partial or wrong secrets. + +## What it does not do + +- It is not a secret store and does not replace Vault, SSM, or + 1Password — those systems keep custody of keys. postmaster is the + last hop, and it will never grow a network client for them. +- It does not supervise services (restarts, health checks) — that + stays with systemd/launchd. Its tiny monitor process handles only + stop-signal forwarding and secret cleanup. +- It does not hold secrets over time: the process that decrypted them + is gone the moment the service binary starts. + +## Operational footprint + +- One small Rust binary per host; one tiny monitor process per service + for the service's lifetime. +- Linux (systemd) and macOS (launchd); no kernel modules, no network + calls, no privileges beyond what the service itself needs. +- Rollout is per-service and reversible: postmaster wraps the existing + launch command. + +## Assurance posture + +- Pure-Rust cryptography — no openssl in the binary. +- An executable conformance suite mirrors the documented launch + contract, so documented behavior is tested behavior. +- Every finding from the 2026-08 security audits is fixed and listed + in the changelog with its finding ID. + +## Where to go next + +| Audience | Read | +| -------- | ---- | +| Engineering leadership | This page, then the [Threat model](./architecture/threat-model.md) | +| Product / project management | This page and the [Introduction](./introduction.md) | +| Engineers integrating a service | [Quick start](./getting-started/quick-start.md) | diff --git a/docs/src/introduction.md b/docs/src/introduction.md index 7abbd23..6a164af 100644 --- a/docs/src/introduction.md +++ b/docs/src/introduction.md @@ -22,7 +22,7 @@ holds secrets in memory. | Platform / SRE | [Key provisioning](./getting-started/key-provisioning.md) and the [Threat model](./architecture/threat-model.md) | | Security engineer | The [Threat model](./architecture/threat-model.md) and [Materialization ABI](./architecture/materialization-abi.md) | | Integration author | The [Launcher contract](./reference/launcher-contract.md) and [CLI reference](./reference/cli.md) | -| Product / project manager | This introduction and the [postmaster](./architecture/postmaster.md) overview | +| Product / project manager, engineering leadership | The [Executive overview](./executive-overview.md), then this introduction | ### Quick glossary From fadcc6d65d6913c00c1fdcc73b8f1ae6fa64cdb8 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Fri, 7 Aug 2026 16:42:41 -0500 Subject: [PATCH 32/47] docs(changelog): record the 2026-08-07 clean sweep + e1f1c21 (O27) - the missing e1f1c21 bundle-ring fix (user-visible: every bundle exec failed at the ring) now has its entry - the 2026-08-07 sweep: security tightenings, darwin serve fix, schema realignment, conformance/coverage additions, docs layering, CI/repo housekeeping - the 2026-08-02 disposition parenthetical now matches the vault record (all fixed/resolved except A14, A18, A24-stale, A25) instead of the garbled 12+4 != 17 arithmetic Battery: docs build + lint-md green (full battery + 10x test shake green immediately prior). --- CHANGELOG.md | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00c8344..9e45156 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Security - Remediated all 33 findings of the 2026-08-02 security audit (5 HIGH, - 11 MEDIUM, 17 LOW/INFO — 12 fixed, 4 documented as accepted). + 11 MEDIUM, 17 LOW/INFO — all fixed or resolved except four documented + as accepted: A14, A18, A24-stale, A25). - Bundle entries are now name-bound: a ciphertext decrypts only under its own entry name (AES-GCM AAD); relocating it fails authentication. Suite bumped to `ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad`; @@ -35,6 +36,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 fields (root and nested); Linux `id` resolved from verified absolute paths only; setup verification reuses the runtime key-variable predicate; bundle `encoding: "utf8"` is validated at resolution. +- Remediated all 60 findings of the 2026-08-07 full-repo clean sweep + (code, tests, docs, repo files): redacted `Debug` on `KeyRing` and + `Resolution` (latent key-material/plaintext leak channels); env key + loading skips non-UTF-8 entries instead of panicking under + panic=abort; credential-source stat errors are terminal rather than + fall-through; `setup --force` is real (keychain re-seed, keys-file + re-prompt; force+unattended fails closed); daemon refuses a symlinked + socket parent and non-absolute config paths, and rejects empty + credentials at preflight; `--allow-nonroot` no longer overrides a + configured `peer_user` ACL; ramdisk verification enforces lexical + path containment; NUL in an env-bound bundle value is a hard error + under any strictness (one rule for every env-bound value). ### Changed @@ -47,6 +60,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 (setup-rust, setup-nix — the latter verifies the pinned installer's sha256 before executing), actions pinned by sha, workflows consume just recipes. +- Monitor tests extracted to `src/monitor/tests.rs` (`monitor.rs` + 797 → 503 lines, same module path and visibility). +- Markdown linting consolidated into `.markdownlint-cli2.jsonc` (cli2 + never read `.markdownlintignore`); the two dead config files were + deleted and `just lint-md` (pinned markdownlint-cli2) now gates in + lefthook pre-commit, with `deny`+`audit` in pre-push. +- CI housekeeping: the duplicated `deny` job left ci.yml (security.yml + owns it), security.yml's path filters include the workflow file + itself, the docs job installs a pinned mdbook/mdbook-mermaid, and + cargo-deny/cargo-audit installs are version-pinned. +- `ci-rust` now includes `clippy-release` and `clippy-linux` recipes, + and rust-toolchain.toml pins the `x86_64-unknown-linux-gnu` target. ### Added @@ -55,6 +80,52 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ownership, test-only env mutation). - `multiple_crate_versions` clippy lint plus `[bans] multiple-versions` in deny.toml (syn skipped for the wasm-gated duplicate). +- Daemon end-to-end conformance (`tests/exec_conformance/daemon.rs`): + the real binary under `--bind --allow-nonroot`, a real `fetch` + roundtrip with a socket-mode assertion, and preflight refusal before + any bind. +- Regression coverage across the sweep's audit seams: the `read_capped` + cap boundary, symlink refusal end-to-end (env file, bundle file, + secrets dir), execvp-failure cleanup leaving only the sentinel, + passthrough-NUL cleanup, bundle precedence and NUL semantics, + provisioning primitive modes, the positive credential-source leg, and + the monitor's pre-dead-service leg. +- Executive overview page (leadership/PM audience) plus at-a-glance + intros across the unsafe-code section and a monitor lifecycle + mermaid diagram. + +### Fixed + +- Bundle configs resolve keys end-to-end again: `load_ring` admitted + only `DOTENV_PRIVATE_KEY*` (Env naming) at every source leg, so + `POSTMASTER_KEY` never entered the ring and every bundle exec failed + ("key ring has no POSTMASTER_KEY entry"). The ring now admits exactly + the namings the config's artifacts require — no more (least + privilege), no less. (e1f1c21; sweep O27) +- Darwin serve mode starts: `acquire_listeners` fchmod()ed the bound + socket fd (audit 2026-08-02 finding #7), but Darwin `fchmod(2)` + rejects socket fds (EINVAL) — every `--bind` startup failed. Socket + permissions are now umask-borne at bind time on darwin (no TOCTOU + window; Linux keeps the fd-based fchmod). Caught by the new daemon + end-to-end conformance test. +- `docs/schema/exec.schema.json` realigned with the parser: + `bundle_files` added, env/files modes accept `env_files` and/or + `bundle_files`, credentials mode rejects `bundle_files`, and the `$id` + points at postmaster — guarded by a fields-vs-schema tripwire test + and a new bundle example. +- Docs factual sweep (30+ corrections): a phantom exit code 2, `env` + mislabeled as the default mode, argv-exposing keychain seeding + examples, a store-path key-source example the parser rejects, "does + not supervise" contradicting the sibling monitor, stale unsafe-code + counts, undocumented `POSTMASTER_KEY` and 16 MiB read cap, and + envelope/dotenvx naming in the examples. + +### Removed + +- Dead `/postmaster/target/` gitignore line and the inert `docs/book/` + gitattributes pattern (gitattributes has no dir-recursion syntax). +- Duplicated `key_var_for` test copies in keys/exec_config (the legs + live in adapter/mod.rs where the mapping lives). ## [0.1.0] - 2026-07-28 From 9550ec1891561d505f1341896627a747b775047d Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Sat, 7 Nov 2026 23:04:41 -0600 Subject: [PATCH 33/47] fix: isolate launch keys and own bundle AAD decoding Strip reserved private-key variables from launched applications and align bundle precedence with dotenv inputs. Decode authenticated bundle envelopes locally while retaining released ECIES compatibility and license notices. Update dependencies, preserve build-matrix flags and profile settings, and align documentation with runtime behavior and deployment requirements. --- .gitignore | 5 + .markdownlint-cli2.jsonc | 2 + CHANGELOG.md | 74 ++--- Cargo.lock | 290 ++++++++++++------- Cargo.toml | 23 +- Justfile | 111 ++++--- README.md | 45 +-- deny.toml | 5 +- docs/src/architecture/materialization-abi.md | 43 ++- docs/src/architecture/postmaster.md | 61 ++-- docs/src/architecture/threat-model.md | 205 +++++++------ docs/src/executive-overview.md | 104 +++---- docs/src/getting-started/injection-modes.md | 27 +- docs/src/getting-started/quick-start.md | 6 +- docs/src/introduction.md | 30 +- docs/src/reference/cli.md | 2 +- docs/src/reference/launcher-contract.md | 91 +++--- docs/src/unsafe-code/index.md | 7 +- docs/src/unsafe-code/macos-libc-boundary.md | 6 +- docs/src/unsafe-code/monitor.md | 37 ++- docs/src/unsafe-code/signal-deferral.md | 30 +- docs/src/unsafe-code/test-env-mutation.md | 6 +- licenses/ecies-MIT.txt | 21 ++ nixpkgs-package.nix | 4 - package.nix | 10 +- src/aad.rs | 90 ++++++ src/aad/vectors.json | 22 ++ src/adapter/bundle.rs | 50 ++-- src/adapter/mod.rs | 6 +- src/cli/mod.rs | 20 +- src/exec_config.rs | 13 +- src/keys/env.rs | 9 +- src/keys/mod.rs | 19 +- src/keys/provisioning/mod.rs | 7 +- src/keys/verify.rs | 6 +- src/launcher.rs | 67 +++-- src/lib.rs | 1 + src/monitor.rs | 19 +- src/monitor/tests.rs | 8 +- src/ramdisk.rs | 12 +- src/secret_files.rs | 15 +- src/server.rs | 53 ++-- src/test_util.rs | 5 +- src/test_util/aad_fixture.rs | 26 ++ tests/common/mod.rs | 3 + tests/exec_conformance/bundle.rs | 201 ++++++++++++- tests/exec_conformance/main.rs | 2 + 47 files changed, 1226 insertions(+), 673 deletions(-) create mode 100644 licenses/ecies-MIT.txt create mode 100644 src/aad.rs create mode 100644 src/aad/vectors.json create mode 100644 src/test_util/aad_fixture.rs diff --git a/.gitignore b/.gitignore index 0f8f735..bf88633 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,8 @@ docs/src/changelog.md target/ docs/superpowers/ .superpowers/ +.aider* +.crush/ + +# zvec-grep workspace index — local, per-machine, rebuilt with `zg index` +.zvec-grep/ diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc index 56e0d7c..4c3ffad 100644 --- a/.markdownlint-cli2.jsonc +++ b/.markdownlint-cli2.jsonc @@ -19,6 +19,8 @@ "MD060": false }, "ignores": [ + // Cargo and Rustdoc build output. + "target/", // mdBook build output. "docs/book/", // Generated at docs-build time from the root CHANGELOG.md. diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e45156..0d5bf0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,15 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Security -- Remediated all 33 findings of the 2026-08-02 security audit (5 HIGH, - 11 MEDIUM, 17 LOW/INFO — all fixed or resolved except four documented - as accepted: A14, A18, A24-stale, A25). +- Launched applications no longer inherit private-key variables from either + adapter namespace, regardless of key source or projection mode. Bundle + entries using reserved private-key names are rejected before launch. - Bundle entries are now name-bound: a ciphertext decrypts only under its own entry name (AES-GCM AAD); relocating it fails authentication. Suite bumped to `ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad`; - pre-AAD bundles are rejected. AAD support comes from the additive - `encrypt_with_aad`/`decrypt_with_aad` on the ecies fork (upstream PR - ecies/rs#159), consumed via a git+rev `[patch.crates-io]` pin. + pre-AAD bundles are rejected. Postmaster owns the compatible AAD envelope + decoder, using released `ecies` curve/HKDF helpers and RustCrypto AES-GCM. - Hardening: a sibling launch monitor now owns stop semantics on the exec path — the launcher forks after zeroization, the parent execs the service (MainPID unchanged), and the fork-child supervises it: @@ -36,26 +35,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 fields (root and nested); Linux `id` resolved from verified absolute paths only; setup verification reuses the runtime key-variable predicate; bundle `encoding: "utf8"` is validated at resolution. -- Remediated all 60 findings of the 2026-08-07 full-repo clean sweep - (code, tests, docs, repo files): redacted `Debug` on `KeyRing` and - `Resolution` (latent key-material/plaintext leak channels); env key - loading skips non-UTF-8 entries instead of panicking under - panic=abort; credential-source stat errors are terminal rather than - fall-through; `setup --force` is real (keychain re-seed, keys-file - re-prompt; force+unattended fails closed); daemon refuses a symlinked - socket parent and non-absolute config paths, and rejects empty - credentials at preflight; `--allow-nonroot` no longer overrides a - configured `peer_user` ACL; ramdisk verification enforces lexical - path containment; NUL in an env-bound bundle value is a hard error - under any strictness (one rule for every env-bound value). +- Hardening: redacted `Debug` on `KeyRing` and `Resolution` (latent + key-material/plaintext leak channels); env key loading skips non-UTF-8 + entries instead of panicking under panic=abort; credential-source + stat errors are terminal rather than fall-through; `setup --force` is + real (keychain re-seed, keys-file re-prompt; force+unattended fails + closed); daemon refuses a symlinked socket parent and non-absolute + config paths, and rejects empty credentials at preflight; + `--allow-nonroot` no longer overrides a configured `peer_user` ACL; + ramdisk verification enforces lexical path containment; NUL in an + env-bound bundle value is a hard error under any strictness (one rule + for every env-bound value). ### Changed +- Build matrix preserves compiler flags and profile environment overrides, + uses `cargo zigbuild` for cross builds, and remaps source paths at `max`. + Help describes the configured release profile without performance estimates. +- Bundle files follow the same first-file-wins precedence as dotenv inputs; + `overload` selects the last definition. Dotenv files precede bundle files. - Module restructure per file-size limits (500/750/1000 LOC bands): `keys/`, `cli/`, `adapter/` domains; conformance suite split under `tests/exec_conformance/`. -- Dependencies: base64 0.23 plus the minor/patch set (libc 0.2.189, - serde family 1.0.229, serde_json 1.0.151, syn 3.0.3). +- Dependencies: base64 0.23.1, ecies 0.2.13, serde 1.0.229, + serde_json 1.0.154, zeroize 1.9.1, rustix 1.1.6, and libc 0.2.191. + The ECIES git patch is replaced by registry releases; AES-GCM 0.11.1 + provides bundle authentication with key-schedule zeroization enabled. - CI automation conforms to the repo doctrine: in-repo composites only (setup-rust, setup-nix — the latter verifies the pinned installer's sha256 before executing), actions pinned by sha, workflows consume @@ -84,7 +89,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 the real binary under `--bind --allow-nonroot`, a real `fetch` roundtrip with a socket-mode assertion, and preflight refusal before any bind. -- Regression coverage across the sweep's audit seams: the `read_capped` +- Regression coverage across secret-handling edges: the `read_capped` cap boundary, symlink refusal end-to-end (env file, bundle file, secrets dir), execvp-failure cleanup leaving only the sentinel, passthrough-NUL cleanup, bundle precedence and NUL semantics, @@ -96,27 +101,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Documentation matches strict-mode exceptions, dotenv interpolation, bundle + metadata, monitor inheritance, and deployment hardening requirements. + Rustdoc placeholders render as code, and the overview states protections + without timing claims or unconditional cleanup guarantees. - Bundle configs resolve keys end-to-end again: `load_ring` admitted only `DOTENV_PRIVATE_KEY*` (Env naming) at every source leg, so `POSTMASTER_KEY` never entered the ring and every bundle exec failed ("key ring has no POSTMASTER_KEY entry"). The ring now admits exactly the namings the config's artifacts require — no more (least - privilege), no less. (e1f1c21; sweep O27) + privilege), no less. - Darwin serve mode starts: `acquire_listeners` fchmod()ed the bound - socket fd (audit 2026-08-02 finding #7), but Darwin `fchmod(2)` - rejects socket fds (EINVAL) — every `--bind` startup failed. Socket - permissions are now umask-borne at bind time on darwin (no TOCTOU - window; Linux keeps the fd-based fchmod). Caught by the new daemon - end-to-end conformance test. + socket fd, but Darwin `fchmod(2)` rejects socket fds (EINVAL) — every + `--bind` startup failed. Socket permissions are now umask-borne at + bind time on darwin (no TOCTOU window; Linux keeps the fd-based + fchmod). Caught by the new daemon end-to-end conformance test. - `docs/schema/exec.schema.json` realigned with the parser: `bundle_files` added, env/files modes accept `env_files` and/or `bundle_files`, credentials mode rejects `bundle_files`, and the `$id` points at postmaster — guarded by a fields-vs-schema tripwire test and a new bundle example. -- Docs factual sweep (30+ corrections): a phantom exit code 2, `env` - mislabeled as the default mode, argv-exposing keychain seeding - examples, a store-path key-source example the parser rejects, "does - not supervise" contradicting the sibling monitor, stale unsafe-code +- Documentation corrections: a phantom exit code 2, `env` mislabeled as + the default mode, argv-exposing keychain seeding examples, a + store-path key-source example the parser rejects, "does not + supervise" contradicting the sibling monitor, stale unsafe-code counts, undocumented `POSTMASTER_KEY` and 16 MiB read cap, and envelope/dotenvx naming in the examples. @@ -170,7 +178,3 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Child reads secrets via `$KEY_FILE` pointers (Docker secrets / systemd credentials / 12-factor `_FILE` convention). - `verify_key_freshness` uses `KeyNaming::Env.metadata_prefix()`. -- Two security audits conducted (provider handoff + destination - handoff), all findings fixed. -- Memory hardening audit conducted, all findings fixed. -- 12 verified-safe security properties documented in the threat model. diff --git a/Cargo.lock b/Cargo.lock index 454b39f..97576cb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,44 +4,52 @@ version = 4 [[package]] name = "aead" -version = "0.5.2" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" dependencies = [ "crypto-common", - "generic-array", + "inout", ] [[package]] name = "aes" -version = "0.8.4" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" dependencies = [ - "cfg-if", "cipher", + "cpubits", "cpufeatures", + "zeroize", ] [[package]] name = "aes-gcm" -version = "0.10.3" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f" dependencies = [ "aead", "aes", "cipher", "ctr", + "ctutils", "ghash", - "subtle", + "zeroize", ] +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "base16ct" -version = "0.2.0" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" [[package]] name = "base64" @@ -57,11 +65,11 @@ checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" [[package]] name = "block-buffer" -version = "0.10.4" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" dependencies = [ - "generic-array", + "hybrid-array", ] [[package]] @@ -78,19 +86,26 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "cipher" -version = "0.4.4" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ + "block-buffer", "crypto-common", "inout", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "const-oid" -version = "0.9.6" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" [[package]] name = "core-foundation" @@ -108,11 +123,17 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" -version = "0.2.17" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" dependencies = [ "libc", ] @@ -125,40 +146,53 @@ checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" [[package]] name = "crypto-bigint" -version = "0.5.5" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" dependencies = [ - "generic-array", - "rand_core", + "cpubits", + "ctutils", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", "subtle", "zeroize", ] [[package]] name = "crypto-common" -version = "0.1.7" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ - "generic-array", - "typenum", + "hybrid-array", + "rand_core 0.10.1", ] [[package]] name = "ctr" -version = "0.9.2" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" dependencies = [ "cipher", ] +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", + "subtle", +] + [[package]] name = "der" -version = "0.7.10" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" dependencies = [ "const-oid", "zeroize", @@ -166,13 +200,13 @@ dependencies = [ [[package]] name = "digest" -version = "0.10.7" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer", "crypto-common", - "subtle", + "ctutils", ] [[package]] @@ -183,8 +217,9 @@ checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" [[package]] name = "ecies" -version = "0.2.11" -source = "git+https://github.com/beardedeagle/rs.git?rev=81e1b84#81e1b840d99f2787b5c208f8172a496be304daf5" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05585cd8ca04e63c7bb5d7308fd7583cc8df9fcf3e6ff9132562c57209a7f231" dependencies = [ "aes-gcm", "getrandom", @@ -193,7 +228,7 @@ dependencies = [ "lock_api", "once_cell", "parking_lot", - "rand_core", + "rand_core 0.6.4", "sha2", "typenum", "wasm-bindgen", @@ -201,16 +236,17 @@ dependencies = [ [[package]] name = "elliptic-curve" -version = "0.13.8" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" dependencies = [ "base16ct", "crypto-bigint", + "crypto-common", "ff", - "generic-array", "group", - "rand_core", + "hybrid-array", + "rand_core 0.10.1", "sec1", "subtle", "zeroize", @@ -228,11 +264,11 @@ dependencies = [ [[package]] name = "ff" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" dependencies = [ - "rand_core", + "rand_core 0.10.1", "subtle", ] @@ -260,17 +296,6 @@ dependencies = [ "slab", ] -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", - "zeroize", -] - [[package]] name = "getrandom" version = "0.2.17" @@ -286,22 +311,22 @@ dependencies = [ [[package]] name = "ghash" -version = "0.5.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" dependencies = [ - "opaque-debug", "polyval", + "zeroize", ] [[package]] name = "group" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" dependencies = [ "ff", - "rand_core", + "rand_core 0.10.1", "subtle", ] @@ -313,29 +338,40 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "hkdf" -version = "0.12.4" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" dependencies = [ "hmac", ] [[package]] name = "hmac" -version = "0.12.1" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ "digest", ] +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "subtle", + "typenum", + "zeroize", +] + [[package]] name = "inout" -version = "0.1.4" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" dependencies = [ - "generic-array", + "hybrid-array", ] [[package]] @@ -357,20 +393,21 @@ dependencies = [ [[package]] name = "k256" -version = "0.13.4" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" +checksum = "93f50113171a713f4a4231ef82eb26703607139b35dcb56241f0ceab2ae1f7d8" dependencies = [ - "cfg-if", + "cpubits", "elliptic-curve", - "once_cell", + "primeorder", + "wnaf", ] [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "linux-raw-sys" @@ -393,6 +430,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -403,12 +449,6 @@ dependencies = [ "portable-atomic", ] -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - [[package]] name = "parking_lot" version = "0.12.5" @@ -440,14 +480,14 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "polyval" -version = "0.6.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" dependencies = [ - "cfg-if", + "cpubits", "cpufeatures", - "opaque-debug", "universal-hash", + "zeroize", ] [[package]] @@ -460,6 +500,7 @@ checksum = "3d20d5497ef88037a52ff98267d066e7f11fcc5e99bbfbd58a42336193aacec3" name = "postmaster" version = "0.1.0" dependencies = [ + "aes-gcm", "base64", "dotenvy", "ecies", @@ -472,6 +513,32 @@ dependencies = [ "zeroize", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint", + "crypto-common", + "ff", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve", + "once_cell", + "primefield", + "wnaf", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -499,6 +566,12 @@ dependencies = [ "getrandom", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -510,9 +583,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", @@ -535,13 +608,14 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sec1" -version = "0.7.3" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" dependencies = [ "base16ct", + "ctutils", "der", - "generic-array", + "hybrid-array", "subtle", "zeroize", ] @@ -601,9 +675,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.151" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -614,9 +688,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.10.9" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", "cpufeatures", @@ -677,20 +751,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "universal-hash" -version = "0.5.1" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" dependencies = [ "crypto-common", - "subtle", + "ctutils", ] -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -757,11 +825,23 @@ dependencies = [ "windows-link", ] +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff", + "group", + "hybrid-array", + "primefield", +] + [[package]] name = "zeroize" -version = "1.9.0" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" [[package]] name = "zmij" diff --git a/Cargo.toml b/Cargo.toml index 7e624c0..9464646 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "postmaster" version = "0.1.0" edition = "2024" -rust-version = "1.96.1" +rust-version = "1.99.1" description = "standalone, format-neutral local secret materialization engine" license = "MIT" repository = "https://github.com/beardedeagle/postmaster" @@ -99,7 +99,9 @@ used_underscore_binding = "warn" # Wire-compatible with eciesjs (dotenvx's crypto): secp256k1 + HKDF-SHA256 + # AES-256-GCM with the ecies family's 16-byte nonce default. `pure` selects # the RustCrypto AES backend — no openssl in the closure. -ecies = { version = "0.2.11", default-features = false, features = ["pure", "secp256k1", "std"] } +ecies = { version = "0.2.13", default-features = false, features = ["pure", "secp256k1", "std"] } +# The bundle adapter owns its AAD envelope; RustCrypto performs AES-GCM. +aes-gcm = { version = "0.11.1", default-features = false, features = ["aes", "zeroize"] } dotenvy = "0.15" serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -111,19 +113,13 @@ zeroize = "1" # single fd-ownership assertion at the systemd socket-activation boundary. rustix = { version = "1", features = ["net", "process", "mm", "fs"] } -# AAD support for the bundle adapter (audit 2026-08-02 A7) lives on the -# `aad-support` branch of the author's ecies fork pending the upstream PR -# against ecies/rs. Pinned by rev for reproducibility; drop this section -# once the PR merges and ships in a crates.io release. -[patch.crates-io] -ecies = { git = "https://github.com/beardedeagle/rs.git", rev = "81e1b84" } - [target.'cfg(target_os = "linux")'.dependencies] # Linux-only additions for the sibling launch monitor # (docs/src/unsafe-code/monitor.md): # - rustix "runtime": the monitor's signal ops (mask for life, synchronous # consumption) use kernel_sigprocmask/kernel_sigpending/kernel_sigwait — -# rustix's experimental, doc-hidden runtime API — so the Linux leg stays +# rustix's experimental runtime API (exported under a rotating module +# name) — so the Linux leg stays # on linux_raw with NO libc signal FFI. Cargo.lock pins the exact rustix; # an update that changes this unstable API fails the build loudly, # never silently. @@ -150,10 +146,9 @@ opt-level = 3 lto = "fat" codegen-units = 1 strip = "symbols" -# PT_DENY_ATTACH (macOS hardening) is gated on not(debug_assertions); pin -# this so a profile override can't silently compile it out (audit -# 2026-08-02 A23). This is already the release default — explicitness is -# the guard. +# PT_DENY_ATTACH (macOS hardening) is gated on not(debug_assertions). +# Keep release builds covered by default; enabling debug assertions through +# a profile or environment override disables that call. debug-assertions = false # Arithmetic bugs become panic → abort → Restart=on-failure: fail closed, # never a wrong answer. Cost is ~nil (crypto deps use wrapping intrinsics). diff --git a/Justfile b/Justfile index e8a9bc5..c85c85b 100644 --- a/Justfile +++ b/Justfile @@ -91,9 +91,9 @@ ci: ci-rust flake-check # # Optimization Levels: # debug - Fast compile, no optimizations, debug symbols (for development) -# release - Cargo defaults (opt-level=3, no LTO) -# optimized - Thin LTO + single codegen unit (good balance of size/speed) -# max - Fat LTO + strip + CPU targeting (smallest, fastest binary) +# release - Cargo.toml release profile (opt-level=3, fat LTO, stripped) +# optimized - Release profile with thin LTO and one codegen unit +# max - Release profile with CPU targeting and source path remapping # # Targets: # native - Current platform @@ -110,7 +110,7 @@ ci: ci-rust flake-check # just build-all optimized # Build all platforms at optimization level # ============================================================================= -# Build with specific optimization level, optional target +# Build with a specific optimization level and optional target; preserve env overrides. build-matrix level target="native": #!/usr/bin/env bash set -euo pipefail @@ -143,55 +143,75 @@ build-matrix level target="native": ;; esac - # Set optimization flags based on level + CARGO_ARGS=(--locked) + # Set optimization defaults without replacing caller overrides. case "$LEVEL" in debug) - CARGO_ARGS="" - export CARGO_PROFILE_DEV_OPT_LEVEL=0 + export CARGO_PROFILE_DEV_OPT_LEVEL="${CARGO_PROFILE_DEV_OPT_LEVEL:-0}" echo "Building: debug (fast compile, no optimizations)" ;; release) - CARGO_ARGS="--release" - echo "Building: release (Cargo defaults)" + CARGO_ARGS+=(--release) + echo "Building: release (Cargo.toml release profile)" ;; optimized) - CARGO_ARGS="--release" - export CARGO_PROFILE_RELEASE_LTO=thin - export CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 - echo "Building: optimized (LTO=thin, codegen-units=1)" + CARGO_ARGS+=(--release) + export CARGO_PROFILE_RELEASE_LTO="${CARGO_PROFILE_RELEASE_LTO:-thin}" + export CARGO_PROFILE_RELEASE_CODEGEN_UNITS="${CARGO_PROFILE_RELEASE_CODEGEN_UNITS:-1}" + echo "Building: optimized (thin LTO by default)" ;; max) - CARGO_ARGS="--release" - export CARGO_PROFILE_RELEASE_LTO=fat - export CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 - export CARGO_PROFILE_RELEASE_OPT_LEVEL=3 - export CARGO_PROFILE_RELEASE_STRIP=symbols - # CPU targeting: `native` describes the build HOST, so only apply - # it when the target IS the host. Explicit ARM targets get no - # target-cpu override (toolchain baseline); x86 targets use - # x86-64-v3. - if [[ "$TARGET" == "native" ]]; then - case "$(uname -m)" in - arm64|aarch64) export RUSTFLAGS="-C target-cpu=native" ;; - *) export RUSTFLAGS="-C target-cpu=x86-64-v3" ;; - esac - elif [[ "$TARGET" == "linux-arm" || "$TARGET" == "macos-arm" ]]; then - : # cross-building: no target-cpu override, use toolchain baseline + CARGO_ARGS+=(--release) + export CARGO_PROFILE_RELEASE_LTO="${CARGO_PROFILE_RELEASE_LTO:-fat}" + export CARGO_PROFILE_RELEASE_CODEGEN_UNITS="${CARGO_PROFILE_RELEASE_CODEGEN_UNITS:-1}" + export CARGO_PROFILE_RELEASE_OPT_LEVEL="${CARGO_PROFILE_RELEASE_OPT_LEVEL:-3}" + export CARGO_PROFILE_RELEASE_STRIP="${CARGO_PROFILE_RELEASE_STRIP:-symbols}" + # Cargo prefers encoded flags; use that format for paths containing spaces. + if [[ -n "${CARGO_ENCODED_RUSTFLAGS+x}" ]]; then + configured_flags="$CARGO_ENCODED_RUSTFLAGS" + build_flags=() else - export RUSTFLAGS="-C target-cpu=x86-64-v3" + configured_flags="${RUSTFLAGS:-}" + IFS=$' \t\n' read -r -d '' -a build_flags < <(printf '%s\0' "$configured_flags") + fi + build_flags+=( + "--remap-path-prefix=${CARGO_HOME:-$HOME/.cargo}/registry/src=/cargo/registry" + "--remap-path-prefix=$PWD=/workspace" + ) + if [[ "$configured_flags" != *target-cpu* ]]; then + case "$TARGET" in + native) build_flags+=(-C target-cpu=native) ;; + linux|linux-musl|macos) build_flags+=(-C target-cpu=x86-64-v3) ;; + esac + fi + build_flags_encoded="$(IFS=$'\x1f'; printf '%s' "${build_flags[*]}")" + if [[ -n "${CARGO_ENCODED_RUSTFLAGS:-}" ]]; then + build_flags_encoded="$CARGO_ENCODED_RUSTFLAGS"$'\x1f'"$build_flags_encoded" fi - echo "Building: max (LTO=fat, strip, target-cpu optimized)" + export CARGO_ENCODED_RUSTFLAGS="$build_flags_encoded" + echo "Building: max (CPU targeting and source path remapping)" ;; esac - # Build command + HOST_TRIPLE="$(rustc +{{stable_toolchain}} -vV | awk '/^host:/ { print $2 }')" + CARGO_SUBCOMMAND=build if [[ -n "$RUST_TARGET" ]]; then echo "Target: $RUST_TARGET" - cargo +{{stable_toolchain}} build --locked $CARGO_ARGS --target "$RUST_TARGET" + CARGO_ARGS+=(--target "$RUST_TARGET") + if [[ "$RUST_TARGET" != "$HOST_TRIPLE" ]]; then + if ! command -v cargo-zigbuild >/dev/null 2>&1 || ! command -v zig >/dev/null 2>&1; then + echo "Error: cross-compilation requires cargo-zigbuild and Zig on PATH." >&2 + exit 1 + fi + CARGO_SUBCOMMAND=zigbuild + fi + else + echo "Target: native ($HOST_TRIPLE)" + fi + cargo +{{stable_toolchain}} "$CARGO_SUBCOMMAND" "${CARGO_ARGS[@]}" + if [[ -n "$RUST_TARGET" ]]; then echo "Output: target/$RUST_TARGET/$([ "$LEVEL" = "debug" ] && echo "debug" || echo "release")/postmaster" else - echo "Target: native ($(rustc +{{stable_toolchain}} -vV | grep host | cut -d' ' -f2))" - cargo +{{stable_toolchain}} build --locked $CARGO_ARGS echo "Output: target/$([ "$LEVEL" = "debug" ] && echo "debug" || echo "release")/postmaster" fi @@ -202,6 +222,7 @@ build-all level="release": echo "Building all platforms at '{{level}}' optimization level..." echo "Note: cross targets need their toolchains installed first" echo " (e.g. 'rustup target add '); a missing toolchain fails loudly." + echo "Cross-compilation also requires cargo-zigbuild, Zig, and a macOS SDK for Darwin targets." for target in native linux linux-musl linux-arm macos macos-arm; do echo "" echo "=== Building target: $target ===" @@ -223,14 +244,11 @@ build-help: @echo " debug Fast compile, no optimizations, includes debug symbols" @echo " Best for: development, debugging, quick iteration" @echo "" - @echo " release Cargo defaults (opt-level=3, no LTO)" - @echo " Best for: testing release behavior, CI builds" + @echo " release Cargo.toml release profile (opt-level=3, fat LTO, stripped)" @echo "" @echo " optimized LTO (thin) + single codegen unit" - @echo " Best for: staging deployments, performance testing" @echo "" - @echo " max LTO (fat) + strip + CPU targeting (x86-64-v3 or native ARM)" - @echo " Best for: production deployments, final releases" + @echo " max Release with CPU targeting and source path remapping" @echo "" @echo "TARGETS:" @echo " native Current platform (default)" @@ -247,10 +265,9 @@ build-help: @echo " just build-matrix max macos-arm # Max for Apple Silicon" @echo " just build-matrix max linux-arm # Max for ARM Linux" @echo "" - @echo "TRADE-OFFS (times/sizes vary with codebase growth):" - @echo " Level Compile Time Binary Size Runtime Perf" - @echo " --------- ------------- ----------- ------------" - @echo " debug fastest largest 1x (baseline)" - @echo " release ~1.3x debug ~3-4x smaller 3-5x faster" - @echo " optimized ~2x debug ~4-5x smaller 5-7x faster" - @echo " max ~3x debug smallest 7-10x faster" + @echo "OVERRIDES AND PREREQUISITES:" + @echo " Existing RUSTFLAGS / CARGO_ENCODED_RUSTFLAGS and profile overrides are preserved." + @echo " max defaults: native CPU for native, x86-64-v3 for x86 targets, baseline for ARM." + @echo " Matching host/target triples use cargo build; cross builds use cargo zigbuild." + @echo " Install the Rust target, cargo-zigbuild, and Zig before cross-compiling." + @echo " Darwin cross builds also require a macOS SDK." diff --git a/README.md b/README.md index 18993db..2895bb9 100644 --- a/README.md +++ b/README.md @@ -19,14 +19,13 @@ Postmaster works with Nix, AWS CDK, Ansible, SaltStack, Puppet, Terraform, and OpenTofu as deployment automation targets, all sharing the same `exec.json` contract. -The trick that makes this compose: the ciphertext is *designed* to be -public. Every value is ECIES/secp256k1-encrypted individually, and the -embedded public key only permits encrypting *new* values. So the -world-readable Nix store — normally the reason secrets and Nix don't -mix — stops being an adversary. Encrypted env files ship inside the -closure, deploy atomically, roll back with the generation, and the -entire secret surface collapses to one 64-hex private key per -environment. +Encrypted values can be public: each value is ECIES/secp256k1-encrypted, +and the embedded public key permits encryption but not decryption. +Encrypted env files can ship in the Nix closure and roll back with the +generation. Keep private keys separate and protect artifact write access: +anyone with the public key can encrypt replacement values. Plaintext +passthrough entries are public too, so they must not contain secrets in a +public artifact. Runtime flow per service (systemd path): @@ -47,9 +46,10 @@ Runtime flow per service (systemd path): macOS runs the same flow under launchd, with a RAM disk replacing the private tmpfs. -Plaintext never touches persistent disk. Postmaster decrypts natively -and `execvp`s your binary directly from the same process -image — no Node, no separate CLI process, no shell in the startup path. +Postmaster decrypts natively and replaces the launcher with your binary. +Deployments must provide RAM-backed storage for secret files and configure +swap and dump protections. A hand-written `files` config without +`verify_ramdisk` does not establish that its directory is RAM-backed. ## CLI @@ -80,7 +80,8 @@ process environment and the wrapper `exec`s your binary. Correct for **`mode = "files"`.** Values are written one-file-per-key onto a namespace-private tmpfs (`TemporaryFileSystem=/run/postmaster`; on macOS, a per-service directory on an HFS RAM disk) and only `_FILE` pointer -variables are exported — the Docker-secrets convention. Secrets are +variables are exported by default, following the Docker-secrets convention. +`passthrough` also exports selected values. File-only projected secrets are absent from environ, `ps e`, crash-dump environment sections, and ambient child inheritance. @@ -118,8 +119,9 @@ stage-by-stage breakdown lives in The `exec.json` contract and `postmaster exec --check` conformance suite are the interface between postmaster and every integration. An -integration is correct if and only if the `exec.json` it emits passes -`--check` and the conformance suite. +integration must emit configs accepted by `--check` and verify its launch +behavior against the conformance suite. Host permissions, key availability, +and service-manager wiring need separate validation. ## Documentation @@ -127,7 +129,7 @@ Full documentation is in the [docs/](docs/) directory, buildable with [mdBook](https://rust-lang.github.io/mdBook/): ```console -$ mdbook serve docs +$ just docs-serve ``` See [docs/src/SUMMARY.md](docs/src/SUMMARY.md) for the table of contents. @@ -143,8 +145,13 @@ $ just ci-rust # all of the above in one command $ just build-matrix max macos-arm # optimized release ``` -See `just build-help` for the full build matrix (optimization levels -and cross-compilation targets). +Source builds require Rust 1.99.1 or newer. `just build-help` lists the +optimization levels and cross-compilation targets. + +Cross builds use `cargo zigbuild` and require the Rust target, `cargo-zigbuild`, +and Zig to be installed; Darwin cross builds also require a macOS SDK. +The matrix preserves compiler flags and profile environment overrides. Its +`max` level remaps checkout and Cargo registry source paths in build outputs. With Nix: @@ -153,6 +160,10 @@ $ nix build $ nix flake check ``` +The flake exports packages and an overlay. Service-manager bindings live in +deployment integrations; they must render `exec.json` and configure storage, +permissions, cleanup, and hardening. + ## License MIT diff --git a/deny.toml b/deny.toml index cb9e17e..ba0d9aa 100644 --- a/deny.toml +++ b/deny.toml @@ -41,10 +41,7 @@ confidence-threshold = 0.93 ignore = true [sources] -# The ecies fork in [patch.crates-io] (audit 2026-08-02 A7) is the only -# sanctioned git source; drop this entry together with the patch section -# once the upstream PR ships in a crates.io release. -allow-git = ["https://github.com/beardedeagle/rs.git"] +unknown-git = "deny" [bans] # Warn on duplicate crate versions — companion to clippy's diff --git a/docs/src/architecture/materialization-abi.md b/docs/src/architecture/materialization-abi.md index 034c345..ef8256f 100644 --- a/docs/src/architecture/materialization-abi.md +++ b/docs/src/architecture/materialization-abi.md @@ -4,7 +4,7 @@ contract between public deployment artifacts, local private key material, and the process that receives plaintext at runtime. -## Audience Quickstart (Plain Language) +## Audience Quickstart **What this is:** the contract that every integration (Nix, Terraform, CDK, Ansible, etc.) must follow when wiring postmaster. If you're writing @@ -35,7 +35,7 @@ The ABI is deliberately local: - private key material arrives through local terminal sources - `postmaster` decrypts and projects plaintext on the host - plaintext is handed to the target process through one selected projection -- failure happens before `exec`, not after a partially configured launch +- required validation and decryption checks finish before `exec` This page describes the ABI and how `exec.json` fits inside it. It is a contract for bindings and documentation recipes, not an invitation to put @@ -91,9 +91,9 @@ private keys are never config fields. `exec.json` is the first ABI instance. It is implicitly: - ABI version: `0` -- input adapter: `.env` (wire-compatible with dotenvx-encrypted files) -- artifact shape: `env_files` -- key material shape: `.env.keys` / `DOTENV_PRIVATE_KEY*` +- input adapters: `.env` and `postmaster_bundle` +- artifact fields: `env_files` and `bundle_files` +- key variables: `DOTENV_PRIVATE_KEY*` for dotenv, `POSTMASTER_KEY` for bundles - projection modes: `env`, `files`, and `credentials` The current parser does not accept explicit `version` or `adapter` fields. @@ -167,6 +167,12 @@ store or repo adversary who cuts a ciphertext from one entry and pastes it under another key name gets an authentication failure at decryption, not a mislabeled secret. +The decoded envelope is a 65-byte uncompressed secp256k1 ephemeral public key, +a 16-byte nonce, a 16-byte authentication tag, then ciphertext. HKDF-SHA256 +uses the uncompressed ephemeral and shared points, matching `ecies` defaults. +The entry name's exact UTF-8 bytes are the AAD; plaintext is returned only +after AES-256-GCM authentication succeeds. + The remaining metadata (profile, recipient ids, encodings) is not yet cryptographically bound. Binding it requires specifying canonical serialized bytes for the authenticated metadata first — generated artifacts need @@ -178,19 +184,19 @@ The design constraints are: values. - `suite` is mandatory so cryptographic suites can be explicit rather than inferred from payload length. -- `profile` is optional public selection metadata; it is not a secret. -- `recipients[*].id` is public routing metadata used to select local private - key material. +- `profile` and `recipients` are public metadata. They are parsed but do not + select local private keys or filter entries. - Private key material comes from the `POSTMASTER_KEY` variable: comma-separated rotation candidates are admitted, and `POSTMASTER_KEY_` variants match by the same predicate as `DOTENV_PRIVATE_KEY_*`. There is no per-environment filename mapping — - `profile` handles selection. + bindings select bundle paths through `bundle_files`. - `entries` keys must use the same identifier rule as `.env`-derived keys: `[A-Za-z_][A-Za-z0-9_]*`. -- `encoding` is either `utf8` or `bytes`. `env` projection rejects bytes that - cannot become a POSIX environment value; `files` and `credentials` preserve - byte-exact values. +- `encoding` is either `utf8` or `bytes`. A `utf8` entry must decrypt to valid + UTF-8. Env projection rejects NUL bytes; files preserve byte-exact values. +- Bundles are accepted in `env` and `files` modes. The credential daemon + resolves dotenv entries; `credentials` mode does not accept `bundle_files`. - A bundle can contain many entries for one projection, but it does not encode service-manager policy. Projection remains in the `postmaster` config, not inside the encrypted artifact. @@ -218,8 +224,8 @@ Implemented launcher key sources are local and terminal: - `{"file": "/path/to/.env.keys"}` reads a local file and fails closed if the file is unavailable or under `/nix/store`. - `{"keychain": ""}` reads from macOS Keychain and is terminal. -- `"environment"` reads `DOTENV_PRIVATE_KEY*` from the process environment - and is terminal. +- `"environment"` reads the required adapters' private-key variables from the + process environment and is terminal. Provider names such as `aws_ssm` and `vault` are reserved contract language, but they are not implemented key sources. A Vault Agent, cloud-init step, @@ -232,7 +238,7 @@ local sources. Resolution must: - parse every configured encrypted artifact before launching the target -- build the wanted private-key set from artifact metadata +- build the wanted private-key set from configured artifact names and formats - load key material from the ordered local sources - decrypt with the selected adapter - reject malformed key names @@ -244,6 +250,10 @@ Resolution must: For the `.env` adapter, this is implemented by `resolve_all` and the same native ECIES path used by the credential daemon. +`strict: false` permits undecryptable dotenv values to be logged and omitted. +`--verify-keys` rejects those omissions. Bundle authentication always fails +closed, independent of `strict`. + ## Diagnostics and redaction Failures identify the field, artifact, key name, or projection that failed @@ -272,6 +282,9 @@ because POSIX environment variables cannot carry them safely. Each resolved value is written as a `0600` file under `secrets_dir`. `postmaster` exports `_FILE` pointers for each secret. +The deployment must supply RAM-backed storage. The launcher does not establish +RAM backing when `verify_ramdisk` is absent. + The launcher refuses to follow symlinks when writing secret files. On macOS, when `verify_ramdisk` is set, it verifies the configured mount before writing plaintext. diff --git a/docs/src/architecture/postmaster.md b/docs/src/architecture/postmaster.md index 659d951..2c9357d 100644 --- a/docs/src/architecture/postmaster.md +++ b/docs/src/architecture/postmaster.md @@ -1,15 +1,14 @@ # postmaster: the secret materialization engine -Postmaster is a standalone Rust binary that does exactly one thing: -decrypt encrypted secret inputs at process launch time and inject -them into a child process, then replace its own process image with -the target binary via `execvp`. +Postmaster is a standalone Rust binary that decrypts secret inputs +at process launch, injects them into the child process, and replaces +its own process image with the target binary via `execvp`. It is not a library. It is not a plugin host. It is not a daemon framework. It is a single binary with a fixed, local, offline contract. -## Audience Quickstart (Plain Language) +## Audience Quickstart **What this is:** the architecture of postmaster — what it does, what it owns, and where it fits in the secret delivery pipeline. @@ -69,8 +68,7 @@ plaintext in its environment or files": ## What postmaster does NOT own -Postmaster does NOT own anything that happens before the encrypted -artifact exists or after the child process starts: +Deployment tooling owns authoring, custody, and service-manager policy: - **Secret authoring.** Encrypting secrets is done by workstation tooling (dotenvx CLI, or any tool producing the same ECIES @@ -91,7 +89,7 @@ artifact exists or after the child process starts: - **Service supervision policy.** Postmaster owns no lifecycle policy — no restarts, no health checks. The service manager (systemd on Linux, launchd on macOS) starts, monitors, and stops the service. - What postmaster does run is a secretless sibling monitor alongside + Postmaster runs a sibling monitor alongside the exec'd service: it forwards stop signals, escalates to SIGKILL after a bounded grace, and removes plaintext secret files on every death path (see "The secret pipeline" below) — supervision of @@ -197,10 +195,11 @@ Postmaster decrypts encrypted inputs and injects them into the child context. This is the only stage postmaster owns. - Decrypts `.env` files via the `ecies` crate (native Rust, offline) -- Decrypts `postmaster_bundle` files via the same crypto path +- Decrypts `postmaster_bundle` entries with name-bound AES-GCM AAD - Injects via `env`, `files`, or `credentials` mode -- Zeroizes decrypted values and private keys before `execvp` -- Fails closed if any value cannot decrypt +- Zeroizes its key ring and resolved buffers before `execvp` +- Rejects decryption failures by default; `strict: false` permits skipped + dotenv values, while bundle authentication remains mandatory ### Stage 5: Launch (execvp) @@ -208,14 +207,19 @@ Postmaster forks a **sibling monitor** and then calls `execvp` in the parent. The parent's process image is replaced. The child binary IS `MainPID`. Postmaster is gone from the service's process. -The fork-child is the monitor: secretless by construction (forked after -zeroization), it keeps the termination signals blocked for life and +The fork-child becomes the monitor. It scrubs its projected environment +pairs, keeps the termination signals blocked for life, and supervises its parent — forwards stop signals with a 250 ms grace before SIGKILL escalation, and removes the plaintext secret files on every service-death path (natural exit, `kill -9`, crash), then exits. One tiny extra process per service for the service's lifetime; liveness is pidfd+`poll` on Linux and kqueue `NOTE_EXIT` on macOS. +The monitor retains the original process environment, which can contain +private keys supplied through environment variables. Use a non-environment +key source to avoid this exposure. The credential daemon is a separate, +long-lived process that retains its key ring for requests. + The service manager (systemd/launchd) supervises the child from this point. `ExecStopPost` runs `postmaster cleanup` to remove plaintext files after the child exits (Linux) — now a backstop behind the @@ -223,18 +227,17 @@ monitor. The ramdisk is destroyed when the launchd job stops (macOS). ## Implementation -`postmaster/` contains a dependency-lean Rust binary (edition -2024; pure-Rust crypto, no openssl; no async runtime; syscalls via -rustix's `linux_raw` backend rather than libc FFI on Linux; on macOS, -`libc` is used for `getpeereid` and `PT_DENY_ATTACH` hardening — each -`unsafe` site carries a SAFETY comment and is catalogued in the -[unsafe-code registry](../unsafe-code/index.md)) that materializes -decrypted secret values as systemd -`LoadCredential=` AF_UNIX sources or directly injects them via -`execvp`. systemd's documented contract for socket credential sources +Postmaster uses Rust edition 2024, RustCrypto, and no async runtime or OpenSSL. +Linux uses rustix's `linux_raw` backend, with a libc call for `fork`. +macOS uses libc for peer checks, signal handling, kqueue, and anti-debug +hardening. Each unsafe site has a SAFETY comment and an entry in the +[unsafe-code registry](../unsafe-code/index.md). + +The binary serves decrypted values as systemd `LoadCredential=` AF_UNIX +sources or projects them before `execvp`. systemd's contract for socket sources is minimal — the manager connects once at process invocation and reads until EOF, with no request metadata in-band — so the request is encoded -in the *path*: one socket per (service, key). The module generates a +in the *path*: one socket per (service, key). A binding can generate a single `postmaster-credd.socket` unit carrying N `ListenStream=` entries; postmaster maps each inherited fd back to its path via `getsockname(2)`. @@ -256,9 +259,14 @@ and per-mode injection rules are the cross-binding contract at ## Dependency policy -Postmaster has 10 direct dependencies (8 portable, 2 platform-gated): +Source builds require Rust 1.99.1 or newer. The flake exports packages and +an overlay, not NixOS or nix-darwin service modules. Deployment integrations +own the service units, RAM-backed storage, and hardening described above. + +Postmaster has 11 direct dependencies (9 portable, 2 platform-gated): - `ecies` — crypto (secp256k1 + AES-256-GCM) +- `aes-gcm` — bundle-envelope authentication with entry-name AAD - `dotenvy` — `.env` file parser - `serde` + `serde_json` — JSON config deserialization - `base64` — ciphertext decoding @@ -272,8 +280,9 @@ Postmaster has 10 direct dependencies (8 portable, 2 platform-gated): - `security-framework` — macOS only (Security.framework keychain reads) - `zeroize` — secret memory wiping -(`ecies` is currently a git+rev pin of the author's fork via -`[patch.crates-io]`, pending upstream PR ecies/rs#159.) +Bundle envelopes use Postmaster's AAD decoder with the released `ecies` +curve/HKDF helpers and RustCrypto AES-GCM. This preserves existing ciphertext +compatibility without a git patch or an upstream AAD API dependency. No CLI parsing library (clap, etc.). No async runtime. No OpenSSL. No network client. No plugin system. The dependency set is diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index 16d6715..23aebfb 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -1,6 +1,6 @@ # Threat model -## Audience Quickstart (Plain Language) +## Audience Quickstart **What this is:** what postmaster protects, what it cannot prevent, and why it's built this way. This is the security reference. @@ -20,7 +20,7 @@ and why it's built this way. This is the security reference. | Term | Plain meaning | | ------ | --------------- | | **execvp** | Replaces the current process — no parent holds secrets after launch | -| **Fail-closed** | If anything fails, the service does NOT start — no partial secrets | +| **Fail-closed** | A failed required check prevents launch; dotenv decryption is strict by default | | **Zeroize** | Overwrite secret memory with zeros before it's freed | | **mlockall** | Pin memory in RAM so the kernel can't swap it to disk | | **TOCTOU** | Time-of-check to time-of-use — a race between verifying and using a file | @@ -32,7 +32,7 @@ and why it's built this way. This is the security reference. | Category | Status | | -------- | ------ | | Secrets at rest (ciphertext in git/Nix store) | Safe — ciphertext is public | -| Plaintext on persistent disk | Prevented — only RAM-backed filesystems | +| Plaintext on persistent disk | Avoided when the deployment supplies RAM-backed secret storage | | Plaintext in swap | Mitigated — mlockall + MemorySwapMax=0 | | Core dumps | Mitigated — PR_SET_DUMPABLE=0, RLIMIT_CORE=0 | | Shell injection | Prevented — no shell anywhere in the path | @@ -77,10 +77,25 @@ repository (which lets any repo writer add or replace encrypted values), this would be remote code execution at service start for anyone who can commit to the repo. -Postmaster never shells out or evals. Decrypted values move directly +Postmaster never evaluates secret values as shell code. Decrypted values move directly into the child's environment array or a file write. No shell sits between decryption and injection to reinterpret the values. +### Private-key environment variables + +Postmaster removes private-key variables from the launched application's +environment in every projection mode. Both adapter namespaces are reserved: +`DOTENV_PRIVATE_KEY`, `POSTMASTER_KEY`, and their `_` variants. +The environment source can still use these variables to decrypt inputs; +ordinary inherited variables remain available to the application. + +This filtering does not erase the launcher's original environment or the +copy inherited by its sibling monitor. Prefer a non-environment key source +to avoid that exposure. Filtering also does not prevent an application from +reading key files or keychain items its OS identity can access. Keeping a +master key inaccessible to the service requires a separate OS access +boundary, such as a credential daemon that delivers only selected secrets. + ### Offline decryption Postmaster's decryption uses the `ecies` library — a native Rust @@ -135,18 +150,20 @@ Only someone with the private key can decrypt the values. A teammate who has repository access (and thus the public key) can add or replace encrypted secrets, but cannot read existing ones. -### Plaintext never on persistent disk +### Plaintext storage depends on the deployment -Decrypted values exist only in: +The deployment must keep decrypted values in: - **Process memory** (anonymous heap, zeroized after use) - **RAM-backed filesystems** (Linux tmpfs, macOS ramdisk — destroyed when the service unit stops) -They are never written to a file on persistent disk. The tmpfs is -namespace-private (invisible outside the unit's mount namespace on -Linux) and unswappable (via `mlockall` on Linux and the service -manager's cgroup-level `MemorySwapMax=0` setting). +Postmaster writes to the configured `secrets_dir`. Without `verify_ramdisk`, +it does not prove that this directory is RAM-backed. Linux integrations must +provide a private RAM-backed mount and configure swap protection, for example +with `MemorySwapMax=0`. On macOS, enable `verify_ramdisk` to check RAM backing +before writing. Key files are separate: a `.env.keys` file can itself reside +on persistent disk. ### Fail-closed by default @@ -155,6 +172,10 @@ key file), the entire launch aborts before the child process starts. Nothing partial is injected. This is controlled by the `strict` setting, which defaults to `true`. +With `strict: false`, undecryptable dotenv values are logged and omitted. +`--verify-keys` makes those omissions fatal. Bundle authentication failures +always abort, regardless of `strict`. + ### Symlink attacks on key files and secret paths Postmaster rejects symlinks at every point where secret material is @@ -176,9 +197,9 @@ read or written: - **Secrets directory** is checked with `symlink_metadata` even on Linux where `verify_ramdisk` is not used, rejecting a symlinked `secrets_dir` that could redirect plaintext to persistent disk. -- **Socket permissions** are set via `fchmod` on the file descriptor, - not `set_permissions` on the path, eliminating the TOCTOU window - between `bind` and `chmod`. +- **Socket permissions** use `fchmod` on the socket fd on Linux. macOS rejects + that operation, so Postmaster sets the umask before binding there and + restores it afterward. ### External binary verification @@ -209,11 +230,10 @@ the secret path: `[A-Za-z_][A-Za-z0-9_]*` — this is enforced before any value from that file is used, since a key name becomes a shell-visible env-var name or a filename component. -- **No shell expansion:** Postmaster performs no `${VAR}` or `$(…)` - expansion anywhere in the decrypt-and-inject path. Values are - opaque bytes end to end. A repo contributor who commits - `KEY=$(cmd)` gets the literal string, never a command execution at - service start. +- **No shell evaluation:** decrypted values and bundle plaintext are injected + as bytes. Plaintext dotenv entries follow `dotenvy` parsing rules, including + variable substitution in unquoted and double-quoted values. Single quotes + preserve `${VAR}` literally. `$(cmd)` is not executed. ### Key freshness verification @@ -260,18 +280,19 @@ When multiple private keys are configured for one variable (the comma-separated rotation convention), decryption tries each candidate in order and stops at the first that works. A local observer measuring launch or fetch latency can infer which candidate matched — i.e., the -rotation position of the current key. Accepted (audit 2026-08-02 A14): -the observer learns only the rotation index, not key material, and -already needs same-host access; equalizing the timing would require -attempting every candidate on every decryption for no meaningful gain. +rotation position of the current key. Accepted: the observer learns +only the rotation index, not key material, and already needs same-host +access; equalizing the timing would require attempting every candidate +on every decryption for no meaningful gain. ### Env-file content is trusted input (no variable-name denylist) Postmaster injects what the configured env files and bundles say, -including plaintext passthrough entries. There is no denylist of -environment variable names (audit 2026-08-02 A18): names like -`LD_PRELOAD` or `PATH` are honored, because real deployments -legitimately set variables of this family (`LD_LIBRARY_PATH` is common). +including plaintext passthrough entries. Apart from reserved private-key names, +there is no denylist of +environment variable names: names like `LD_PRELOAD` or `PATH` are +honored, because real deployments legitimately set variables of this +family (`LD_LIBRARY_PATH` is common). The protection boundary is artifact authorship: anyone who can write the env file (or produce valid ciphertext for it) already controls what the child process receives. Treat plaintext passthrough entries in @@ -286,7 +307,7 @@ persistent disk. **Core dumps** are disabled at both the process level (`PR_SET_DUMPABLE=0` on Linux, `RLIMIT_CORE=0` on macOS) and the unit -level (`LimitCORE=0`, `CoredumpFilter=0` in the Nix module). For +level when the integration sets `LimitCORE=0` and `CoredumpFilter=0`. For host-wide coverage, set `systemd.coredump.extraConfig = "Storage=none"`. @@ -295,10 +316,10 @@ host-wide coverage, set - Per-unit: the service manager (systemd) can set `MemorySwapMax=0` on the unit, preventing the kernel from swapping the unit's pages. Postmaster also calls `mlockall(MCL_CURRENT | MCL_FUTURE)` on Linux - (best-effort, may fail under `RLIMIT_MEMLOCK`). On macOS, - `mlockall(2)` does not exist, but macOS encrypts swap by default, so - swapped pages are ciphertext at rest. -- Host-wide: encrypted swap or zram keeps all swap off persistent disk. + (best-effort, may fail under `RLIMIT_MEMLOCK`). Postmaster does not lock all + memory on macOS; it relies on the platform's encrypted swap. +- Host-wide: encrypted swap protects swapped pages at rest; zram keeps + compressed swap pages in RAM. On NixOS, this is a one-liner: [`swapDevices.*.randomEncryption`](https://search.nixos.org/options?show=swapDevices.*.randomEncryption.enable) for dm-crypt with an ephemeral key, or @@ -313,17 +334,18 @@ hardening (`PR_SET_DUMPABLE=0`, `mlockall`, `RLIMIT_CORE=0`). After `execvp`, the child process gets a fresh address space. Some settings survive `execvp`, some do not: -- **`RLIMIT_CORE`**: preserved across `execve` (kernel guarantee). The - child inherits `LimitCORE=0` from the systemd unit. Core dumps stay - disabled. -- **`PR_SET_DUMPABLE`**: preserved across `execve` for non-setuid - binaries. The child inherits non-dumpable status unless it is a - setuid/setgid/capability-bearing binary (which would be unusual for - a service). +- **`RLIMIT_CORE`**: preserved across `execve`. Postmaster sets it to zero + on macOS. Linux integrations must set `LimitCORE=0` for the application; + the launcher's dumpability setting alone does not survive exec. +- **`PR_SET_DUMPABLE`**: an ordinary Linux `execve` resets dumpability to 1. + Postmaster's setting protects the launcher and credential daemon, not the + executed application. The application needs its own non-dumpable setting + or OS isolation to restrict same-UID tracing. See the + [Linux exec setup](https://github.com/torvalds/linux/blob/d48723711bae9b8cdc56719c448ba42fef28cbee/fs/exec.c#L1125-L1351). - **`MemorySwapMax=0`**: cgroup-level, not process-level. The child stays in the same cgroup, so the swap limit applies to the child's pages too. This is the primary swap protection for the child. The - Nix module sets this via `preventSwap = true` by default. + integration must configure this limit; the package does not supply a unit. - **`mlockall`**: does NOT survive `execvp` — the child's fresh address space is not pinned in RAM. This gap is covered by the cgroup-level `MemorySwapMax=0`. @@ -337,24 +359,23 @@ explicitly a non-goal. ### Anonymous memory (heap, stack) — Mitigated -Postmaster's decrypted values, key material, and resolved environment -pairs all live in anonymous memory — heap allocations wrapped in -`Zeroizing>` that zero the buffer on drop. The child process +Postmaster wraps its key ring and resolved values in `Zeroizing` buffers. +Projected environment pairs use ordinary `OsString` buffers that must remain +intact until `execvp`. The child process receives plaintext via its environment array (env mode) or reads it from files on a tmpfs/ramdisk (files/credentials mode). **Paging/swap:** Anonymous pages can be swapped out by the kernel. Postmaster mitigates this on Linux with `mlockall(MCL_CURRENT | MCL_FUTURE)` (best-effort, may fail under `RLIMIT_MEMLOCK`) and the -service manager's cgroup knob `MemorySwapMax=0` (wired by `preventSwap` -in the Nix module). On macOS, `mlockall(2)` does not exist, but macOS -encrypts swap by default, so swapped pages are ciphertext at rest. -Host-wide encrypted swap or zram on Linux provides the same guarantee -without per-unit configuration. +service manager's cgroup setting `MemorySwapMax=0`, configured by the +deployment. Postmaster does not lock all memory on macOS; it relies on +encrypted swap. Linux deployments can use encrypted swap for protection at +rest or zram to keep swap pages in RAM. **Core dumps:** Disabled at the process level (`PR_SET_DUMPABLE=0` on Linux, `RLIMIT_CORE=0` on macOS) and at the unit level -(`LimitCORE=0`, `CoredumpFilter=0` in the Nix module). Host-wide +when configured by the integration (`LimitCORE=0`, `CoredumpFilter=0`). Host-wide `systemd.coredump.extraConfig = "Storage=none"` is a belt for all units. @@ -366,9 +387,10 @@ explicitly `drop`ped immediately after they are consumed, before `execvp` is called. In env mode, `resolved` is dropped after `env_pairs` extracts the `OsString` pairs the kernel needs. In files mode, `resolved` is dropped after the secret files are written. -Only the `extra` vector (env array for env mode, file paths for files -mode) survives to `execvp` — and in files mode, `extra` contains only -paths, not plaintext. +The `extra` vector survives until `execvp`: it contains plaintext in env mode +and in files-mode `passthrough`, plus file pointers where applicable. The +original process environment is separate and is not zeroized. The credential +daemon retains its key ring while serving requests. ### Post-execvp heap lifetime — Residual (mitigated as far as possible) @@ -391,38 +413,36 @@ secrets in a long-lived parent heap (strictly worse) and was rejected. The sibling monitor is forked after zeroization, so the key ring and the `Zeroizing` resolved values are already wiped in the copy it -inherits. One plaintext-bearing structure does cross the fork: the +inherits. The projected `extra` env array (plaintext values in env mode and in files-mode passthrough). The monitor scrubs its copy **first**, before the supervision loop starts: each `OsString` is consumed into its existing buffer (no copy) and wiped in place with `zeroize` — free() alone would leave the bytes in the monitor's mapped pages for its whole life, and the monitor never allocates again, so they would never even be -reused. The parent's copy dies with `execvp` (image replacement). What -the monitor keeps beyond the scrub is non-secret metadata only: the -pinned secrets-dir fd and entry names (already visible in the -directory listing). - -### File-backed memory (page cache) — Mitigated by design - -Postmaster does not `mmap` secret files. Secret files on Linux tmpfs -and macOS ramdisk are kernel-resident RAM — they are never on -persistent disk and never enter the page cache for a backing file. -The `.env` and `.env.keys` source files are read via `dotenvy`'s -`from_read_iter` which uses `read(2)`, not `mmap(2)` — their contents -enter anonymous memory, not file-backed pages. - -The distinction matters: file-backed pages (e.g., a secret stored in a -regular file on an ext4 volume) persist in the kernel page cache after -the file is closed and the process exits. Postmaster avoids this by -writing secrets only to tmpfs/ramdisk (RAM-backed, no page cache for a -backing file) and by using `read(2)` for source files (anonymous -memory, not mapped). +reused. The parent's copy dies with `execvp` (image replacement). Cleanup +uses the pinned secrets-dir fd and entry names. The monitor also retains +the original process environment, which can contain private keys and other +secrets. Scrubbing `extra` does not erase that environment. + +### File-backed memory and page cache — Residual + +Postmaster reads source files into userspace buffers rather than mapping +them. That does not bypass the kernel page cache: ordinary file reads can +populate it. Zeroizing a userspace buffer does not clear the backing file +or its cached pages. See the +[Linux page-cache overview](https://docs.kernel.org/admin-guide/mm/concepts.html#page-cache). + +Keep decrypted output on RAM-backed storage. A persistent `.env.keys` file +retains its key material on disk and can leave copies in the kernel cache +after Postmaster closes it. Use credentials, RAM-backed files, or keychain +storage when persistent plaintext key files do not fit the deployment's +requirements. Swap and crash-dump protections remain separate requirements. ### Container swap enforcement — Mitigated `MemorySwapMax=0` can be wired by the service manager (systemd) or the -Nix module via `preventSwap`. This enforces the cgroup's swap limit — +deployment integration. This enforces the cgroup's swap limit — the kernel will not swap the unit's pages even under host memory pressure. The residual is only if the host kernel itself is compromised, which falls under "root on the host is always game over." @@ -462,23 +482,23 @@ privileged memory inspection within the same kernel. ### Plaintext file persistence window (files mode) — Mitigated Secret files written to the tmpfs/ramdisk are removed by the **sibling -launch monitor** (design 2026-08-05), by `postmaster cleanup --config -` wired to `ExecStopPost` in the systemd Nix module, and by -ramdisk destruction when the `postmaster-ramdisk` launchd job stops. The -`prune_stale` function also removes stale files from prior launches -before writing new ones. +launch monitor**, by `postmaster cleanup --config ` wired to +`ExecStopPost` in the service integration, and by ramdisk destruction +when the `postmaster-ramdisk` launchd job stops. The `prune_stale` +function also removes stale files from prior launches before writing +new ones. A `TerminationGuard` blocks SIGTERM/SIGINT/SIGHUP/SIGQUIT across the write window on both platforms, so a signal landing mid-write cannot -strand partial plaintext (audit 2026-08-02 A11). At the end of the -window — after zeroization, before `execvp` — the launcher forks. The -parent restores its pre-guard mask and execs the service (MainPID -unchanged); the fork-child is the **sibling monitor**: it keeps the -four termination signals blocked for life and owns stop semantics. - -*Monitor model (2026-08-05):* the monitor consumes stop signals -synchronously (no handlers anywhere — the sigaction flag-handler and -second pre-exec gate were retired with this design), forwards them to +strand partial plaintext. At the end of the window — after zeroization, +before `execvp` — the launcher forks. The parent restores its pre-guard +mask and execs the service (MainPID unchanged); the fork-child is the +**sibling monitor**: it keeps the four termination signals blocked for +life and owns stop semantics. + +*Monitor model:* the monitor consumes stop signals synchronously (no +handlers anywhere — the sigaction flag-handler and second pre-exec gate +were retired with this design), forwards them to the service, and escalates to SIGKILL after a **250 ms grace** — a single global constant, deliberately not configurable (per-service erosion of a security policy is unacceptable; the per-unit knob is the @@ -502,13 +522,10 @@ service leaves the pre-existing backstops (`ExecStopPost`, teardown, monitor's cleanup delete files based on one service's key set, so two services sharing one directory lets one service's lifecycle delete the other's live files. The impact is availability, not confidentiality — -no plaintext crosses services. The generated Nix modules comply by -construction (Linux: each unit mounts a namespace-private tmpfs at the -path; darwin: per-service subdirectory under the shared ramdisk), so -this binds hand-written configs only: one `secrets_dir` per service. -Runtime enforcement via a service-identity sentinel is a -considered-and-deferred hardening for the broker era, when multi-tenant -topologies become real by design. +no plaintext crosses services through Postmaster's resolution. Bindings must +give each service its own directory or private mount. Postmaster does not +enforce a service identity in the sentinel; directory separation is an +integration requirement. ### Ramdisk mount verification (macOS) — Mitigated diff --git a/docs/src/executive-overview.md b/docs/src/executive-overview.md index dec2cdf..f484a43 100644 --- a/docs/src/executive-overview.md +++ b/docs/src/executive-overview.md @@ -1,79 +1,71 @@ # Executive overview -A one-page briefing on postmaster for engineering leadership and -product/project management. No code, no commands — what it is, why it -exists, and what it does and does not promise. +A briefing for engineering leadership and product managers on what +postmaster does, where it fits, and which protections depend on the deployment. ## What it is -postmaster is a small, single-purpose Unix tool that decrypts a -service's secrets at launch time and hands them directly to the -service — then removes itself from the picture. It replaces the common -practice of shell scripts or long-lived helper processes holding -plaintext secrets in memory for the service's entire lifetime. +Postmaster is a Unix tool that decrypts a service's secrets at launch and +delivers them through environment variables, files, or systemd credentials. +Its launcher replaces itself with the service binary. A separate monitor +forwards stop signals and removes secret files when the service exits. ## The problem it solves -Most deployments get secrets to production one of a few ways, and each -leaves plaintext somewhere an incident can reach it: - -- **Plaintext files on disk** — readable by any process, any backup - job, any accidental `cat` in a debugging session. -- **Deploy-time environment variables** — visible in process listings, - unit files, and crash dumps. -- **Wrapper scripts and parent processes** — keep decrypted secrets in - a long-lived process's memory for as long as the service runs. - -The common thread is plaintext with a long lifetime and a wide blast -radius. postmaster's entire design is collapsing that lifetime to -microseconds and that radius to one process. - -## What it guarantees - -- **No plaintext at rest.** Decrypted secrets exist only in memory, - in the moments between decryption and launch. Where a deployment - mode needs files, they live on a ramdisk and are deleted on every - service-death path — including `kill -9` — by a dedicated monitor - process. -- **Ciphertext is safe to publish.** Encrypted secret files can live - in git or a world-readable artifact store; only one 64-character - private key per environment needs protection, and it can itself be - sealed to the host (TPM2) or held in the macOS keychain. -- **Small, auditable surface.** One dependency-lean Rust binary, no - network client, no plugin system, no shell in the runtime path. - Every `unsafe` block is catalogued with its justification and - mitigations. -- **Fail closed.** A missing key, a stale key, or a malformed config - stops the launch loudly and names the problem — a service never - starts with partial or wrong secrets. +Secret delivery can leave plaintext accessible beyond the process that needs it: + +- Files on persistent disk can reach backups or remain after a service stops. +- Environment variables can appear in process listings, diagnostics, or dumps. +- A wrapper that stays alive can retain its copy of keys and decrypted values. + +Postmaster decrypts at launch and wipes its key ring and resolved buffers +before replacing the launcher. The application still needs access to its +secrets for as long as it uses them. + +## Protections and their limits + +- **RAM-backed secret files.** Deployments must provide private RAM-backed + storage for file projections. The monitor removes + files after service exit, a crash, or `kill -9`, provided the monitor survives. +- **Public ciphertext.** Encrypted artifacts can live in git or a public + artifact store. Private keys need separate protection, and write access to + artifacts still controls which values the application receives. +- **Local decryption.** One Rust binary handles decryption and injection. + It has no remote secret-store client, plugin system, or shell evaluation of + secret values. The unsafe-code reference records the syscall boundaries. +- **Strict decryption by default.** A decryption failure stops launch. + `strict: false` allows undecryptable dotenv values to be omitted; + `--verify-keys` makes those omissions fatal. Bundle decryption always fails + if an entry cannot authenticate. ## What it does not do -- It is not a secret store and does not replace Vault, SSM, or - 1Password — those systems keep custody of keys. postmaster is the - last hop, and it will never grow a network client for them. -- It does not supervise services (restarts, health checks) — that - stays with systemd/launchd. Its tiny monitor process handles only - stop-signal forwarding and secret cleanup. -- It does not hold secrets over time: the process that decrypted them - is gone the moment the service binary starts. +- Vault, SSM, and 1Password keep custody of keys. External tooling delivers + keys to local sources before Postmaster starts. +- The service manager owns restarts and health checks. Postmaster's monitor + handles stop-signal forwarding and cleanup. +- The monitor retains the launcher's original environment. Use a file, + keychain, or credential key source to avoid leaving environment-supplied + private keys in that process. +- The optional credential daemon is long-lived and retains its key ring to + decrypt requests. It is separate from the per-service launcher and monitor. ## Operational footprint -- One small Rust binary per host; one tiny monitor process per service +- One Rust binary per host; one monitor process per service for the service's lifetime. -- Linux (systemd) and macOS (launchd); no kernel modules, no network - calls, no privileges beyond what the service itself needs. +- Linux with systemd and macOS with launchd. Bindings configure filesystem + permissions, credential access, RAM-backed storage, and service hardening. - Rollout is per-service and reversible: postmaster wraps the existing launch command. ## Assurance posture -- Pure-Rust cryptography — no openssl in the binary. -- An executable conformance suite mirrors the documented launch - contract, so documented behavior is tested behavior. -- Every finding from the 2026-08 security audits is fixed and listed - in the changelog with its finding ID. +- RustCrypto and released ECIES dependencies provide the cryptographic + operations. Postmaster owns the bundle's name-bound AAD envelope decoder. +- The conformance suite checks configuration examples and launch behavior. +- The threat model records residual exposure, deployment requirements, and + the limits of cleanup and memory hardening. ## Where to go next diff --git a/docs/src/getting-started/injection-modes.md b/docs/src/getting-started/injection-modes.md index 04a465b..1971880 100644 --- a/docs/src/getting-started/injection-modes.md +++ b/docs/src/getting-started/injection-modes.md @@ -12,7 +12,7 @@ environment variables, as files, or as systemd credentials. | Mode | Best for | Secrets in environ? | Hygiene | | --- | --- | --- | --- | | `env` | 12-factor apps, simple services | Yes | Lowest — same-UID processes can read `/proc/PID/environ` | -| `files` | Apps that read `KEY_FILE` pointers (Docker secrets convention) | No — only `_FILE` pointers | Medium — secrets absent from environ, `ps`, crash dumps | +| `files` | Apps that read `KEY_FILE` pointers (Docker secrets convention) | Only when `passthrough` requests it | No environment copy by default; the app still reads plaintext files | | `credentials` | systemd services wanting strongest isolation | No — reads `$CREDENTIALS_DIRECTORY` | Highest — unit-private unswappable ramfs | ## Mode comparison @@ -27,9 +27,9 @@ flowchart TB tmpfs -->|KEY_FILE=/run/.../KEY| child_files["your binary"] end subgraph cred["mode: credentials"] - systemd["systemd"] -->|LoadCredential=| ramfs["ramfs\n$CREDENTIALS_DIR"] - pm_cred["postmaster"] -->|decrypt + write| ramfs - ramfs -->|KEY_FILE=$CREDENTIALS_DIR/KEY| child_cred["your binary"] + daemon["postmaster credential daemon"] -->|decrypted bytes over local socket| systemd["systemd"] + systemd -->|LoadCredential=| ramfs["ramfs\n$CREDENTIALS_DIRECTORY"] + ramfs -->|KEY_FILE=$CREDENTIALS_DIRECTORY/KEY| child_cred["your binary"] end ``` @@ -46,14 +46,14 @@ and prone to appearing in crash dumps and debug output. means "this service only"), `ProtectProc` hardening (hides other processes' `/proc` entries), and ultimately switching to `files` mode. -**No shell expansion:** postmaster performs no `${VAR}`/`$(…)` expansion -anywhere in the decrypt-and-inject path, in any mode. A repo contributor -who commits `KEY=$(cmd)` gets the literal string, never a command -execution at service start. +**No shell execution:** decrypted values are injected without shell +evaluation. Plaintext dotenv entries follow `dotenvy` parsing rules, including +variable substitution in unquoted and double-quoted values. Single quotes +preserve `${VAR}` literally. `$(cmd)` does not execute a command. ## `mode = "files"` -Values are written one-file-per-key onto a namespace-private tmpfs +Deployments provide a namespace-private tmpfs for one-file-per-key output (`TemporaryFileSystem=/run/postmaster`; on macOS, a per-service directory on an HFS RAM disk) and only `_FILE` pointer variables are exported — the Docker-secrets convention @@ -66,6 +66,11 @@ mount namespace on Linux (root needs `nsenter`) and is destroyed with the unit. On macOS, the RAM disk is protected by ownership (`0700`), not invisibility — macOS has no mount namespaces. +This describes file-only projection. `passthrough` adds environment copies, +and ordinary inherited variables remain present. The application can also +copy file contents into its own memory. A hand-written config must provide +RAM-backed storage; setting `secrets_dir` alone does not verify it. + Each secret file is written with `O_NOFOLLOW | O_CREAT | O_TRUNC` and `fchmod`'d to `0600` on the file descriptor (no TOCTOU window between open and chmod). @@ -76,6 +81,7 @@ For a mostly-file-capable app with a straggler that needs an env var: { "mode": "files", "env_files": ["secrets/.env.production"], + "keys": [{"file": "/var/lib/postmaster/.env.keys"}], "secrets_dir": "/run/postmaster", "passthrough": ["RUST_LOG"] } @@ -105,6 +111,9 @@ systemd credentials, so app code is unchanged. - **`strict` (default `true`):** if any value fails to decrypt, the entire exec aborts before the child runs. Nothing partial is injected. +- **`strict: false`:** undecryptable dotenv values are logged and omitted. + `--verify-keys` makes those omissions fatal. Bundle entries must authenticate + under either setting. - **NUL in env values:** rejected in `env` mode and for `passthrough` values in `files` mode. In `files` mode's primary write path, NUL is not restricted — the exact bytes reach the file. diff --git a/docs/src/getting-started/quick-start.md b/docs/src/getting-started/quick-start.md index 57ae6d6..b150acb 100644 --- a/docs/src/getting-started/quick-start.md +++ b/docs/src/getting-started/quick-start.md @@ -1,7 +1,6 @@ # Quick start -This page shows how to get postmaster running with an encrypted `.env` -file in under 10 minutes. +This page launches a command with values from an encrypted `.env` file. ## Audience Quickstart @@ -11,7 +10,7 @@ postmaster. ## Prerequisites -- A Rust toolchain (`rustup`, stable) +- Rust 1.99.1 or newer (`rustup`, stable) - [dotenvx CLI](https://github.com/dotenvx/dotenvx) (or any tool producing the same ECIES format) for encrypting secrets - postmaster built from source (or from the Nix flake) @@ -21,6 +20,7 @@ postmaster. Create a `.env` file and encrypt it: ```console +$ mkdir -p secrets $ dotenvx set DATABASE_URL 'postgres://user:pass@localhost:5432/myapp' \ -f secrets/.env.production $ dotenvx set API_TOKEN 'secret-token-here' \ diff --git a/docs/src/introduction.md b/docs/src/introduction.md index 6a164af..59f4fe4 100644 --- a/docs/src/introduction.md +++ b/docs/src/introduction.md @@ -6,7 +6,7 @@ injects them into a child process via environment variables, files, or systemd credentials — then `execvp`s the target binary directly. No Node, no shell, no separate CLI process in the runtime path. -## Audience Quickstart (Plain Language) +## Audience Quickstart **What this is:** a tool that takes encrypted secrets (like database passwords and API tokens) and safely puts them into your service's @@ -52,16 +52,16 @@ each have tradeoffs: - **Manual env vars** put plaintext secrets in the systemd unit file or the container spec — visible in `ps`, `systemctl cat`, and crash dumps. -Postmaster takes a different approach: decrypt locally, inject directly, -replace the process image. The secret material exists in process memory -for a brief window, never touches persistent disk, and the process that -held the secrets is gone the moment your binary starts. +Postmaster decrypts locally, injects directly, and replaces the launcher +with your binary. It wipes its key ring and resolved buffers before launch. +Deployments provide RAM-backed secret storage and configure swap and dump +protection. The application keeps access to the secrets it uses. ## What postmaster Does 1. **Decrypts** encrypted `.env` files (or `postmaster_bundle` JSON - containers) using the `ecies` crate — native Rust, no network calls, - no external CLIs, no shell. + containers) using native Rust cryptography. Bundle entries use Postmaster's + AAD decoder with released ECIES helpers and RustCrypto AES-GCM. 2. **Injects** decrypted values into the child via one of three modes: - `env` — environment variables (12-factor apps) @@ -71,7 +71,7 @@ held the secrets is gone the moment your binary starts. 3. **Launches** the target binary via `execvp` — postmaster is replaced by your binary. The child process IS `MainPID` from its first - instruction. No parent process holds secrets. + instruction. A sibling monitor handles stop signals and file cleanup. 4. **Cleans up** — `postmaster cleanup` removes plaintext secret files after the child exits, wired to `ExecStopPost` in systemd. @@ -94,9 +94,9 @@ flowchart LR The ciphertext is designed to be public. Every value is ECIES/secp256k1-encrypted individually — the public key embedded in the file only permits encrypting new values, never decrypting existing -ones. So the world-readable Nix store, git repo, or artifact registry -stops being an adversary. The entire secret surface collapses to one -64-hex private key per environment. +ones. This allows encrypted values in the Nix store, git, or an artifact +registry. Private keys still need separate protection. Anyone with the public +key can encrypt replacement values, so artifact write access remains trusted. ## The Secret Pipeline @@ -109,11 +109,17 @@ per-stage detail live in Postmaster does not participate in stages 1-3. It does not fetch from remote systems, does not deploy infrastructure, and owns no service -lifecycle policy — no restarts, no health checks (a secretless sibling +lifecycle policy — no restarts, no health checks (a sibling monitor forwards stop signals and cleans up plaintext; the service manager supervises the service itself). It decrypts, injects, and gets out of the way. +The monitor scrubs the projected environment pairs, but retains the original +process environment. Environment-supplied private keys can remain there. +The optional credential daemon also retains its key ring while serving +requests. See the [Threat model](./architecture/threat-model.md) for these +limits and the deployment requirements. + ## Capability Horizon - `.env` adapter (wire-compatible with dotenvx), `postmaster_bundle` diff --git a/docs/src/reference/cli.md b/docs/src/reference/cli.md index cdb60ee..f6bf731 100644 --- a/docs/src/reference/cli.md +++ b/docs/src/reference/cli.md @@ -123,7 +123,7 @@ when it writes there) — a misconfigured `secrets_dir` can never wipe a directory postmaster doesn't manage. Empty or missing directories are fine. -Wired to `ExecStopPost` in systemd by the Nix module. On macOS, the +Integrations can wire this to `ExecStopPost` in systemd. On macOS, the ramdisk destruction handles cleanup automatically when the launchd job stops. diff --git a/docs/src/reference/launcher-contract.md b/docs/src/reference/launcher-contract.md index 23041b6..439f158 100644 --- a/docs/src/reference/launcher-contract.md +++ b/docs/src/reference/launcher-contract.md @@ -1,6 +1,6 @@ # Launcher contract (exec.json) -## Audience Quickstart (Plain Language) +## Audience Quickstart **What this is:** the complete specification of `exec.json` — every field, every mode, every validation rule. This is the contract a @@ -27,10 +27,9 @@ binding (Nix, Terraform, CDK, Ansible) must produce. `postmaster exec` is the concrete instance of the [materialization ABI](../architecture/materialization-abi.md). -The current config shape is -the `.env` adapter: encrypted inputs are `env_files`, private key material uses -the `.env.keys` / `DOTENV_PRIVATE_KEY*` convention, and output projection is -selected with `mode`. This page documents the committed parser and launcher +The config accepts dotenv inputs through `env_files` and JSON bundles through +`bundle_files`. They use `DOTENV_PRIVATE_KEY*` and `POSTMASTER_KEY` respectively; +`mode` selects output projection. This page documents the parser and launcher behavior; the ABI page records how this contract fits into the broader format-neutral architecture. @@ -43,22 +42,20 @@ hand-rolled process supervisors, or nix-darwin's launchd — get the same decrypt-and-inject semantics as the Linux daemon path, without templating shell or re-implementing the crypto. -This page is **the** cross-binding contract. The Nix module is the first -binding to emit `exec.json`; it is not privileged over any other binding. -**A binding is correct if and only if the `exec.json` it emits is -described by this document and passes the conformance suite.** -Nothing here documents intent or a roadmap; every claim below is true -of the committed parser and launcher (`src/exec_config.rs`, -`src/launcher.rs`, `src/keys/mod.rs`) as of this writing. +This is the cross-binding contract. Nix and other deployment integrations +emit the same `exec.json` format. +Bindings must emit configs accepted by the parser and check their behavior +against the conformance suite. Host permissions, key availability, and +service-manager wiring require separate validation. ### Config to launch flow ```mermaid flowchart TD - cfg["exec.json\n(mode, keys, env_files)"] + cfg["exec.json\n(mode, keys, env_files, bundle_files)"] check["--check\nconfig shape only"] recheck["setup --recheck\nkey source accessible?"] - resolve["resolve_all\ndecrypt + resolve"] + resolve["resolve_all + resolve_bundle\ndecrypt + resolve"] verify["--verify-keys\nstale key check"] inject["inject\n(env / files / credentials)"] execvp["execvp\nchild = MainPID"] @@ -77,11 +74,9 @@ The `.env` semantics this contract mirrors — encrypted-value format, `.env.keys` rotation via comma-separated candidates, `DOTENV_PRIVATE_KEY*` naming, `--strict`/`--overload` precedence — are wire-compatible with [dotenvx](https://github.com/dotenvx/dotenvx)-encrypted `.env` files. -`postmaster exec` does not shell out to any external CLI at all — it -implements the decrypt path natively in Rust (same `ecies` crate the -daemon uses) — but wherever this document describes a precedence or -filtering rule, it describes the wire-compatible behavior, not a -postmaster-only invention. +`postmaster exec` decrypts natively in Rust, using the same dotenv ECIES +path as the daemon. It does not invoke an external encryption CLI. +Platform checks can invoke verified system tools, as described below. ## Invocation @@ -143,8 +138,8 @@ Every field except `mode` has a default, so a minimal config is just | `mode` | `"env" \| "files" \| "credentials"` | — (required) | Injection mode; see below. | | `keys` | array of key-source specs | `[]` | Ordered list of where to obtain `DOTENV_PRIVATE_KEY*` / `POSTMASTER_KEY` material. Unused in `credentials` mode. | | `env_files` | array of paths | `[]` | Encrypted `.env[.]` files, in precedence order (first file wins unless `overload`). `env`/`files` modes require at least one of `env_files` or `bundle_files` non-empty. | -| `bundle_files` | array of paths | `[]` | Encrypted `postmaster_bundle` JSON containers, in precedence order. Entries are merged with `env_files`; bundle keys use the same identifier rule and injection modes. | -| `strict` | bool | **`true`** | Any value that fails to decrypt aborts the whole exec before the child runs. | +| `bundle_files` | array of paths | `[]` | Encrypted `postmaster_bundle` JSON containers, resolved after `env_files`. The first definition wins unless `overload` selects the last; bundle keys use the same identifier rule and injection modes. | +| `strict` | bool | **`true`** | Undecryptable dotenv values abort launch when true and are omitted when false. Bundle authentication failures always abort. | | `overload` | bool | `false` | File-derived values override the process environment; later files override earlier ones. | | `secrets_dir` | path or `null` | `null` | `files` mode, and `credentials` mode on the launchd/fetch path: directory plaintext files are written into. | | `passthrough` | array of strings | `[]` | `files` mode only: these keys are *also* exported as real env vars, in addition to their `_FILE` pointer. | @@ -171,10 +166,8 @@ single-tenant: `prune_stale` at launch and cleanup on every death path delete files there based on one service's key set, so two services sharing a directory lets one service's lifecycle delete the other's live files (an availability failure — plaintext never crosses services). The -generated Nix modules comply by construction — each Linux unit mounts a -namespace-private tmpfs at the path, and the darwin module writes -per-service subdirectories under the ramdisk — so this rule binds -hand-written configs. +integration must separate services, for example with a namespace-private +tmpfs per Linux unit or per-service directories on a macOS RAM disk. `--check` also validates env-file basenames, rejects private-key `file` sources under `/nix/store`, rejects path-like `credential` source @@ -211,8 +204,16 @@ Each entry in `keys` is one externally-tagged JSON shape: candidates are admitted, and `POSTMASTER_KEY_` variants match by the same predicate as `DOTENV_PRIVATE_KEY_*`. There is no per-environment filename mapping — every bundle file resolves against -the one `POSTMASTER_KEY` variable, and the bundle's `profile` field -handles environment selection. +the one `POSTMASTER_KEY` variable. `profile` and `recipients` are public +metadata; they do not select keys. Bindings select the bundle paths. + +**Application environment.** In every projection mode, the launched command +does not receive `DOTENV_PRIVATE_KEY`, `POSTMASTER_KEY`, or their +`_` variants. This applies regardless of the selected key +source and after all projected values are added. Other inherited variables, +including `PATH` and `HOME`, are preserved. Bundle entries using these +reserved private-key names are rejected before launch, even with +`strict: false`. **Selection contract**, evaluated in list order: @@ -234,13 +235,13 @@ decryption happens in that mode; see below. ## Precedence contract -This is the contract `resolve_all` (`src/keys/mod.rs`) implements, -verbatim: +The launcher resolves `env_files` first, followed by `bundle_files`. +Both adapters follow this contract: - **Within one file, the last assignment wins** — ordinary dotenv semantics. `A=1` followed later in the same file by `A=2` yields `2`. - **Across files, the first file that defines a key wins**, in the order - `env_files` lists them — *unless* `overload` is `true`, in which case + the lists specify — *unless* `overload` is `true`, in which case the **last** file defining the key wins. Note: which file wins does not change the *position* a key is emitted in; a key's slot is fixed by the first file that introduces it, `overload` only changes which @@ -249,8 +250,8 @@ verbatim: but only when `overload` is `false`: if the variable is already set in postmaster's process environment, it is dropped from the resolved set entirely (the child inherits the parent's existing value - unmodified, since `exec()` only *adds* the resolved pairs on top of an - inherited environment). When `overload` is `true`, process environment + unmodified, except for reserved private-key variables). When `overload` + is `true`, process environment is not consulted at all — file values always win. ## `DOTENV_` filtering and identifier validation @@ -274,14 +275,19 @@ verbatim: ## Encrypted-value format -A raw value that does not start with `encrypted:` is passed through -verbatim as opaque bytes (this is how plaintext values reach the child — -no decryption attempted). A value that does start with `encrypted:` has the +Values are first parsed by `dotenvy`, including its quoting and variable +substitution rules. A parsed value without `encrypted:` needs no decryption +and is passed through as bytes. A value that starts with `encrypted:` has the following payload base64-decoded and decrypted with `ecies` against each candidate key under the matching `DOTENV_PRIVATE_KEY*` name (comma-separated rotation candidates in `.env.keys` are tried in order; first one that decrypts wins). +Decrypted plaintext and bundle entries are not interpolated. For a plaintext +dotenv value, single quotes preserve `${VAR}` literally; unquoted and +double-quoted values can substitute variables. No value is evaluated as shell +code, and `$(cmd)` does not run a command. + **Lenient base64 decoding:** the payload after `encrypted:` may contain ASCII whitespace (spaces, tabs, newlines, carriage returns). If any is present, it is stripped before decoding, so a value that has been @@ -299,7 +305,8 @@ alias). A file name that doesn't start with `.env` is a hard parse error. ## Per-mode injected variables -**`mode: "env"`.** Decrypts `env_files` through the key ring in `keys`, +**`mode: "env"`.** Decrypts `env_files` and `bundle_files` through the key ring +in `keys`, then exports every resolved `KEY=value` pair directly into the child's environment. No pointer files, no `secrets_dir`. A resolved value containing a NUL byte is a hard error @@ -344,11 +351,13 @@ this mode — it dispatches on whether `sockets` is empty: ## Fail-closed rules -- **`strict` (default `true`).** In `env`/`files` modes, if any value - fails to decrypt (bad key, wrong key, malformed ciphertext), the whole +- **`strict` (default `true`).** In `env`/`files` modes, if a selected dotenv + value fails to decrypt (bad key, wrong key, malformed ciphertext), the whole exec aborts before the child runs — nothing partial is injected. With `strict: false`, an undecryptable value is logged and simply omitted from the resolved set (never served as an error string or empty value). + Bundle entries must authenticate regardless of `strict`. `--verify-keys` + also rejects skipped dotenv values when `strict` is false. - **NUL in an environment value** is refused in `env` mode and for `passthrough` values in `files` mode (see above); in `files` mode's primary write path (the pointer-file contents), NUL is not restricted @@ -358,9 +367,9 @@ this mode — it dispatches on whether `sockets` is empty: serve, and fails closed with `": server sent zero bytes (refused to serve); failing closed"` rather than writing an empty credential file. -- **16 MiB read cap.** Every single read — secret, bundle, config, and - fetch payloads — is hard-capped at 16 MiB (`read_capped`); an oversize - payload fails rather than truncates. +- **16 MiB read cap.** Config JSON, bundle JSON, and credential fetch payloads + are capped at 16 MiB by `read_capped`; oversized payloads fail. Dotenv and + private-key files are streamed through `dotenvy` without this cap. - **Missing `$CREDENTIALS_DIRECTORY`** in `credentials` mode's systemd branch fails closed rather than silently exporting nothing. - **Private keys never come from the Nix store.** A `{"file": …}` key diff --git a/docs/src/unsafe-code/index.md b/docs/src/unsafe-code/index.md index 35fd50d..1bda367 100644 --- a/docs/src/unsafe-code/index.md +++ b/docs/src/unsafe-code/index.md @@ -43,7 +43,6 @@ Note what is NOT in the inventory: `mlockall`, `setrlimit(Core, 0)`, and 6. **Write tests** — verify the mitigations work (or document why untestable) 7. **Get review** — unsafe requires explicit approval -The bar is intentionally high. Postmaster's design keeps plaintext -custody to microseconds — decrypt at the last instant, zeroize -immediately, never persist. A memory-safety bug is one of the few -things that can silently break that invariant. +Postmaster decrypts at launch and wipes its key ring and resolved buffers +before `execvp`. A memory-safety bug can expose those buffers or invalidate +cleanup, so each unsafe boundary needs a specific justification. diff --git a/docs/src/unsafe-code/macos-libc-boundary.md b/docs/src/unsafe-code/macos-libc-boundary.md index c053759..2505e0c 100644 --- a/docs/src/unsafe-code/macos-libc-boundary.md +++ b/docs/src/unsafe-code/macos-libc-boundary.md @@ -48,9 +48,9 @@ src/server.rs — fn harden_process (macOS cfg, release builds only) The ptrace-from-peers half of Linux's `PR_SET_DUMPABLE`: deny debugger attachment to the daemon. Compiled only under `not(debug_assertions)`; -`[profile.release]` pins `debug-assertions = false` so a profile override -cannot silently compile it out (audit 2026-08-02 A23). Best-effort by -policy, but a failure is security-relevant and is logged (A10). +`[profile.release]` sets `debug-assertions = false` by default. Enabling debug +assertions, including through a profile environment override, disables this +call. A failed attach-denial request is logged. ### UB Vectors and Mitigations diff --git a/docs/src/unsafe-code/monitor.md b/docs/src/unsafe-code/monitor.md index b83c754..f5f2969 100644 --- a/docs/src/unsafe-code/monitor.md +++ b/docs/src/unsafe-code/monitor.md @@ -1,9 +1,9 @@ # Sibling Launch Monitor -> **At a glance:** a tiny forked sibling — born after every secret has -> been zeroized — watches the service for its whole life. It forwards -> stop signals, escalates to SIGKILL after a short grace, and deletes -> plaintext secret files on every death path, including `kill -9`. +> **At a glance:** a sibling process watches the service until it exits. +> It forwards stop signals, escalates to SIGKILL after a 250 ms grace, and +> removes secret files after exit, a crash, or `kill -9`. It scrubs projected +> environment pairs but retains the launcher's original environment. ## Lifecycle @@ -13,9 +13,9 @@ sequenceDiagram participant M as Monitor (fork-child) participant S as Service (exec'd parent) - L->>L: zeroize plaintext; block stop signals + L->>L: block stop signals; materialize; wipe ring and resolved buffers L->>M: fork() - Note over M: scrub inherited env pairs (wipe_pair); mask stays blocked for life + Note over M: scrub projected pairs; retain original environment; keep mask blocked L->>S: restore mask; execvp becomes service loop poll tick M->>S: liveness (pidfd+poll / kqueue NOTE_EXIT) @@ -48,10 +48,11 @@ Unsafe blocks: fork(2) (libc, both platforms); rustix `runtime` ## Purpose -The sibling-monitor launch supervision design (2026-08-05) closes the -launch-handoff stop-semantics gap and adds plaintext cleanup on **every** -service-death path. After validation, plaintext writes, and zeroization — -and before `execvp` — the launcher `fork()`s. The parent restores its +The sibling monitor closes the launch-handoff stop-semantics gap and +adds plaintext cleanup on **every** service-death path. After +validation, plaintext writes, and zeroization of the key ring and resolved +buffers, and before `execvp`, +the launcher `fork()`s. The parent restores its pre-guard signal mask and execs the service (MainPID unchanged); the fork-child becomes the monitor: it keeps the four termination signals blocked for life, consumes them synchronously (sigpending/sigwait — no @@ -64,6 +65,11 @@ runs `cleanup_written` before exiting — on stop, on natural exit, on were retired with this design: the monitor is the single owner of stop semantics, so no async-signal context exists anywhere. +The scrub does not erase the monitor's original process environment. +Private keys supplied through environment variables can remain there for +the monitor's lifetime. Use a non-environment key source to avoid that +exposure. See [Private-key environment variables](../architecture/threat-model.md#private-key-environment-variables). + ## Why Unsafe - **`fork(2)` has no rustix wrapper** (a deliberate rustix omission), so @@ -72,7 +78,7 @@ semantics, so no async-signal context exists anywhere. exception to the "rustix linux_raw / no libc FFI on Linux" doctrine. Everything else on the Linux leg is rustix. - **Linux signal masking and synchronous consumption** use rustix's - `runtime` module (`kernel_sigprocmask`, `kernel_sigwait`, + experimental runtime API (`kernel_sigprocmask`, `kernel_sigwait`, `kernel_sigpending`, `exit_group`) — rustix's experimental, doc-hidden API for libc-like runtimes. It is the only rustix route to signal masks (there is no `rustix::process::sigprocmask`), and taking it avoids libc @@ -91,7 +97,7 @@ semantics, so no async-signal context exists anywhere. (monitor diagnostics) are fd-ownership assertions of the same kind as the systemd socket boundary. -Liveness findings that shaped the code: rustix 1.x **does** cover +rustix 1.x provides `pidfd_open`/`pidfd_send_signal` (Linux-only) and `poll`, so the pidfd leg needs no fallback in practice; `kill(pid, 0)` polling is kept only for kernels without `pidfd_open` (< 5.3) and for kqueue failure. An @@ -101,11 +107,14 @@ cleanup (on macOS, xnu drops exited procs from the pid table before they are reaped, so NOTE_EXIT registration on an already-exited service fails `ESRCH` — handled as death, not as a fallback trigger). +rustix 1.1.6 exports the experimental API as `runtime_448b8ad740e2a26f`. +The launcher and monitor import it as `runtime`. + ## UB Vectors and Mitigations | Vector | Description | Mitigation | |--------|-------------|------------| -| Fork in a threaded process | The child inherits locked malloc/stdio state | The exec path is single-threaded at fork (worker threads exist only in serve mode). The child performs no allocation, no stdio locks, no destructor runs — only the async-signal-safe syscall set documented at the top of `monitor.rs` — and exits via `_exit`/`exit_group` (no atexit, no stdio flush). Tests fork from the multithreaded harness under the same discipline | +| Fork in a threaded process | The child inherits locked malloc/stdio state | The production launcher is single-threaded at fork. The monitor first scrubs and frees projected env pairs; this exception requires that single-threaded parent. Test children pass an empty pair list. The loop then uses the syscall set documented in `monitor.rs`, without allocation or stdio locks, and exits via `_exit`/`exit_group` | | Invalid `sigset_t` | Uninitialized set passed to sigwait/sigpending | `KernelSigSet::empty()` (rustix) / `zeroed()` + `sigemptyset` (libc) | | Blocking sigwait hang | `sigwait` blocks until a set member is pending | Called only after `sigpending` shows a member pending — single-threaded, so nothing else can dequeue it first | | Mask clobber | Restoring a mask never captured | Linux guard stores `None` on block failure (logged); restore then no-ops | @@ -120,7 +129,7 @@ are reaped, so NOTE_EXIT registration on an already-exited service fails | Risk | Likelihood | Impact | |------|------------|--------| | rustix `runtime` API changes in a future rustix | Low (lockfile-pinned; build fails loudly at update time) | Build breakage, not a runtime defect | -| Monitor dies before the service | Very low (tiny, secretless loop) | Cleanup falls to the pre-existing backstops: `ExecStopPost`, ramdisk teardown, next-launch `prune_stale` — the same floor as before the monitor | +| Monitor dies before the service | Monitor failure or external termination | Cleanup falls to integration-provided `ExecStopPost`, ramdisk teardown, and next-launch `prune_stale` | | Job-control stop (SIGTSTP) of the monitor's process group | Interactive sessions only | The monitor suspends with the service; cleanup waits for continuation — backstops remain | | Service unkillable in D-state after SIGKILL | Kernel pathology | The monitor's post-SIGKILL death wait is unbounded by design (abandoning cleanup is worse); the manager's own escalation path still applies | | Polling fallback on a pre-5.3 kernel | Legacy kernels only | Zombie-blindness until the parent reaps (systemd reaps promptly); PID-reuse exposure as documented | diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md index 2d4ae35..eef0b4a 100644 --- a/docs/src/unsafe-code/signal-deferral.md +++ b/docs/src/unsafe-code/signal-deferral.md @@ -1,9 +1,9 @@ # Signal Deferral (TerminationGuard) > **At a glance:** while postmaster decrypts and injects, termination -> signals are blocked so a well-timed `Ctrl-C` or `systemctl stop` -> cannot strand half-written plaintext. The original mask is captured -> and restored before launch — the service never inherits it. +> signals are blocked to protect the plaintext-write window. The launcher +> restores the captured mask before exec. Masking failures are logged and +> leave the write window unguarded. ## Location @@ -14,13 +14,13 @@ Blocks: block() (sigmask), restore_mask() (sigmask), Drop (restore) ## Purpose -Audit 2026-08-02 A11: on macOS, plaintext secret files persist on the -ramdisk until explicitly removed, so a SIGTERM landing *during* the -plaintext-write window would leave material on disk with no cleanup. -`TerminationGuard` blocks SIGTERM/SIGINT/SIGHUP/SIGQUIT -(`monitor::STOP_SIGNALS`) from just after config validation until the -fork/exec at the end of the window — a deterministic write window: no -termination signal can kill the launcher mid-write. +On macOS, plaintext secret files persist on the ramdisk until +explicitly removed, so a SIGTERM landing *during* the plaintext-write +window would leave material on disk with no cleanup. `TerminationGuard` +blocks SIGTERM/SIGINT/SIGHUP/SIGQUIT (`monitor::STOP_SIGNALS`) from +just after config validation until the fork/exec at the end of the +window — a deterministic write window: no termination signal can kill +the launcher mid-write. At the end of the window the launcher forks the sibling monitor (see [Sibling Launch Monitor](./monitor.md)), which **inherits the blocked @@ -31,9 +31,9 @@ running no destructors). The parent calls `restore_mask()` before The guard previously also carried a sigaction flag-recording handler (`disarm`/`recorded`) and a second pre-exec gate to close the -check/exec race. Both were **retired with the sibling-monitor design -(2026-08-05)**: the monitor owns stop semantics on every death path, so -no async handler is needed anywhere and the handler's forever-purity +check/exec race. Both were **retired with the sibling-monitor +design**: the monitor owns stop semantics on every death path, so no +async handler is needed anywhere and the handler's forever-purity constraint is gone with it. What remains — `block()` and `restore_mask()` — is what this page covers. @@ -68,8 +68,8 @@ holds only standard signals no libc reserves. | Risk | Likelihood | Impact | |------|------------|--------| -| Kernel/libc signal quirks on future OS versions | Very low | Missed deferral (fail-open to pre-A11 behavior) | -| Operator sends SIGKILL mid-write | n/a | Unblockable by design; ramdisk contents persist until next boot (macOS) — accepted residual; the monitor covers everything *after* the fork | +| Kernel/libc signal quirks on future OS versions | Very low | Missed deferral (fail-open to an unguarded write window) | +| Operator sends SIGKILL mid-write | n/a | The monitor has not been forked yet. Files can remain until cleanup, RAM-disk destruction, or reboot | For the design-level stop semantics the guard feeds into (monitor forwarding, grace, escalation, cleanup on every death path), see the diff --git a/docs/src/unsafe-code/test-env-mutation.md b/docs/src/unsafe-code/test-env-mutation.md index 2744828..73d9cd5 100644 --- a/docs/src/unsafe-code/test-env-mutation.md +++ b/docs/src/unsafe-code/test-env-mutation.md @@ -39,9 +39,9 @@ The discipline was previously **per-module**: `keys/source.rs` and `keys/env.rs`'s `from_env_loads_and_fails_closed` mutated env holding no lock at all. Module-local locks do not exclude each other, so two such tests still raced — the loser's panic poisoned a mutex and failed -unrelated tests (~1 in 5 baseline runs, observed 2026-08-04). Since -2026-08-06 every env-mutating test in every module acquires the single -`crate::test_util::ENV_LOCK`; any new env-touching test must do the same. +unrelated tests (~1 in 5 baseline runs). Every env-mutating test in +every module now acquires the single `crate::test_util::ENV_LOCK`; any +new env-touching test must do the same. ## Tests diff --git a/licenses/ecies-MIT.txt b/licenses/ecies-MIT.txt new file mode 100644 index 0000000..51ab670 --- /dev/null +++ b/licenses/ecies-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-2026 Weiliang Li + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/nixpkgs-package.nix b/nixpkgs-package.nix index 545ce30..6cc8c57 100644 --- a/nixpkgs-package.nix +++ b/nixpkgs-package.nix @@ -36,10 +36,6 @@ rustPlatform.buildRustPackage rec { cargoLock = { lockFile = src + "/Cargo.lock"; - # While ecies is git-pinned via [patch.crates-io] (audit 2026-08-02 A7): - # the git dep's fetch hash. Drop once the upstream ecies PR (ecies/rs#159) - # ships on crates.io and the patch section is removed. - outputHashes."ecies-0.2.11" = "sha256-FOKSWQNJ9dZbQZdLI49o1OzeFoS3isQKchylQT/FaFk="; }; meta = { diff --git a/package.nix b/package.nix index 92dac51..8e5a36f 100644 --- a/package.nix +++ b/package.nix @@ -3,8 +3,8 @@ let cargoToml = lib.importTOML ./Cargo.toml; # Build a rustPlatform from the latest stable rust-overlay toolchain. - # nixos-25.05's rustPlatform ships rustc 1.86.0, too old for edition 2024 - # + let-chains (requires >= 1.96.1). rust-overlay provides newer toolchains + # nixos-25.05's rustPlatform ships rustc 1.86.0, below Cargo.toml's + # Rust 1.99.1 minimum. rust-overlay provides newer toolchains # independent of the nixpkgs channel. rustPlatform = makeRustPlatform { rustc = rust-bin.stable.latest.rust; @@ -21,15 +21,11 @@ rustPlatform.buildRustPackage { fileset = lib.fileset.unions [ ./Cargo.toml ./Cargo.lock + ./licenses ./src ]; }; cargoLock.lockFile = ./Cargo.lock; - # Cargo.lock currently pins ecies to a git rev (see [patch.crates-io] in - # Cargo.toml, audit 2026-08-02 A7), so importCargoLock needs the git dep's - # fetch hash. Drop this again when the upstream ecies PR (ecies/rs#159) - # ships on crates.io and the patch section is removed. - cargoLock.outputHashes."ecies-0.2.11" = "sha256-FOKSWQNJ9dZbQZdLI49o1OzeFoS3isQKchylQT/FaFk="; meta = { description = cargoToml.package.description; diff --git a/src/aad.rs b/src/aad.rs new file mode 100644 index 0000000..4ec3f96 --- /dev/null +++ b/src/aad.rs @@ -0,0 +1,90 @@ +//! Entry-name-bound ECIES bundle envelopes. +//! +//! The wire layout is an uncompressed secp256k1 point (65 bytes), nonce +//! (16 bytes), authentication tag (16 bytes), then ciphertext. +// Portions adapted from ecies/rs. Copyright (c) 2019-2026 Weiliang Li. +// MIT license: see licenses/ecies-MIT.txt. + +use aes_gcm::aead::{AeadInOut, KeyInit, Nonce, Tag}; +use aes_gcm::{AesGcm, aes::Aes256, aes::cipher::consts::U16}; +use zeroize::Zeroizing; + +type Cipher = AesGcm; + +/// Decrypt an ECIES envelope with the caller's exact additional authenticated data. +/// +/// Returns plaintext only after authentication succeeds, or `None` for an +/// invalid key, malformed envelope, or authentication failure. +pub(crate) fn decrypt(secret: &[u8], envelope: &[u8], aad: &[u8]) -> Option>> { + let (ephemeral, payload) = envelope.split_at_checked(65)?; + let (nonce, payload) = payload.split_at_checked(16)?; + let (tag, ciphertext) = payload.split_at_checked(16)?; + let secret = ecies::SecretKey::parse_slice(secret).ok()?; + let ephemeral = ecies::PublicKey::parse_slice(ephemeral, None).ok()?; + let key = Zeroizing::new(ecies::utils::decapsulate(&ephemeral, &secret, false).ok()?); + let cipher = Cipher::new_from_slice(&key[..]).ok()?; + let nonce = Nonce::::try_from(nonce).ok()?; + let tag = Tag::::try_from(tag).ok()?; + let mut plaintext = Zeroizing::new(ciphertext.to_vec()); + cipher + .decrypt_inout_detached(&nonce, aad, plaintext.as_mut_slice().into(), &tag) + .ok()?; + Some(plaintext) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::decrypt; + use serde::Deserialize; + + #[derive(Deserialize)] + struct Vector { + aad_hex: String, + ciphertext_hex: String, + plaintext_hex: String, + } + + fn vectors() -> Vec { + // Fixed outputs of the previously deployed AAD fork at 81e1b84. + serde_json::from_str(include_str!("aad/vectors.json")).unwrap() + } + + #[test] + fn decrypts_existing_fork_envelopes_byte_exactly() { + for vector in vectors() { + let ciphertext = hex::decode(vector.ciphertext_hex).unwrap(); + let aad = hex::decode(vector.aad_hex).unwrap(); + let expected = hex::decode(vector.plaintext_hex).unwrap(); + assert_eq!( + decrypt(&[0x11; 32], &ciphertext, &aad).unwrap().as_slice(), + expected + ); + if aad.is_empty() { + assert_eq!(ecies::decrypt(&[0x11; 32], &ciphertext).unwrap(), expected); + } else { + assert!(decrypt(&[0x11; 32], &ciphertext, b"").is_none()); + } + assert!(decrypt(&[0x11; 32], &ciphertext, b"wrong-entry").is_none()); + assert!(decrypt(&[0x22; 32], &ciphertext, &aad).is_none()); + } + } + + #[test] + fn malformed_and_tampered_envelopes_fail_closed() { + let vector = vectors().remove(1); + let ciphertext = hex::decode(vector.ciphertext_hex).unwrap(); + let aad = hex::decode(vector.aad_hex).unwrap(); + for len in 0..ciphertext.len() { + assert!(decrypt(&[0x11; 32], &ciphertext[..len], &aad).is_none()); + } + for i in 0..ciphertext.len() { + let mut changed = ciphertext.clone(); + changed[i] ^= 1; + assert!(decrypt(&[0x11; 32], &changed, &aad).is_none(), "byte {i}"); + } + for key in [vec![], vec![0x11; 31], vec![0; 32], vec![0xff; 32]] { + assert!(decrypt(&key, &ciphertext, &aad).is_none()); + } + } +} diff --git a/src/aad/vectors.json b/src/aad/vectors.json new file mode 100644 index 0000000..865ae84 --- /dev/null +++ b/src/aad/vectors.json @@ -0,0 +1,22 @@ +[ + { + "aad_hex": "", + "ciphertext_hex": "04e1f84068c5393739e00975958030f5d3d84b293ad251faff1834c6356018ab3f0397b905f2ef5854a32d99a48d6f8eed001708ba61dabad3517253dd4fbd3acd709ee1c06a162bdec0e1fc9643b984327afffc2c624eba46dab7f80419727de85704a27e9f21", + "plaintext_hex": "6c6567616379" + }, + { + "aad_hex": "534543524554", + "ciphertext_hex": "0499c1196596fc690653b4ead8717a6724263c8de7b1343209c122449d278a8e052709a129652b91a5b31336b3eff9981d1a248ef53ebf48eb2ec6a288de8ebde20c98c863fad6ec3c0c5af2cb8532168f742e58bea3495da5427c0c3c41a3db4a894e564e987dafc322aaf8d8f06d0f", + "plaintext_hex": "6578697374696e672062756e646c65" + }, + { + "aad_hex": "42494e415259", + "ciphertext_hex": "04b259c62d4e1d2b6f81f13966287f4967d94e82d9675b192217ed7e9440c4db5d6182ab0321bd5f59c745c3b22dd1f0b871c961cbc65e9a9b4d029a73d9d06fa687eabd3efe5e634c85bcce1fad68155a4b5075a792f640f1cf44c893069adf2f07f0f303", + "plaintext_hex": "00ff800a" + }, + { + "aad_hex": "454d505459", + "ciphertext_hex": "04ce8c1eb88b4f167ea05c0fd9f4125fc9abc9d552479d22178bcdf813674d38ebb2105880f5c41a2b85a118cf09e24684c7c7ad4061da0b97a055e4a9a3c8d58fd162e634288caf1379e99749ab73368423221113f1910e6a6f786b63bf8c5d77", + "plaintext_hex": "" + } +] diff --git a/src/adapter/bundle.rs b/src/adapter/bundle.rs index a46c8d8..29818ab 100644 --- a/src/adapter/bundle.rs +++ b/src/adapter/bundle.rs @@ -4,7 +4,7 @@ //! The bundle format is a JSON file with: //! - `format`: must be `"postmaster.bundle"` (fail closed on unknown) //! - `version`: integer, must be `1` -//! - `profile`: optional public selection metadata (not a secret) +//! - `profile`: optional public metadata, not used for key selection //! - `suite`: mandatory crypto suite identifier (must match the ECIES path) //! - `recipients`: array of `{ id, public_key }` — public routing metadata //! - `entries`: map of key name → `{ encoding, ciphertext }` @@ -13,7 +13,7 @@ //! encrypted and authenticated. Each entry's ciphertext is additionally //! bound to its key name as AES-GCM additional authenticated data (AAD): //! a ciphertext cut from one entry and pasted under another name fails -//! decryption (audit 2026-08-02 A7). Entries use the same identifier +//! decryption. Entries use the same identifier //! rule as `.env`-derived keys: `[A-Za-z_][A-Za-z0-9_]*`. use std::path::Path; @@ -23,7 +23,7 @@ use base64::engine::general_purpose::STANDARD as BASE64; use serde::Deserialize; use zeroize::Zeroizing; -use crate::keys::{KeyRing, is_ident}; +use crate::keys::{KeyRing, is_ident, is_private_key_var_name}; /// The top-level bundle container. #[derive(Deserialize, Debug)] @@ -33,7 +33,7 @@ pub struct Bundle { pub format: String, /// Must be `1`. pub version: u32, - /// Optional public selection metadata (not a secret). + /// Optional public metadata, not used to select keys or entries. #[serde(default)] pub profile: Option, /// Mandatory crypto suite identifier. @@ -48,13 +48,14 @@ pub struct Bundle { /// A recipient in the bundle: public routing metadata reserved for /// future recipient selection. Parsed and shape-validated only today — /// resolution selects ring candidates by the fixed `POSTMASTER_KEY` -/// variable, never by recipient (sweep 2026-08-07 K10). +/// variable, never by recipient. #[derive(Deserialize, Debug)] #[serde(deny_unknown_fields)] pub struct Recipient { /// Public identifier for this recipient (e.g., `"host:api-01"`). pub id: String, - /// Compressed secp256k1 public key (hex-encoded). + /// Public-key metadata, conventionally compressed secp256k1 hex. + /// Parsed as a string; not used for decryption. pub public_key: String, } @@ -62,9 +63,8 @@ pub struct Recipient { #[derive(Deserialize, Debug)] #[serde(deny_unknown_fields)] pub struct BundleEntry { - /// Either `"utf8"` or `"bytes"`. `env` projection rejects bytes that - /// cannot become a POSIX environment value; `files` and `credentials` - /// preserve byte-exact values. + /// Either `"utf8"` or `"bytes"`. UTF-8 is validated during resolution. + /// Env projection rejects NUL bytes; files preserve byte-exact values. pub encoding: Encoding, /// Base64-encoded ECIES ciphertext. pub ciphertext: String, @@ -74,9 +74,9 @@ pub struct BundleEntry { #[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum Encoding { - /// UTF-8 string value (env projection rejects non-UTF-8). + /// UTF-8 string value, validated during resolution in every mode. Utf8, - /// Raw byte value (files/credentials preserve byte-exact). + /// Raw byte value; files preserve it and env projection rejects NUL. Bytes, } @@ -86,7 +86,7 @@ pub enum Encoding { /// (authentication failure), not just here. const SUITE: &str = "ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad"; -/// Parse a bundle JSON file from raw bytes. +/// Parse a bundle JSON file, rejecting invalid metadata and reserved key names. pub fn parse_bundle(raw: &[u8], path: &Path) -> Result { let bundle: Bundle = serde_json::from_slice(raw).map_err(|e| format!("{}: {e}", path.display()))?; @@ -118,6 +118,12 @@ pub fn parse_bundle(raw: &[u8], path: &Path) -> Result { path.display() )); } + if is_private_key_var_name(name) { + return Err(format!( + "{}: key {name:?} is reserved for private-key provisioning", + path.display() + )); + } } Ok(bundle) } @@ -151,8 +157,8 @@ pub fn resolve_bundle( // entry fails authentication here (audit 2026-08-02 A7). let mut decrypted: Option>> = None; for sk in candidates { - if let Ok(pt) = ecies::decrypt_with_aad(&sk[..], &ciphertext, name.as_bytes()) { - decrypted = Some(Zeroizing::new(pt)); + if let Some(pt) = crate::aad::decrypt(&sk[..], &ciphertext, name.as_bytes()) { + decrypted = Some(pt); break; } } @@ -187,6 +193,7 @@ pub fn resolve_bundle( #[allow(clippy::unwrap_used, clippy::panic, unused_qualifications)] mod tests { use super::*; + use crate::test_util::aad_fixture::encrypt; use std::collections::BTreeMap; fn test_pk_hex() -> String { @@ -222,7 +229,7 @@ mod tests { fn enc(name: &str, value: &str) -> String { let pk = hex::decode(test_pk_hex()).unwrap(); - let ct = ecies::encrypt_with_aad(&pk, value.as_bytes(), name.as_bytes()).unwrap(); + let ct = encrypt(&pk, value.as_bytes(), name.as_bytes()); BASE64.encode(ct) } @@ -344,10 +351,11 @@ mod tests { let other_sk_bytes = hex::decode(&other_sk).unwrap(); let other_sk = ecies::SecretKey::parse_slice(&other_sk_bytes).unwrap(); let other_pk = ecies::PublicKey::from_secret_key(&other_sk); - let ct = BASE64.encode( - ecies::encrypt_with_aad(&other_pk.serialize_compressed(), b"unreachable", b"SECRET") - .unwrap(), - ); + let ct = BASE64.encode(encrypt( + &other_pk.serialize_compressed(), + b"unreachable", + b"SECRET", + )); let bundle = make_bundle(vec![("SECRET", &ct, Encoding::Utf8)]); let ring = crate::keys::tests::make_test_ring(); let err = resolve_bundle(&bundle, &ring, Path::new("/test")).unwrap_err(); @@ -358,7 +366,7 @@ mod tests { fn resolve_bundle_handles_bytes_encoding() { let binary_val = b"\x00\x01\x02\xff"; let pk = hex::decode(test_pk_hex()).unwrap(); - let ct = BASE64.encode(ecies::encrypt_with_aad(&pk, binary_val, b"TLS_KEY").unwrap()); + let ct = BASE64.encode(encrypt(&pk, binary_val, b"TLS_KEY")); let bundle = make_bundle(vec![("TLS_KEY", &ct, Encoding::Bytes)]); let ring = crate::keys::tests::make_test_ring(); let resolved = resolve_bundle(&bundle, &ring, Path::new("/test")).unwrap(); @@ -373,7 +381,7 @@ mod tests { // `encoding: "bytes"` stays byte-exact. let invalid = b"\xff\xfe"; let pk = hex::decode(test_pk_hex()).unwrap(); - let ct = BASE64.encode(ecies::encrypt_with_aad(&pk, invalid, b"GREETING").unwrap()); + let ct = BASE64.encode(encrypt(&pk, invalid, b"GREETING")); let ring = crate::keys::tests::make_test_ring(); let bundle = make_bundle(vec![("GREETING", &ct, Encoding::Utf8)]); diff --git a/src/adapter/mod.rs b/src/adapter/mod.rs index d505845..35558f0 100644 --- a/src/adapter/mod.rs +++ b/src/adapter/mod.rs @@ -27,8 +27,7 @@ pub enum KeyNaming { /// `.env.production` → `DOTENV_PRIVATE_KEY_PRODUCTION`. Env, /// The `postmaster_bundle` adapter. Uses `POSTMASTER_KEY` as its - /// key variable naming (no per-environment suffix — the bundle's - /// `profile` field handles environment selection). No metadata + /// key variable naming, regardless of filename or `profile`. No metadata /// prefix (the bundle format is structured JSON, not flat key-value). Bundle, } @@ -56,8 +55,7 @@ impl KeyNaming { /// Map an artifact filename to the key variable name it needs. /// `.env` → `DOTENV_PRIVATE_KEY`, `.env.production` → /// `DOTENV_PRIVATE_KEY_PRODUCTION`. Bundle files map to a single - /// key variable regardless of filename (the `profile` field inside - /// the bundle handles environment selection). + /// key variable regardless of filename. `profile` does not select a key. pub fn key_var_for(self, artifact_path: &Path) -> Result { match self { KeyNaming::Env => { diff --git a/src/cli/mod.rs b/src/cli/mod.rs index e30f65e..4a10605 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -16,8 +16,7 @@ mod help; pub use help::{HELP_CLEANUP, HELP_EXEC, HELP_FETCH, HELP_SETUP, HELP_TOP}; /// Full configuration loaded from the JSON file produced by the Nix module. -/// Unknown fields are rejected (audit 2026-08-02 A21) — same strictness -/// as the exec config. +/// Unknown fields are rejected — same strictness as the exec config. #[derive(Deserialize, Debug)] #[serde(deny_unknown_fields)] pub struct Config { @@ -40,7 +39,7 @@ pub enum KeysSource { #[derive(Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] /// A single credential mapping served by postmaster. Unknown fields are -/// rejected (audit 2026-08-02 A21) — same strictness as `Config`. +/// rejected — same strictness as `Config`. pub struct Entry { /// encrypted env file (a Nix store path; ciphertext is public). pub env_file: PathBuf, @@ -61,7 +60,7 @@ pub struct Args { /// Bind listener sockets even when not socket-activated. pub bind: bool, /// Allow non-root peers to connect (dev escape hatch; never overrides - /// a configured `peer_user` ACL — sweep 2026-08-07 D1). + /// a configured `peer_user` ACL). pub allow_nonroot: bool, } @@ -84,9 +83,9 @@ pub enum Invocation { check: bool, /// Preflight: fail unless EVERY value in every env file /// decrypts. Catches stale keys from a previous rotation cycle - /// that are valid hex but no longer match the ciphertext (audit - /// finding #4); under `strict: false` any skipped/undecryptable - /// value also aborts the launch (fail-closed). + /// that are valid hex but no longer match the ciphertext; under + /// `strict: false` any skipped/undecryptable value also aborts + /// the launch (fail-closed). verify_keys: bool, /// Child argv — everything after `--` on the command line. argv: Vec, @@ -114,8 +113,7 @@ pub enum Invocation { /// `ExecStopPost` in systemd or equivalent lifecycle hooks in other /// service managers. Does not decrypt — only removes files that /// postmaster would have written. Bulk removal is refused for a - /// non-empty directory lacking the `.postmaster-managed` sentinel - /// (audit 2026-08-02 A19). + /// non-empty directory lacking the `.postmaster-managed` sentinel. Cleanup { /// Path to the exec config JSON. config: PathBuf, @@ -130,8 +128,8 @@ pub enum Invocation { pub const VERSION: &str = env!("CARGO_PKG_VERSION"); /// Consume the value of a value-taking option, rejecting another flag as -/// the value (sweep 2026-08-07 D6): `--config --check` must not parse -/// `"--check"` as the config path. +/// the value: `--config --check` must not parse `"--check"` as the +/// config path. fn option_value( it: &mut std::iter::Peekable>, flag: &str, diff --git a/src/exec_config.rs b/src/exec_config.rs index 6f042c7..b31d3cf 100644 --- a/src/exec_config.rs +++ b/src/exec_config.rs @@ -26,13 +26,14 @@ pub struct ExecConfig { /// Encrypted env files, in precedence order (first wins unless overload). #[serde(default)] pub env_files: Vec, - /// Encrypted `postmaster_bundle` files, in precedence order. + /// Encrypted `postmaster_bundle` files, resolved after `env_files`. /// Each file is a JSON container with `format: "postmaster.bundle"`. - /// Entries are merged with `env_files` entries; bundle keys use the - /// same identifier rule and the same injection modes. + /// The first definition wins unless `overload` selects the last. + /// Bundle keys use the same identifier rule and injection modes. #[serde(default)] pub bundle_files: Vec, - /// Any undecryptable value aborts before exec (fail closed). + /// Undecryptable dotenv values abort before exec unless false. + /// Bundle authentication failures always abort. #[serde(default = "default_true")] pub strict: bool, /// File values override process env; later files override earlier. @@ -44,7 +45,7 @@ pub struct ExecConfig { /// files mode: keys ALSO exported as real env vars. #[serde(default)] pub passthrough: Vec, - /// credentials mode: keys exposed as $CREDENTIALS_DIRECTORY/. + /// credentials mode: keys exposed as `$CREDENTIALS_DIRECTORY/`. #[serde(default)] pub credential_keys: Vec, /// credentials mode, darwin: key → postmaster socket to fetch from. @@ -84,7 +85,7 @@ pub enum KeySourceSpec { File(PathBuf), /// Read from macOS Keychain (terminal, macOS only). Keychain(String), - /// Read `DOTENV_PRIVATE_KEY*` from the process environment. + /// Read the required adapters' private-key variables from the environment. Environment, } diff --git a/src/keys/env.rs b/src/keys/env.rs index da4d7d9..d6b39a1 100644 --- a/src/keys/env.rs +++ b/src/keys/env.rs @@ -7,7 +7,7 @@ use crate::adapter::KeyNaming; /// True for exactly `PREFIX` or `PREFIX_`. A bare /// prefix match would slurp unrelated variables like -/// `DOTENV_PRIVATE_KEYFOO` as key material (audit 2026-08-02 A16). +/// `DOTENV_PRIVATE_KEYFOO` as key material. pub(crate) fn is_key_var_name(prefix: &str, name: &str) -> bool { name == prefix || name @@ -15,6 +15,13 @@ pub(crate) fn is_key_var_name(prefix: &str, name: &str) -> bool { .is_some_and(|rest| rest.len() > 1 && rest.starts_with('_')) } +/// Whether `name` is a private-key variable for any supported adapter. +pub(crate) fn is_private_key_var_name(name: &str) -> bool { + [KeyNaming::Env, KeyNaming::Bundle] + .into_iter() + .any(|n| is_key_var_name(n.key_prefix(), name)) +} + /// Implementation of [`KeyRing::from_env`]; the contract is documented on /// the method. pub(super) fn from_env(namings: &[KeyNaming]) -> Result { diff --git a/src/keys/mod.rs b/src/keys/mod.rs index 3b8f925..e960729 100644 --- a/src/keys/mod.rs +++ b/src/keys/mod.rs @@ -28,13 +28,10 @@ mod verify; /// Re-exported so `crate::keys::verify_external_binary` keeps resolving. pub use verify::verify_external_binary; -/// The exact predicate `KeyRing::from_env` and `KeyRing::from_pairs` -/// admit, re-exported so setup verification accepts precisely the -/// variables resolution would load (audit 2026-08-02 A16; from_pairs -/// shares the predicate since sweep 2026-08-07 K6). -pub(crate) use env::is_key_var_name; +/// Key-variable predicates shared by loading, setup and launch validation. +pub(crate) use env::{is_key_var_name, is_private_key_var_name}; -/// Full variable name (adapter-specific, e.g. DOTENV_PRIVATE_KEY[_]) +/// Full variable name (adapter-specific, e.g. `DOTENV_PRIVATE_KEY[_]`) /// → candidate secret keys. Multiple candidates per name come from /// comma-separated rotation convention; decryption tries each in order. pub struct KeyRing(HashMap>>); @@ -64,7 +61,7 @@ impl KeyRing { /// Security invariants enforced on the opened file (all checked on the /// file descriptor, never the path, to eliminate TOCTOU windows): /// - `O_NOFOLLOW`: reject a symlink at `path` (defense-in-depth; also - /// closes the credential-source symlink leg of audit finding #2). + /// closes the credential-source symlink attack leg). /// - `mode & 0o077 == 0`: no group or world read/write/exec. A keys /// file accidentally `chmod 0644` would expose private keys to every /// process on the host; fail closed instead. @@ -78,9 +75,9 @@ impl KeyRing { /// Core parser shared by every key source: keep keys exactly matching /// the required adapters' key prefixes (`PREFIX` or `PREFIX_` — - /// the A16 predicate; a bare starts_with admitted unreachable + /// the key-variable predicate; a bare starts_with admitted unreachable /// prefix-collision material like `DOTENV_PRIVATE_KEYFOO` from keys - /// files, sweep 2026-08-07 K6), split comma-separated rotation + /// files), split comma-separated rotation /// candidates, hex-decode to 32-byte zeroized keys. Empty result is an /// error (fail closed). Takes `Zeroizing` values so callers /// never hand key material as a plain heap String that drops without @@ -273,8 +270,8 @@ pub struct Resolution { pub resolved: ResolvedVars, /// `(name, error)` for each encrypted value that could not be /// decrypted and was skipped under `strict: false`. Recorded so - /// `--verify-keys` can fail closed on a partial key rotation - /// (audit 2026-08-02 A3). Always empty under `strict: true`, where + /// `--verify-keys` can fail closed on a partial key rotation. + /// Always empty under `strict: true`, where /// the first failure aborts the whole pass instead. pub failed: Vec<(String, String)>, } diff --git a/src/keys/provisioning/mod.rs b/src/keys/provisioning/mod.rs index e1e9bb3..ae608fd 100644 --- a/src/keys/provisioning/mod.rs +++ b/src/keys/provisioning/mod.rs @@ -40,7 +40,7 @@ fn default_keys_dir() -> PathBuf { /// If it exists, verify permissions and ownership are correct, correcting /// the mode whenever wrong. `force` has no directory effect — there is /// nothing to re-seed in a directory; force governs the keys file and the -/// keychain items (sweep 2026-08-07 K7). +/// keychain items. #[allow(clippy::print_stderr)] fn ensure_keys_dir(keys_dir: &Path, _force: bool) -> Result<(), String> { if keys_dir.exists() { @@ -122,7 +122,7 @@ fn ensure_keys_dir(keys_dir: &Path, _force: bool) -> Result<(), String> { /// exists but has wrong permissions, fix them. /// /// `--force` re-prompts for the contents even when the file is already -/// correct (manual key rotation, sweep 2026-08-07 K7). Force requires +/// correct (manual key rotation). Force requires /// interactive mode: unattended has no operator to paste contents. #[allow(clippy::print_stderr)] fn ensure_keys_file(path: &Path, force: bool, unattended: bool) -> Result<(), String> { @@ -267,8 +267,7 @@ fn ensure_keys_file(path: &Path, force: bool, unattended: bool) -> Result<(), St /// Verify keychain items exist for the wanted key variables. If they /// don't exist and we're in interactive mode, offer to seed them. -/// `--force` re-seeds EVERY wanted item, present or not (sweep -/// 2026-08-07 K7). On macOS only. +/// `--force` re-seeds EVERY wanted item, present or not. On macOS only. #[cfg(target_os = "macos")] #[allow(clippy::print_stderr)] fn ensure_keychain_items( diff --git a/src/keys/verify.rs b/src/keys/verify.rs index 99e86cb..b0456c9 100644 --- a/src/keys/verify.rs +++ b/src/keys/verify.rs @@ -5,7 +5,7 @@ use std::path::Path; /// Verify the integrity of an external binary before invoking it as part /// of a secret-handling path. This is a defense-in-depth trust boundary -/// check (audit finding #3): the binary path is a trust root, and we +/// check: the binary path is a trust root, and we /// verify it has not been tampered with before exec. /// /// On macOS: `codesign -v ` verifies the code signature. The binary @@ -17,7 +17,7 @@ use std::path::Path; /// on Linux, so ownership and permission checks are the practical /// defense-in-depth boundary. /// -/// Bootstrap limitation (audit 2026-08-02 O2): on macOS the verifier +/// Bootstrap limitation: on macOS the verifier /// itself invokes `/usr/bin/codesign`. Self-verifying codesign with /// codesign is circular — a compromised codesign would vouch for /// itself — so codesign is trusted via SIP alone. Moving verification @@ -33,7 +33,7 @@ pub fn verify_external_binary(path: &Path) -> Result<(), String> { .map_err(|e| format!("{}: codesign verification failed: {e}", path.display()))?; if !out.status.success() { return Err(format!( - "{}: code signature verification failed (audit finding #3 trust boundary)", + "{}: code signature verification failed (binary trust boundary)", path.display() )); } diff --git a/src/launcher.rs b/src/launcher.rs index 359ad89..2652da0 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -1,9 +1,7 @@ -//! `postmaster exec` — the envelope launcher. Reads a public JSON config, -//! loads private keys, decrypts values natively (same ecies path as the -//! daemon), injects via the configured mode, and execvp's the target. -//! This file OWNS the injection boundary formerly templated as shell in -//! modules/lib.nix: values are opaque bytes end to end — no interpolation, -//! no eval, no shell. +//! Read a public launch config, load keys, decrypt inputs, and project values +//! before replacing the launcher with the target binary through `execvp`. +//! Decrypted values are injected as bytes without shell evaluation. Plaintext +//! dotenv inputs follow `dotenvy` parsing rules, including variable substitution. use std::collections::HashMap; use std::ffi::OsString; @@ -12,11 +10,14 @@ use std::os::unix::ffi::OsStringExt; use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; +#[cfg(target_os = "linux")] +use rustix::runtime_448b8ad740e2a26f as runtime; + use crate::adapter::KeyNaming; use crate::bundle::{parse_bundle, resolve_bundle}; use crate::exec_config::{ExecConfig, ExecMode}; use crate::key_source::load_ring; -use crate::keys::resolve_all; +use crate::keys::{is_private_key_var_name, resolve_all}; use crate::monitor::{self, STOP_SIGNALS}; use crate::ramdisk::verify_ramdisk; use crate::secret_files::{ @@ -25,7 +26,7 @@ use crate::secret_files::{ use crate::server::{fetch_bytes, log, read_capped}; /// Guard deferring termination signals across the window where plaintext -/// secret files exist on the ramdisk/tmpfs (audit 2026-08-02 A11). A +/// secret files exist on the ramdisk/tmpfs. A /// signal landing mid-write would otherwise strand partial plaintext, so /// the four termination signals (`STOP_SIGNALS`) are *blocked* across the /// window. The sibling monitor is then forked — it inherits the blocked @@ -34,8 +35,8 @@ use crate::server::{fetch_bytes, log, read_capped}; /// signal state. /// /// The sigaction flag-handler and second pre-exec gate this guard used -/// to implement were retired with the sibling-monitor design -/// (2026-08-05): the monitor owns stop semantics, so no async handler is +/// to implement were retired with the sibling-monitor design: the +/// monitor owns stop semantics, so no async handler is /// needed anywhere. What remains is the deterministic write window /// (`block`) and the pre-exec mask restore (`restore_mask`) — now real /// on Linux too, because the fork+monitor model runs there as well. @@ -43,8 +44,7 @@ use crate::server::{fetch_bytes, log, read_capped}; pub(crate) struct TerminationGuard { /// `None` only if the block call failed (logged); restore then no-ops /// rather than installing an empty mask that would unblock signals the - /// launcher's parent deliberately blocked — mirrors the Linux leg - /// (sweep 2026-08-07 X2). + /// launcher's parent deliberately blocked — mirrors the Linux leg. old: Option, } @@ -97,13 +97,13 @@ impl Drop for TerminationGuard { pub(crate) struct TerminationGuard { /// `None` only if the block call failed (logged); restore then no-ops /// rather than clobbering a mask that was never captured. - old: Option, + old: Option, } #[cfg(target_os = "linux")] impl TerminationGuard { pub(crate) fn block() -> Self { - let mut set = rustix::runtime::KernelSigSet::empty(); + let mut set = runtime::KernelSigSet::empty(); for sig in STOP_SIGNALS { set.insert(sig); } @@ -112,9 +112,7 @@ impl TerminationGuard { // reserves 32/33, untouched). The launcher is single-threaded at // this point (the exec path spawns no threads; worker threads // exist only in serve mode). - match unsafe { - rustix::runtime::kernel_sigprocmask(rustix::runtime::How::BLOCK, Some(&set)) - } { + match unsafe { runtime::kernel_sigprocmask(runtime::How::BLOCK, Some(&set)) } { Ok(old) => Self { old: Some(old) }, Err(e) => { // rt_sigprocmask cannot realistically fail here (EINVAL/ @@ -132,9 +130,7 @@ impl TerminationGuard { if let Some(old) = &self.old { // SAFETY: restoring a mask previously returned by the kernel // for this thread. - let _ = unsafe { - rustix::runtime::kernel_sigprocmask(rustix::runtime::How::SETMASK, Some(old)) - }; + let _ = unsafe { runtime::kernel_sigprocmask(runtime::How::SETMASK, Some(old)) }; } } } @@ -164,8 +160,8 @@ pub fn check_config(config_path: &Path) -> Result<(), String> { } /// Preflight key freshness check: fail if any encrypted env value was -/// skipped during resolution because the key ring could not decrypt it -/// (audit 2026-08-02 A3). Under `strict: false` a partial key rotation +/// skipped during resolution because the key ring could not decrypt it. +/// Under `strict: false` a partial key rotation /// would otherwise pass silently here — the old check only caught total /// failure (empty resolved set) — and the child would launch with a /// partial secret set. The failure list recorded by `resolve_all` makes @@ -174,7 +170,7 @@ pub fn check_config(config_path: &Path) -> Result<(), String> { /// Bundle files need no scan here: `resolve_bundle` is all-or-nothing — /// the first undecryptable entry aborts `decrypt()` regardless of /// `strict`, so stale bundle keys already fail closed before this check -/// runs (audit 2026-08-02 A4). +/// runs. fn verify_key_freshness(failed: &[(String, String)]) -> Result<(), String> { if let Some((k, _)) = failed.first() { return Err(format!( @@ -239,7 +235,12 @@ fn decrypt(cfg: &ExecConfig) -> Result<(Resolved, Vec<(String, String)>), String (r.resolved, r.failed) }; - // Resolve bundle files (if any) via the bundle adapter + let mut positions: HashMap = resolved + .iter() + .enumerate() + .map(|(i, (name, _))| (name.clone(), i)) + .collect(); + // Bundle files follow env files and use the same first/last-wins contract. for bundle_path in &cfg.bundle_files { // O_NOFOLLOW on the ciphertext open (audit 2026-08-02 A13): // refuse to read through a planted symlink. @@ -274,7 +275,14 @@ fn decrypt(cfg: &ExecConfig) -> Result<(Resolved, Vec<(String, String)>), String "{name}: value contains a NUL byte; cannot be an environment variable (use files mode)" )); } - resolved.push((name, value)); + if let Some(&i) = positions.get(&name) { + if cfg.overload { + resolved[i].1 = value; + } + } else { + positions.insert(name.clone(), resolved.len()); + resolved.push((name, value)); + } } } @@ -510,6 +518,15 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() sig_guard.restore_mask(); let mut cmd = std::process::Command::new(program); cmd.args(&argv[1..]).envs(extra); + // Remove after projection so resolved values cannot reintroduce private-key variables. + let private_key_names: Vec<_> = std::env::vars_os() + .map(|(name, _)| name) + .chain(cmd.get_envs().map(|(name, _)| name.to_os_string())) + .filter(|name| name.to_str().is_some_and(is_private_key_var_name)) + .collect(); + for name in private_key_names { + cmd.env_remove(name); + } let err = cmd.exec(); // only returns on failure // execvp failed: the process image was NOT replaced, so any // plaintext secret files written above would otherwise persist diff --git a/src/lib.rs b/src/lib.rs index 00dff1f..4678158 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,6 +15,7 @@ // NEW duplicates — remove this allow when syn 2 leaves the tree. #![allow(clippy::multiple_crate_versions)] +mod aad; pub mod adapter; pub mod cli; pub mod exec_config; diff --git a/src/monitor.rs b/src/monitor.rs index 28534db..40cafe4 100644 --- a/src/monitor.rs +++ b/src/monitor.rs @@ -1,15 +1,18 @@ //! Sibling launch monitor — a per-service fork-child that owns stop -//! semantics and plaintext cleanup on every service-death path -//! (sibling-monitor launch supervision design, 2026-08-05). +//! semantics and plaintext cleanup on every service-death path. //! //! The launcher forks the monitor after validation, plaintext writes, and -//! zeroization, and immediately before `execvp`: the parent restores its +//! zeroization of the key ring and resolved values, immediately before `execvp`. +//! The parent restores its //! pre-guard signal mask and execs the service (MainPID unchanged), and -//! the fork-child becomes the monitor. The monitor carries only the +//! the fork-child becomes the monitor. Cleanup uses the //! pinned secrets-dir fd (inherited across fork; `CLOEXEC` does not fire //! because the monitor never execs) and the list of written entry names //! — in env mode both are empty and cleanup is a no-op, but the monitor //! still runs (uniform semantics: it forwards stops regardless). +//! The monitor scrubs projected env pairs, but retains the original process +//! environment. Environment-supplied private keys can remain there; filtering +//! the application's environment before exec does not erase the monitor's copy. //! //! Signal discipline: the four termination signals ({TERM, INT, HUP, //! QUIT}) stay *blocked for the monitor's whole life* — the mask is @@ -62,7 +65,7 @@ use rustix::event::{PollFd, PollFlags, poll}; #[cfg(target_os = "linux")] use rustix::process::{PidfdFlags, pidfd_open, pidfd_send_signal}; #[cfg(target_os = "linux")] -use rustix::runtime::{self, KernelSigSet}; +use rustix::runtime_448b8ad740e2a26f::{self as runtime, KernelSigSet}; #[cfg(target_os = "macos")] use std::os::fd::{AsRawFd, FromRawFd}; @@ -92,9 +95,9 @@ pub(crate) fn wipe_pair(k: std::ffi::OsString, v: std::ffi::OsString) -> (Vec bool { /// True when `dir` names a path lexically beneath `mount_point` /// (component-wise, with no `..` escape). Lexical only — the caller has /// already proven `dir` a real, non-symlink directory and `mount_point` -/// present in mount output (sweep 2026-08-07 X1). +/// present in mount output. fn path_beneath(dir: &Path, mount_point: &Path) -> bool { match dir.strip_prefix(mount_point) { Ok(rest) => !rest @@ -92,8 +91,7 @@ fn path_beneath(dir: &Path, mount_point: &Path) -> bool { } } -/// darwin ramdisk guard (was ramdiskGuard in modules/darwin.nix): plaintext -/// lands only beneath the postmaster ramdisk, in a directory this user owns. +/// Verify a macOS RAM-backed mount and a contained directory owned by this user. pub fn verify_ramdisk(mount_point: &Path, secrets_dir: &Path) -> Result<(), String> { // Trust boundary (audit 2026-08-02 O2): a compromised /sbin/mount or // hdiutil could report persistent disk as the RAM-backed postmaster diff --git a/src/secret_files.rs b/src/secret_files.rs index 770636c..c49e816 100644 --- a/src/secret_files.rs +++ b/src/secret_files.rs @@ -19,8 +19,8 @@ use zeroize::Zeroizing; /// Resolved values keyed by name, each zeroized on drop. pub type Resolved = Vec<(String, Zeroizing>)>; -/// Marker file postmaster creates in any secrets_dir it writes to -/// (audit 2026-08-02 A19). `prune_stale` and `cleanup` refuse to +/// Marker file postmaster creates in any secrets_dir it writes to. +/// `prune_stale` and `cleanup` refuse to /// bulk-delete in a non-empty directory that lacks it — foreign files /// could be present. A permission-mode check cannot make that /// distinction: the Linux files-mode secrets dir is a namespace-private @@ -45,7 +45,7 @@ pub fn env_pairs(resolved: &Resolved) -> Result, Strin /// Open and pin a secrets directory by fd: `O_RDONLY|O_DIRECTORY| /// O_NOFOLLOW|O_CLOEXEC` rejects a symlink or non-directory at open and /// pins the inode, so subsequent `*at` operations are relative to it -/// rather than to a re-resolved path (audit 2026-08-02 A12). +/// rather than to a re-resolved path. pub(crate) fn open_secrets_dir(dir: &Path) -> rustix::io::Result { rustix::fs::open( dir, @@ -83,14 +83,13 @@ pub(crate) fn read_dir_names(dir_fd: impl AsFd) -> rustix::io::Result(reader: R, path: &Path) -> Result, String> { @@ -198,8 +197,8 @@ fn peer_euid(stream: &UnixStream) -> std::io::Result { Ok(euid) } -/// Apply process-level hardening: disable core dumps, prevent ptrace -/// attachment, and pin memory (Linux only). Called once at startup. +/// Attempt to disable dumps and peer tracing and lock memory on Linux. +/// Failures are logged. Dumpability and memory locks reset across exec. #[cfg(target_os = "linux")] pub fn harden_process() { // No core dumps, no ptrace from non-privileged peers. Best-effort by @@ -224,8 +223,8 @@ pub fn harden_process() { } } -/// Apply process-level hardening: disable core dumps and prevent ptrace -/// attachment (macOS only). Called once at startup. +/// Attempt to disable core dumps and, in release builds, peer tracing on macOS. +/// Failures are logged. #[cfg(target_os = "macos")] pub fn harden_process() { // Closest analog to PR_SET_DUMPABLE for dumps: no core files, ever. @@ -315,7 +314,7 @@ fn verified_id_binary() -> Result<&'static str, String> { /// (O_NOFOLLOW|CLOEXEC, so a symlink at the path is rejected at open): /// must be a regular file, owned by root, with no group/other write /// bits. Same fd-based discipline as the keys-file checks — nothing is -/// ever re-resolved by path (audit 2026-08-02 O2). +/// ever re-resolved by path. #[cfg(not(target_os = "macos"))] fn verify_id_candidate(path: &str) -> Result<(), String> { let fd = rustix::fs::open( @@ -373,12 +372,10 @@ pub fn keys_path(source: &KeysSource) -> Result { /// RAII guard that sets the process umask so a bound unix socket is born /// with `mode` (sockets are created `0777 & ~umask`) and restores the /// prior mask on drop. Darwin-only: Linux fchmod()s the already-bound -/// socket fd (audit finding #7), which Darwin cannot do — fchmod(2) -/// rejects socket fds with EINVAL (found by the T2 end-to-end -/// conformance test, sweep 2026-08-07) — and a path chmod would reopen -/// the #7 TOCTOU (a swapped-in symlink redirecting the chmod to an -/// attacker-chosen file). Being born with the right mode has no window -/// at all. +/// socket fd, which Darwin cannot do — fchmod(2) rejects socket fds +/// with EINVAL — and a path chmod would reopen the same TOCTOU (a +/// swapped-in symlink redirecting the chmod to an attacker-chosen +/// file). Being born with the right mode has no window at all. #[cfg(target_os = "macos")] #[derive(Debug)] struct UmaskGuard(libc::mode_t); @@ -408,7 +405,7 @@ impl Drop for UmaskGuard { /// Bind and listen on all configured credential sockets. Returns /// a vector of `(UnixListener, path)` pairs ready for serving (the entry -/// is re-looked-up by the caller; sweep 2026-08-07 D9). +/// is re-looked-up by the caller). pub fn acquire_listeners( cfg: &Config, bind: bool, @@ -559,9 +556,9 @@ pub fn acquire_listeners( } } -/// Enforce the absoluteness the config type docs promise (sweep 2026-08-07 -/// D14): a CWD-relative socket or keys path would resolve against whatever -/// directory the daemon happened to start in. +/// Enforce the absoluteness the config type docs promise: a CWD-relative +/// socket or keys path would resolve against whatever directory the +/// daemon happened to start in. fn validate_absolute_paths(cfg: &Config) -> Result<(), String> { for path in cfg.credentials.keys() { if !path.is_absolute() { @@ -584,8 +581,8 @@ fn validate_absolute_paths(cfg: &Config) -> Result<(), String> { /// Preflight: prove every credential is servable — and every peer_user /// resolvable — before accepting anyone. An empty resolved value is -/// unservable (zero bytes means refusal on the wire, sweep 2026-08-07 -/// D4), so it fails here at startup naming the key rather than leaving +/// unservable (zero bytes means refusal on the wire), so it fails here +/// at startup naming the key rather than leaving /// the daemon looking healthy while the credential permanently fails /// with a misdiagnosing message. fn preflight_credentials( @@ -615,9 +612,9 @@ fn preflight_credentials( Ok(peer_uids) } -/// Run the credential daemon: harden the process, load keys, bind -/// sockets, and serve credential requests. Runs until the process is -/// terminated; returns only on startup-path failure (sweep 2026-08-07 D10). +/// Load keys, bind sockets, and serve credential requests. +/// The caller applies process hardening before calling. Runs until the process is +/// terminated; returns only on startup-path failure. pub fn run(args: &Args) -> Result<(), String> { let file = fs::File::open(&args.config).map_err(|e| format!("{}: {e}", args.config.display()))?; diff --git a/src/test_util.rs b/src/test_util.rs index c07c015..7823a91 100644 --- a/src/test_util.rs +++ b/src/test_util.rs @@ -1,5 +1,7 @@ //! Test-only shared utilities (compiled under `#[cfg(test)]` only). +pub(crate) mod aad_fixture; + /// Process-wide lock serializing every unit test that mutates — or /// wholesale snapshots — the process-global environment. The test /// harness runs tests in parallel threads of one process, so @@ -10,6 +12,5 @@ /// ALL env-touching tests in every module hold this ONE lock for the /// mutation's full scope. Module-local locks do not exclude each other: /// separate per-module statics raced, and the loser's panic poisoned a -/// mutex, failing unrelated tests (~1 in 5 baseline runs, observed -/// 2026-08-04). +/// mutex, failing unrelated tests (~1 in 5 baseline runs). pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); diff --git a/src/test_util/aad_fixture.rs b/src/test_util/aad_fixture.rs new file mode 100644 index 0000000..34c1121 --- /dev/null +++ b/src/test_util/aad_fixture.rs @@ -0,0 +1,26 @@ +//! Test-only AAD envelope construction, independent of the production decoder. +#![allow(clippy::unwrap_used)] + +use aes_gcm::aead::{AeadInOut, KeyInit, Nonce}; +use aes_gcm::{AesGcm, aes::Aes256, aes::cipher::consts::U16}; +use zeroize::Zeroizing; + +/// Encrypt a test value with a fresh ephemeral key and the supplied AAD. +pub fn encrypt(public: &[u8], plaintext: &[u8], aad: &[u8]) -> Vec { + type Cipher = AesGcm; + let public = ecies::PublicKey::parse_slice(public, None).unwrap(); + let (secret, ephemeral) = ecies::utils::generate_keypair(); + let key = Zeroizing::new(ecies::utils::encapsulate(&secret, &public, false).unwrap()); + let cipher = Cipher::new_from_slice(&key[..]).unwrap(); + // Each fixture uses a fresh derived AES key, so this nonce is never reused with a key. + let nonce = Nonce::::default(); + let mut ciphertext = plaintext.to_vec(); + let tag = cipher + .encrypt_inout_detached(&nonce, aad, ciphertext.as_mut_slice().into()) + .unwrap(); + let mut envelope = ephemeral.serialize().to_vec(); + envelope.extend_from_slice(&nonce); + envelope.extend_from_slice(&tag); + envelope.extend_from_slice(&ciphertext); + envelope +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index e65a133..ef85a58 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -4,6 +4,9 @@ //! fixture verification (README); these helpers guard OUR semantics. #![allow(dead_code, clippy::unwrap_used, clippy::panic, missing_docs)] +#[path = "../../src/test_util/aad_fixture.rs"] +pub mod aad_fixture; + use std::fs; use std::path::{Path, PathBuf}; diff --git a/tests/exec_conformance/bundle.rs b/tests/exec_conformance/bundle.rs index a5c64bf..9436491 100644 --- a/tests/exec_conformance/bundle.rs +++ b/tests/exec_conformance/bundle.rs @@ -15,7 +15,7 @@ use crate::{run_exec, write_config}; /// exactly as the bundle adapter's suite requires. fn enc_entry(name: &str, value: &str) -> String { let pk = hex::decode(common::test_pk_hex()).unwrap(); - let ct = ecies::encrypt_with_aad(&pk, value.as_bytes(), name.as_bytes()).unwrap(); + let ct = common::aad_fixture::encrypt(&pk, value.as_bytes(), name.as_bytes()); BASE64.encode(ct) } @@ -91,6 +91,125 @@ fn bundle_exec_loads_postmaster_key_through_load_ring() { ); } +#[test] +fn exec_private_key_variables_are_not_inherited() { + let d = common::tmpdir("private-key-env"); + let env = common::write_env_file( + &d, + ".env", + &[ + format!("PLAIN=\"{}\"", common::enc("from-env")), + format!( + "POSTMASTER_KEY_STAGING=\"{}\"", + common::enc("reserved-output") + ), + ], + ); + let bundle = write_bundle(&d, &[("SECRET", "from-bundle")]); + let keys = write_keys(&d, true); + for (mode, file_source) in [ + ("env", false), + ("env", true), + ("files", false), + ("files", true), + ("credentials", false), + ] { + let secrets = d.join(format!("{mode}-{file_source}")); + std::fs::create_dir(&secrets).unwrap(); + let mut config = serde_json::json!({"mode": mode}); + if mode == "credentials" { + std::fs::write(secrets.join("SECRET"), "from-bundle").unwrap(); + config["credential_keys"] = serde_json::json!(["SECRET"]); + } else { + config["keys"] = if file_source { + serde_json::json!([{"file": keys}]) + } else { + serde_json::json!(["environment"]) + }; + config["env_files"] = serde_json::json!([env]); + config["bundle_files"] = serde_json::json!([bundle]); + config["overload"] = serde_json::json!(true); + if mode == "files" { + config["secrets_dir"] = serde_json::json!(secrets); + } + } + let cfg = write_config(&d, &config.to_string()); + let sh = r#" + [ "${DOTENV_PRIVATE_KEY+x}${DOTENV_PRIVATE_KEY_PRODUCTION+x}${POSTMASTER_KEY+x}${POSTMASTER_KEY_PRODUCTION+x}${POSTMASTER_KEY_STAGING+x}${POSTMASTER_KEY_STAGING_FILE+x}" = "" ] || { + echo 'private key variable reached the application' >&2; exit 42; + } + [ "$DOTENV_PRIVATE_KEYFOO" = keep-dotenv ] && + [ "$POSTMASTER_KEYFOO" = keep-bundle ] && + [ "$HOME" = /postmaster-test-home ] && [ "$PATH" = /usr/bin:/bin ] || exit 43 + if [ -n "${SECRET_FILE:-}" ]; then + [ "$(cat "$SECRET_FILE")" = from-bundle ] || exit 44 + if [ -n "${PLAIN_FILE:-}" ]; then + [ "$(cat "$PLAIN_FILE")" = from-env ] || exit 45 + fi + else + [ "$SECRET" = from-bundle ] && [ "$PLAIN" = from-env ] || exit 46 + fi + "#; + let out = run_exec( + &cfg, + sh, + &[ + ("DOTENV_PRIVATE_KEY", common::TEST_SK_HEX), + ("DOTENV_PRIVATE_KEY_PRODUCTION", common::TEST_SK_HEX), + ("POSTMASTER_KEY", common::TEST_SK_HEX), + ("POSTMASTER_KEY_PRODUCTION", common::TEST_SK_HEX), + ("DOTENV_PRIVATE_KEYFOO", "keep-dotenv"), + ("POSTMASTER_KEYFOO", "keep-bundle"), + ("HOME", "/postmaster-test-home"), + ("PATH", "/usr/bin:/bin"), + ("CREDENTIALS_DIRECTORY", secrets.to_str().unwrap()), + ], + ); + assert!( + out.status.success(), + "mode:{mode}, file_source:{file_source}, stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + } +} + +#[test] +fn bundle_private_key_entry_names_fail_before_launch() { + let d = common::tmpdir("reserved-bundle-keys"); + let keys = write_keys(&d, false); + for name in [ + "DOTENV_PRIVATE_KEY", + "DOTENV_PRIVATE_KEY_PRODUCTION", + "POSTMASTER_KEY", + "POSTMASTER_KEY_PRODUCTION", + ] { + let bundle = write_bundle(&d, &[(name, "reserved-output")]); + let cfg = write_config( + &d, + &serde_json::json!({ + "mode": "env", + "keys": [{"file": keys}], + "bundle_files": [bundle], + "strict": false, + "overload": true, + }) + .to_string(), + ); + let marker = d.join("started"); + let out = run_exec(&cfg, &format!("echo started > '{}'", marker.display()), &[]); + assert!(!out.status.success(), "reserved entry {name} was accepted"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains(name) && stderr.contains("reserved"), + "{stderr}" + ); + assert!( + !marker.exists(), + "reserved entry {name} started the command" + ); + } +} + #[test] fn mixed_env_and_bundle_exec_resolves_both_adapters() { // A config with both env_files and bundle_files requires BOTH @@ -191,6 +310,86 @@ fn bundle_env_precedence_matches_env_adapter() { assert_eq!(std::fs::read(d.join("out2")).unwrap(), b"from-bundle"); } +#[test] +fn bundle_files_follow_first_or_last_wins_precedence() { + let d = common::tmpdir("bundle-file-precedence"); + let first_dir = d.join("first"); + let last_dir = d.join("last"); + std::fs::create_dir(&first_dir).unwrap(); + std::fs::create_dir(&last_dir).unwrap(); + let first = write_bundle(&first_dir, &[("SECRET", "first-bundle"), ("FIRST", "one")]); + let last = write_bundle(&last_dir, &[("SECRET", "last-bundle"), ("LAST", "two")]); + let env = common::write_env_file(&d, ".env", &[format!("SECRET={}", common::enc("from-env"))]); + let keys = write_keys(&d, true); + for mode in ["env", "files"] { + for include_env in [false, true] { + for overload in [false, true] { + let mut config = serde_json::json!({ + "mode": mode, + "keys": [{"file": keys}], + "bundle_files": [first, last], + "overload": overload, + }); + if include_env { + config["env_files"] = serde_json::json!([env]); + } + if mode == "files" { + let dir = d.join(format!("files-{include_env}-{overload}")); + std::fs::create_dir(&dir).unwrap(); + config["secrets_dir"] = serde_json::json!(dir); + } + let cfg = write_config(&d, &config.to_string()); + let sh = if mode == "files" { + "cat \"$SECRET_FILE\"; printf '|'; cat \"$FIRST_FILE\"; printf '|'; cat \"$LAST_FILE\"" + } else { + "printf '%s|%s|%s' \"$SECRET\" \"$FIRST\" \"$LAST\"" + }; + let out = run_exec(&cfg, sh, &[]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let expected = if overload { + "last-bundle|one|two" + } else if include_env { + "from-env|one|two" + } else { + "first-bundle|one|two" + }; + assert_eq!( + out.stdout, + expected.as_bytes(), + "mode:{mode}, include_env:{include_env}, overload:{overload}" + ); + } + } + } +} + +#[test] +fn bundle_shadowed_nul_value_still_fails_closed() { + let d = common::tmpdir("bundle-shadowed-nul"); + let first_dir = d.join("first"); + std::fs::create_dir(&first_dir).unwrap(); + let first = write_bundle(&first_dir, &[("SECRET", "valid")]); + let last = write_bundle(&d, &[("SECRET", "invalid\0value")]); + let keys = write_keys(&d, false); + let cfg = write_config( + &d, + &serde_json::json!({ + "mode": "env", + "keys": [{"file": keys}], + "bundle_files": [first, last], + "strict": false, + }) + .to_string(), + ); + let out = run_exec(&cfg, "true", &[]); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("NUL byte")); +} + #[test] fn bundle_nul_value_is_a_hard_error_under_any_strictness() { // sweep 2026-08-07 T10 (X6): an env-bound bundle value containing NUL diff --git a/tests/exec_conformance/main.rs b/tests/exec_conformance/main.rs index f1c10e1..dfd14cf 100644 --- a/tests/exec_conformance/main.rs +++ b/tests/exec_conformance/main.rs @@ -80,6 +80,8 @@ fn run_exec(config: &Path, sh: &str, envs: &[(&str, &str)]) -> std::process::Out // (sweep 2026-08-07 T8). .env_remove("SECRET") .env_remove("PLAIN") + .env_remove("FIRST") + .env_remove("LAST") .env_remove("A") .env_remove("GOOD") .env_remove("BAD") From 31a3d86f204ff91b5a6810794120b16ae9e2c0c0 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Sat, 7 Nov 2026 23:56:31 -0600 Subject: [PATCH 34/47] fix: retain verified RAM-disk handles during launch Bind RAM-backing and ownership checks to the directory used for pruning, writes and cleanup. Preserve valid internal symlinks and recognize mounted and partitioned hdiutil device rows. Use a portable temporary-file template for the verified Nix installer. Add focused regressions and align the launcher contract and threat model. --- .github/actions/setup-nix/action.yml | 2 +- CHANGELOG.md | 6 +- docs/src/architecture/threat-model.md | 17 +- docs/src/reference/launcher-contract.md | 13 +- src/launcher.rs | 52 ++---- src/ramdisk.rs | 220 +++++++++++++++++++----- src/secret_files.rs | 22 ++- tests/exec_conformance/files_mode.rs | 5 +- 8 files changed, 235 insertions(+), 102 deletions(-) diff --git a/.github/actions/setup-nix/action.yml b/.github/actions/setup-nix/action.yml index 8641457..d8aefa3 100644 --- a/.github/actions/setup-nix/action.yml +++ b/.github/actions/setup-nix/action.yml @@ -29,7 +29,7 @@ runs: echo "nix already available: $(command -v nix) -> $(nix --version)" else url="https://releases.nixos.org/nix/nix-${NIX_VERSION}/install" - tmp="$(mktemp -t nix-install)" + tmp="$(mktemp "${TMPDIR:-/tmp}/nix-install.XXXXXX")" # Verify the pinned digest BEFORE executing: a substituted or # corrupted installer fails closed here, never runs. curl -sSfL "$url" -o "$tmp" diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d5bf0d..335b427 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,12 +43,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 closed); daemon refuses a symlinked socket parent and non-absolute config paths, and rejects empty credentials at preflight; `--allow-nonroot` no longer overrides a configured `peer_user` ACL; - ramdisk verification enforces lexical path containment; NUL in an + ramdisk verification checks lexical containment and the pinned directory's + backing device, retaining that handle for pruning and plaintext I/O; NUL in an env-bound bundle value is a hard error under any strictness (one rule for every env-bound value). ### Changed +- Nix installer temporary-file creation works with GNU and macOS `mktemp`. +- RAM-disk verification recognizes mounted and partitioned device rows in + `hdiutil info` while keeping each device tied to its own image. - Build matrix preserves compiler flags and profile environment overrides, uses `cargo zigbuild` for cross builds, and remaps source paths at `max`. Help describes the configured release profile without performance estimates. diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index 23aebfb..d965745 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -178,8 +178,8 @@ always abort, regardless of `strict`. ### Symlink attacks on key files and secret paths -Postmaster rejects symlinks at every point where secret material is -read or written: +Postmaster rejects final-component symlinks and checks pinned descriptors +where secret material is read or written: - **Key files** are opened with `O_NOFOLLOW` — a symlinked `.env.keys` file is rejected at the kernel level. The file descriptor is then @@ -194,9 +194,11 @@ read or written: the fd level. - **Secret files** are written with `O_NOFOLLOW | O_CREAT | O_TRUNC` — a symlink planted at the target path is rejected, not followed. -- **Secrets directory** is checked with `symlink_metadata` even on - Linux where `verify_ramdisk` is not used, rejecting a symlinked - `secrets_dir` that could redirect plaintext to persistent disk. +- **Secrets directory** is opened with `O_DIRECTORY | O_NOFOLLOW`, + rejecting a final-component symlink. With `verify_ramdisk`, the opened + inode must also belong to the verified RAM device and service user. + This checks intermediate-symlink targets as well. The launcher retains + that handle for pruning, writes, cleanup, and monitoring. - **Socket permissions** use `fchmod` on the socket fd on Linux. macOS rejects that operation, so Postmaster sets the umask before binding there and restores it afterward. @@ -535,6 +537,11 @@ Fails closed if the device isn't found or isn't RAM-backed, preventing plaintext from being written to a file-backed HFS image masquerading as the ramdisk. +The opened secrets directory's device ID must match that RAM device, +not just a lexical path prefix. Verification, pruning, writes, and cleanup +use the same pinned directory handle, so replacing a path after verification +cannot redirect those operations onto persistent storage. + ### fd closure before execvp — Mitigated `OFlags::CLOEXEC` is set on every file descriptor postmaster opens (all diff --git a/docs/src/reference/launcher-contract.md b/docs/src/reference/launcher-contract.md index 439f158..8eaa86a 100644 --- a/docs/src/reference/launcher-contract.md +++ b/docs/src/reference/launcher-contract.md @@ -145,7 +145,7 @@ Every field except `mode` has a default, so a minimal config is just | `passthrough` | array of strings | `[]` | `files` mode only: these keys are *also* exported as real env vars, in addition to their `_FILE` pointer. | | `credential_keys` | array of strings | `[]` | `credentials` mode: keys to expose as `$CREDENTIALS_DIRECTORY/`. Required (non-empty) for that mode. | | `sockets` | map of key → socket path | `{}` | `credentials` mode: postmaster socket to fetch `` from. Non-empty selects the darwin/launchd fetch path; empty means systemd already materialized the credentials via `LoadCredential=`. | -| `verify_ramdisk` | path or `null` | `null` | darwin only: refuse to write plaintext unless this mount point is the HFS ramdisk and `secrets_dir` is a directory owned by the current euid. | +| `verify_ramdisk` | path or `null` | `null` | darwin only: require a RAM-backed HFS mount and a service-owned `secrets_dir` on that device. The verified directory handle is retained for plaintext I/O. | Note the field name is `verify_ramdisk`, not `ramdisk` or `ramdisk_mount` — match it exactly. @@ -391,11 +391,12 @@ this mode — it dispatches on whether `sockets` is empty: `/sbin/mount` and requires the configured mount point to appear as an `hfs` filesystem, then runs `hdiutil info` and requires the device's `image-path` to start with `ram://` (confirming RAM backing, not a - file-backed image). It then `stat`s `secrets_dir` and requires it to - exist, be a directory, and be owned by the launcher's own effective - uid. Either check failing refuses to write plaintext to what might be - persistent disk, with an error pointing at `postmaster-ramdisk` - health. + file-backed image). It opens `secrets_dir` without following a + final-component symlink and checks the pinned inode's ownership and + backing device. The directory must be lexically beneath the mount point + and use the verified RAM device, so an intermediate symlink cannot + redirect plaintext onto persistent storage. Pruning, writes, cleanup, + and the monitor retain that same directory handle. ## Extensibility boundary diff --git a/src/launcher.rs b/src/launcher.rs index 2652da0..beb1f5e 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -19,9 +19,9 @@ use crate::exec_config::{ExecConfig, ExecMode}; use crate::key_source::load_ring; use crate::keys::{is_private_key_var_name, resolve_all}; use crate::monitor::{self, STOP_SIGNALS}; -use crate::ramdisk::verify_ramdisk; +use crate::ramdisk::open_verified_ramdisk_dir; use crate::secret_files::{ - Resolved, cleanup_written, env_pairs, open_secrets_dir, prune_stale, write_secret_file, + Resolved, cleanup_written, env_pairs, open_secrets_dir, prune_stale_at, write_secret_file, }; use crate::server::{fetch_bytes, log, read_capped}; @@ -335,37 +335,19 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() .secrets_dir .as_deref() .ok_or("files mode requires secrets_dir")?; - match &cfg.verify_ramdisk { - Some(mp) => verify_ramdisk(mp, dir)?, - None => { - // Defense-in-depth: use symlink_metadata to reject a - // symlinked secrets_dir even on Linux where - // verify_ramdisk is not used. - let md = - fs::symlink_metadata(dir).map_err(|e| format!("{}: {e}", dir.display()))?; - if md.file_type().is_symlink() { - return Err(format!( - "{}: secrets_dir is a symlink; refusing to write plaintext through a symlink", - dir.display() - )); - } - if !md.is_dir() { - return Err(format!("{}: not a directory", dir.display())); - } - } - } + let dir_fd = match &cfg.verify_ramdisk { + Some(mp) => open_verified_ramdisk_dir(mp, dir)?, + None => open_secrets_dir(dir).map_err(|e| { + format!("{}: {e} (refusing to follow a symlink)", dir.display()) + })?, + }; let (resolved, failed) = decrypt(&cfg)?; if verify_keys { verify_key_freshness(&failed)?; } // Prune stale secret files from a prior launch before writing new ones. let keep_keys: Vec = resolved.iter().map(|(k, _)| k.clone()).collect(); - prune_stale(dir, &keep_keys)?; - // Pin the secrets dir for the whole write window: the writes, - // the mid-loop cleanups, and the post-match cleanups all act - // relative to this one pinned fd. - let dir_fd = open_secrets_dir(dir) - .map_err(|e| format!("{}: {e} (refusing to follow a symlink)", dir.display()))?; + prune_stale_at(&dir_fd, dir, &keep_keys)?; written.reserve(resolved.len()); for (k, v) in &resolved { let path = match write_secret_file(&dir_fd, dir, k, v) { @@ -414,17 +396,15 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() .secrets_dir .as_deref() .ok_or("credentials(fetch) mode requires secrets_dir")?; - if let Some(mp) = &cfg.verify_ramdisk { - verify_ramdisk(mp, dir)?; - } + let dir_fd = match &cfg.verify_ramdisk { + Some(mp) => open_verified_ramdisk_dir(mp, dir)?, + None => open_secrets_dir(dir).map_err(|e| { + format!("{}: {e} (refusing to follow a symlink)", dir.display()) + })?, + }; let sockets: &HashMap = &cfg.sockets; // Prune stale credential files from a prior launch. - prune_stale(dir, &cfg.credential_keys)?; - // Pin the secrets dir for the whole fetch/write window - // (same single-fd discipline as files mode). - let dir_fd = open_secrets_dir(dir).map_err(|e| { - format!("{}: {e} (refusing to follow a symlink)", dir.display()) - })?; + prune_stale_at(&dir_fd, dir, &cfg.credential_keys)?; written.reserve(cfg.credential_keys.len()); for k in &cfg.credential_keys { let sock = sockets diff --git a/src/ramdisk.rs b/src/ramdisk.rs index ad6cc13..5e0eabd 100644 --- a/src/ramdisk.rs +++ b/src/ramdisk.rs @@ -1,13 +1,14 @@ //! macOS ramdisk verification — ensures plaintext secret files land only //! beneath a verified RAM-backed HFS mount: the mount proves RAM-backed -//! via hdiutil, and `secrets_dir` must be contained in it, real (not a -//! symlink), and owned by the service user. +//! via hdiutil, and the pinned `secrets_dir` must use that device and be +//! owned by the service user. The final component cannot be a symlink. //! //! The launcher uses this check when `verify_ramdisk` is configured on macOS. //! Linux integrations provide and secure their own RAM-backed storage. use std::fs; -use std::os::unix::fs::MetadataExt; +use std::os::fd::OwnedFd; +use std::os::unix::fs::{FileTypeExt, MetadataExt}; use std::path::Path; /// Pure parser for /sbin/mount output: is `mp` mounted as HFS? @@ -46,29 +47,26 @@ fn device_is_ram_backed(device: &str, hdiutil_out: &str) -> bool { // image-path : ram://1024 // image-type : read/write // ... - // /dev/disk8 + // /dev/disk8 /Volumes/Postmaster // - // The device appears as a line by itself after the image properties. - // We find the device line, then scan backwards for the image-path - // field in the same image entry. + // Device rows can include partition types and mount paths. Match the + // first token, then find image-path within the same image entry. let lines: Vec<&str> = hdiutil_out.lines().collect(); let device_line = device.trim(); for (idx, line) in lines.iter().enumerate() { - if line.trim() == device_line { + if line.split_whitespace().next() == Some(device_line) { // Scan backwards from the device line to find image-path for prev in lines[..idx].iter().rev() { let trimmed = prev.trim(); - if trimmed.starts_with("image-path") { - // Extract the value after "image-path : " - if let Some(colon_idx) = trimmed.find(':') { - let value = trimmed[colon_idx + 1..].trim(); - return value.starts_with("ram://"); - } + if let Some((name, value)) = trimmed.split_once(':') + && name.trim() == "image-path" + { + return value.trim().starts_with("ram://"); } - // If we hit another device line or a separator, this - // image entry's properties ended — stop scanning. - if trimmed.starts_with("/dev/") || trimmed.starts_with("====") { + // Partition rows share image properties; only the image + // separator ends the search. + if trimmed.starts_with("====") { break; } } @@ -79,9 +77,8 @@ fn device_is_ram_backed(device: &str, hdiutil_out: &str) -> bool { } /// True when `dir` names a path lexically beneath `mount_point` -/// (component-wise, with no `..` escape). Lexical only — the caller has -/// already proven `dir` a real, non-symlink directory and `mount_point` -/// present in mount output. +/// (component-wise, with no `..` escape). This lexical filter must be paired +/// with a backing-device check on the opened directory. fn path_beneath(dir: &Path, mount_point: &Path) -> bool { match dir.strip_prefix(mount_point) { Ok(rest) => !rest @@ -92,7 +89,18 @@ fn path_beneath(dir: &Path, mount_point: &Path) -> bool { } /// Verify a macOS RAM-backed mount and a contained directory owned by this user. +/// +/// This verification-only API does not retain the directory handle. The +/// launcher uses `open_verified_ramdisk_dir` to keep the verified inode pinned. pub fn verify_ramdisk(mount_point: &Path, secrets_dir: &Path) -> Result<(), String> { + open_verified_ramdisk_dir(mount_point, secrets_dir).map(drop) +} + +/// Verify the RAM backing and return the pinned directory for plaintext I/O. +pub(crate) fn open_verified_ramdisk_dir( + mount_point: &Path, + secrets_dir: &Path, +) -> Result { // Trust boundary (audit 2026-08-02 O2): a compromised /sbin/mount or // hdiutil could report persistent disk as the RAM-backed postmaster // ramdisk and let plaintext land on persistent storage. Verify both @@ -129,43 +137,56 @@ pub fn verify_ramdisk(mount_point: &Path, secrets_dir: &Path) -> Result<(), Stri mount_point.display() )); } - // Use symlink_metadata instead of metadata: if secrets_dir is itself a - // symlink to persistent disk (planted by a prior compromised launch on - // the darwin ramdisk, which persists across restarts), fs::metadata would - // follow the link and inspect the TARGET — a directory owned by the - // service user on persistent disk — and approve it. Reject symlinks - // outright so the ramdisk invariant is not bypassed. - let md = fs::symlink_metadata(secrets_dir).map_err(|e| { + let device_md = fs::metadata(&device).map_err(|e| format!("{device}: {e}"))?; + if !device_md.file_type().is_block_device() { + return Err(format!( + "{device}: ramdisk backing device is not a block device" + )); + } + open_verified_dir(mount_point, secrets_dir, device_md.rdev()) +} + +/// Pin a contained, service-owned directory on the expected backing device. +fn open_verified_dir( + mount_point: &Path, + secrets_dir: &Path, + device: u64, +) -> Result { + if !path_beneath(secrets_dir, mount_point) { + return Err(format!( + "{}: secrets_dir is not beneath the verified ramdisk mount {}; refusing to write plaintext outside the ramdisk", + secrets_dir.display(), + mount_point.display() + )); + } + let fd = crate::secret_files::open_secrets_dir(secrets_dir).map_err(|e| { format!( - "{}: {e} (is postmaster-ramdisk healthy?)", + "{}: {e} (refusing a symlinked or non-directory secrets_dir)", secrets_dir.display() ) })?; - if md.file_type().is_symlink() { - return Err(format!( - "{}: secrets_dir is a symlink; refusing to follow — remove the symlink and ensure the directory is on the ramdisk", + let dir = fs::File::from(fd); + let md = dir.metadata().map_err(|e| { + format!( + "{}: {e} (is postmaster-ramdisk healthy?)", secrets_dir.display() - )); - } + ) + })?; if !md.is_dir() || md.uid() != rustix::process::geteuid().as_raw() { return Err(format!( "{}: missing or not owned by this service user (is postmaster-ramdisk healthy?)", secrets_dir.display() )); } - // Containment (sweep 2026-08-07 X1): the checks above prove the mount - // is the RAM-backed postmaster ramdisk and, independently, that - // secrets_dir is a real euid-owned directory — nothing so far related - // the two. A hand-written config pointing secrets_dir at persistent - // disk would pass both and land plaintext off the ramdisk. - if !path_beneath(secrets_dir, mount_point) { + // O_NOFOLLOW covers only the final component; an ancestor can redirect + // the open. Check the pinned inode, then retain it for every plaintext I/O. + if md.dev() != device { return Err(format!( - "{}: secrets_dir is not beneath the verified ramdisk mount {}; refusing to write plaintext outside the ramdisk", - secrets_dir.display(), - mount_point.display() + "{}: secrets_dir is not on the verified ramdisk device; refusing to write plaintext outside the ramdisk", + secrets_dir.display() )); } - Ok(()) + Ok(dir.into()) } #[cfg(test)] @@ -230,6 +251,40 @@ image-type : read/write assert!(!device_is_ram_backed("/dev/disk99", hdiutil)); } + #[test] + fn device_is_ram_backed_accepts_mounted_device_columns() { + let output = "================================================\n\ + image-path : ram://32768\n\ + /dev/disk5\t\t/Volumes/Postmaster Test\n"; + assert!(device_is_ram_backed("/dev/disk5", output)); + assert!(!device_is_ram_backed("/dev/disk", output)); + assert!(!device_is_ram_backed("/dev/disk50", output)); + } + + #[test] + fn device_is_ram_backed_keeps_partition_rows_in_their_image() { + let output = "================================================\n\ + image-path : ram://32768\n\ + /dev/disk8\tGUID_partition_scheme\n\ + /dev/disk8s1\tApple_HFS\t/Volumes/RAM\n\ + =================================================\n\ + image-path : /tmp/file-backed.dmg\n\ + /dev/disk9\tGUID_partition_scheme\n\ + /dev/disk9s1\tApple_HFS\t/Volumes/File Image\n\ + =================================================\n\ + image-path-other: ram://32768\n\ + /dev/disk10\t\t/Volumes/Unknown\n"; + for (device, expected) in [ + ("/dev/disk8", true), + ("/dev/disk8s1", true), + ("/dev/disk9", false), + ("/dev/disk9s1", false), + ("/dev/disk10", false), + ] { + assert_eq!(device_is_ram_backed(device, output), expected, "{device}"); + } + } + #[test] fn path_beneath_enforces_containment() { // sweep 2026-08-07 X1: the guard must relate secrets_dir to the @@ -253,4 +308,83 @@ image-type : read/write mp )); } + + fn test_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!( + "pm-ramdisk-{tag}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn verified_dir_rejects_an_intermediate_link_to_another_device() { + let root = test_dir("ancestor-link"); + let mount = root.join("mount"); + let outside = root.join("outside"); + fs::create_dir(&mount).unwrap(); + fs::create_dir_all(outside.join("service")).unwrap(); + std::os::unix::fs::symlink(&outside, mount.join("link")).unwrap(); + let candidate = mount.join("link/service"); + assert!(path_beneath(&candidate, &mount)); + assert!(fs::symlink_metadata(&candidate).unwrap().is_dir()); + // /dev is a distinct filesystem on supported Linux/macOS hosts. + let expected_device = fs::metadata("/dev").unwrap().dev(); + assert_ne!(expected_device, fs::metadata(&candidate).unwrap().dev()); + + let err = open_verified_dir(&mount, &candidate, expected_device).unwrap_err(); + + assert!(err.contains("not on the verified ramdisk device"), "{err}"); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn verified_dir_allows_internal_links_but_rejects_a_final_symlink() { + let root = test_dir("internal-link"); + let service = root.join("nested/service"); + fs::create_dir_all(&service).unwrap(); + std::os::unix::fs::symlink(root.join("nested"), root.join("link")).unwrap(); + let device = fs::metadata(&root).unwrap().dev(); + let fd = open_verified_dir(&root, &root.join("link/service"), device).unwrap(); + assert_eq!( + fs::File::from(fd).metadata().unwrap().ino(), + fs::metadata(&service).unwrap().ino() + ); + std::os::unix::fs::symlink(&service, root.join("final")).unwrap(); + let err = open_verified_dir(&root, &root.join("final"), device).unwrap_err(); + assert!(err.contains("symlinked"), "{err}"); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn verified_handle_pins_prune_write_and_cleanup_across_path_replacement() { + use crate::secret_files::{cleanup_written, prune_stale_at, write_secret_file}; + + let root = test_dir("path-replacement"); + let service = root.join("service"); + let original = root.join("original"); + let outside = root.join("outside"); + fs::create_dir(&service).unwrap(); + fs::create_dir(&outside).unwrap(); + let device = fs::metadata(&root).unwrap().dev(); + let fd = open_verified_dir(&root, &service, device).unwrap(); + write_secret_file(&fd, &service, "OLD", b"stale").unwrap(); + fs::write(outside.join("OLD"), b"foreign-old").unwrap(); + fs::write(outside.join("SECRET"), b"foreign-secret").unwrap(); + fs::rename(&service, &original).unwrap(); + std::os::unix::fs::symlink(&outside, &service).unwrap(); + + prune_stale_at(&fd, &service, &[]).unwrap(); + assert!(!original.join("OLD").exists()); + assert_eq!(fs::read(outside.join("OLD")).unwrap(), b"foreign-old"); + write_secret_file(&fd, &service, "SECRET", b"test-secret").unwrap(); + assert_eq!(fs::read(original.join("SECRET")).unwrap(), b"test-secret"); + cleanup_written(&fd, &["SECRET".into()]); + assert!(!original.join("SECRET").exists()); + assert_eq!(fs::read(outside.join("SECRET")).unwrap(), b"foreign-secret"); + fs::remove_dir_all(root).unwrap(); + } } diff --git a/src/secret_files.rs b/src/secret_files.rs index c49e816..42f74aa 100644 --- a/src/secret_files.rs +++ b/src/secret_files.rs @@ -43,7 +43,7 @@ pub fn env_pairs(resolved: &Resolved) -> Result, Strin } /// Open and pin a secrets directory by fd: `O_RDONLY|O_DIRECTORY| -/// O_NOFOLLOW|O_CLOEXEC` rejects a symlink or non-directory at open and +/// O_NOFOLLOW|O_CLOEXEC` rejects a final-component symlink or non-directory and /// pins the inode, so subsequent `*at` operations are relative to it /// rather than to a re-resolved path. pub(crate) fn open_secrets_dir(dir: &Path) -> rustix::io::Result { @@ -171,7 +171,6 @@ pub fn cleanup_written(dir_fd: impl AsFd, names: &[String]) { /// plaintext is transient — is best served by cleaning what we can rather /// than aborting the launch over an unrelated stale file. pub fn prune_stale(dir: &Path, keep_keys: &[String]) -> Result<(), String> { - let keep: std::collections::HashSet<&str> = keep_keys.iter().map(String::as_str).collect(); // Pin the directory by fd: O_DIRECTORY|O_NOFOLLOW rejects a symlinked // or non-directory secrets dir at open, and the sentinel check, the // per-entry stat, and every unlink below are all relative to the @@ -188,7 +187,18 @@ pub fn prune_stale(dir: &Path, keep_keys: &[String]) -> Result<(), String> { } Err(e) => return Err(format!("{}: prune: {e}", dir.display())), }; - let names = read_dir_names(&dir_fd).map_err(|e| format!("{}: prune: {e}", dir.display()))?; + prune_stale_at(&dir_fd, dir, keep_keys) +} + +/// Prune through the same pinned directory used for verification and writes. +pub(crate) fn prune_stale_at( + dir_fd: impl AsFd, + dir: &Path, + keep_keys: &[String], +) -> Result<(), String> { + let dir_fd = dir_fd.as_fd(); + let keep: std::collections::HashSet<&str> = keep_keys.iter().map(String::as_str).collect(); + let names = read_dir_names(dir_fd).map_err(|e| format!("{}: prune: {e}", dir.display()))?; // An empty directory is trivially safe (first launch). if names.is_empty() { return Ok(()); @@ -197,7 +207,7 @@ pub fn prune_stale(dir: &Path, keep_keys: &[String]) -> Result<(), String> { // sentinel means postmaster never wrote here — bulk deletes could // hit foreign files. Refuse. match rustix::fs::statat( - &dir_fd, + dir_fd, MANAGED_SENTINEL, rustix::fs::AtFlags::SYMLINK_NOFOLLOW, ) { @@ -228,9 +238,9 @@ pub fn prune_stale(dir: &Path, keep_keys: &[String]) -> Result<(), String> { // the stat (SYMLINK_NOFOLLOW) and the unlink are relative to the // pinned dir fd, so a swapped entry cannot redirect either one. let path = dir.join(name); - match rustix::fs::statat(&dir_fd, name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW) { + match rustix::fs::statat(dir_fd, name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW) { Ok(stat) if rustix::fs::FileType::from_raw_mode(stat.st_mode).is_file() => { - if let Err(e) = rustix::fs::unlinkat(&dir_fd, name, rustix::fs::AtFlags::empty()) { + if let Err(e) = rustix::fs::unlinkat(dir_fd, name, rustix::fs::AtFlags::empty()) { crate::server::log(&format!("{}: prune: {e}", path.display())); } } diff --git a/tests/exec_conformance/files_mode.rs b/tests/exec_conformance/files_mode.rs index 05783bd..b05c8a8 100644 --- a/tests/exec_conformance/files_mode.rs +++ b/tests/exec_conformance/files_mode.rs @@ -281,10 +281,7 @@ fn files_mode_refuses_symlinked_secrets_dir() { let out = run_exec(&cfg, "true", &[]); assert!(!out.status.success()); let stderr = String::from_utf8_lossy(&out.stderr); - assert!( - stderr.contains("secrets_dir is a symlink"), - "stderr: {stderr}" - ); + assert!(stderr.contains("symlink"), "stderr: {stderr}"); assert!( std::fs::read_dir(&real).unwrap().next().is_none(), "the symlink target must stay untouched" From cb4a60713a274ddee6636a81940f8aa6d6b80bf0 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Sun, 8 Nov 2026 00:43:31 -0600 Subject: [PATCH 35/47] docs: describe 0.1.0 as the first planned release Consolidate the changelog under Added and describe current capabilities in present tense. Keep the requested version heading and distinguish runtime behavior from deployment responsibilities. --- CHANGELOG.md | 315 ++++++++++++++++++++++----------------------------- 1 file changed, 138 insertions(+), 177 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 335b427..ef9882c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,184 +1,145 @@ # Changelog -All notable changes to this project are documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -### Security - -- Launched applications no longer inherit private-key variables from either - adapter namespace, regardless of key source or projection mode. Bundle - entries using reserved private-key names are rejected before launch. -- Bundle entries are now name-bound: a ciphertext decrypts only under its - own entry name (AES-GCM AAD); relocating it fails authentication. - Suite bumped to `ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad`; - pre-AAD bundles are rejected. Postmaster owns the compatible AAD envelope - decoder, using released `ecies` curve/HKDF helpers and RustCrypto AES-GCM. -- Hardening: a sibling launch monitor now owns stop semantics on the - exec path — the launcher forks after zeroization, the parent execs the - service (MainPID unchanged), and the fork-child supervises it: - synchronous stop-signal forwarding with a fixed 250 ms grace before - SIGKILL escalation, pidfd/kqueue liveness, and plaintext-file cleanup - on EVERY service-death path (natural exit, `kill -9`, crash) — the - macOS termination-signal deferral across the plaintext-write window - remains, while the sigaction flag-handler and second pre-exec gate are - retired (the monitor subsumes the race; fork(2) on Linux is the one - libc FFI call there, review-gated); logged hardening failures; - fd-pinned secret-file writes and fd-relative prune/cleanup; - `O_NOFOLLOW` ciphertext opens; sentinel-guarded bulk cleanup - (`.postmaster-managed`); keychain reads via the Security.framework API - (no `/usr/bin/security`); `--verify-keys` fails on ANY undecryptable - value, including under `strict:false`; daemon config rejects unknown - fields (root and nested); Linux `id` resolved from verified absolute - paths only; setup verification reuses the runtime key-variable - predicate; bundle `encoding: "utf8"` is validated at resolution. -- Hardening: redacted `Debug` on `KeyRing` and `Resolution` (latent - key-material/plaintext leak channels); env key loading skips non-UTF-8 - entries instead of panicking under panic=abort; credential-source - stat errors are terminal rather than fall-through; `setup --force` is - real (keychain re-seed, keys-file re-prompt; force+unattended fails - closed); daemon refuses a symlinked socket parent and non-absolute - config paths, and rejects empty credentials at preflight; - `--allow-nonroot` no longer overrides a configured `peer_user` ACL; - ramdisk verification checks lexical containment and the pinned directory's - backing device, retaining that handle for pruning and plaintext I/O; NUL in an - env-bound bundle value is a hard error under any strictness (one rule - for every env-bound value). - -### Changed - -- Nix installer temporary-file creation works with GNU and macOS `mktemp`. -- RAM-disk verification recognizes mounted and partitioned device rows in - `hdiutil info` while keeping each device tied to its own image. -- Build matrix preserves compiler flags and profile environment overrides, - uses `cargo zigbuild` for cross builds, and remaps source paths at `max`. - Help describes the configured release profile without performance estimates. -- Bundle files follow the same first-file-wins precedence as dotenv inputs; - `overload` selects the last definition. Dotenv files precede bundle files. -- Module restructure per file-size limits (500/750/1000 LOC bands): - `keys/`, `cli/`, `adapter/` domains; conformance suite split under - `tests/exec_conformance/`. -- Dependencies: base64 0.23.1, ecies 0.2.13, serde 1.0.229, - serde_json 1.0.154, zeroize 1.9.1, rustix 1.1.6, and libc 0.2.191. - The ECIES git patch is replaced by registry releases; AES-GCM 0.11.1 - provides bundle authentication with key-schedule zeroization enabled. -- CI automation conforms to the repo doctrine: in-repo composites only - (setup-rust, setup-nix — the latter verifies the pinned installer's - sha256 before executing), actions pinned by sha, workflows consume - just recipes. -- Monitor tests extracted to `src/monitor/tests.rs` (`monitor.rs` - 797 → 503 lines, same module path and visibility). -- Markdown linting consolidated into `.markdownlint-cli2.jsonc` (cli2 - never read `.markdownlintignore`); the two dead config files were - deleted and `just lint-md` (pinned markdownlint-cli2) now gates in - lefthook pre-commit, with `deny`+`audit` in pre-push. -- CI housekeeping: the duplicated `deny` job left ci.yml (security.yml - owns it), security.yml's path filters include the workflow file - itself, the docs job installs a pinned mdbook/mdbook-mermaid, and - cargo-deny/cargo-audit installs are version-pinned. -- `ci-rust` now includes `clippy-release` and `clippy-linux` recipes, - and rust-toolchain.toml pins the `x86_64-unknown-linux-gnu` target. - -### Added - -- "Unsafe Code" documentation section: exception policy and a registry - of every unsafe site (signal deferral, macOS libc boundary, systemd fd - ownership, test-only env mutation). -- `multiple_crate_versions` clippy lint plus `[bans] multiple-versions` - in deny.toml (syn skipped for the wasm-gated duplicate). -- Daemon end-to-end conformance (`tests/exec_conformance/daemon.rs`): - the real binary under `--bind --allow-nonroot`, a real `fetch` - roundtrip with a socket-mode assertion, and preflight refusal before - any bind. -- Regression coverage across secret-handling edges: the `read_capped` - cap boundary, symlink refusal end-to-end (env file, bundle file, - secrets dir), execvp-failure cleanup leaving only the sentinel, - passthrough-NUL cleanup, bundle precedence and NUL semantics, - provisioning primitive modes, the positive credential-source leg, and - the monitor's pre-dead-service leg. -- Executive overview page (leadership/PM audience) plus at-a-glance - intros across the unsafe-code section and a monitor lifecycle - mermaid diagram. - -### Fixed - -- Documentation matches strict-mode exceptions, dotenv interpolation, bundle - metadata, monitor inheritance, and deployment hardening requirements. - Rustdoc placeholders render as code, and the overview states protections - without timing claims or unconditional cleanup guarantees. -- Bundle configs resolve keys end-to-end again: `load_ring` admitted - only `DOTENV_PRIVATE_KEY*` (Env naming) at every source leg, so - `POSTMASTER_KEY` never entered the ring and every bundle exec failed - ("key ring has no POSTMASTER_KEY entry"). The ring now admits exactly - the namings the config's artifacts require — no more (least - privilege), no less. -- Darwin serve mode starts: `acquire_listeners` fchmod()ed the bound - socket fd, but Darwin `fchmod(2)` rejects socket fds (EINVAL) — every - `--bind` startup failed. Socket permissions are now umask-borne at - bind time on darwin (no TOCTOU window; Linux keeps the fd-based - fchmod). Caught by the new daemon end-to-end conformance test. -- `docs/schema/exec.schema.json` realigned with the parser: - `bundle_files` added, env/files modes accept `env_files` and/or - `bundle_files`, credentials mode rejects `bundle_files`, and the `$id` - points at postmaster — guarded by a fields-vs-schema tripwire test - and a new bundle example. -- Documentation corrections: a phantom exit code 2, `env` mislabeled as - the default mode, argv-exposing keychain seeding examples, a - store-path key-source example the parser rejects, "does not - supervise" contradicting the sibling monitor, stale unsafe-code - counts, undocumented `POSTMASTER_KEY` and 16 MiB read cap, and - envelope/dotenvx naming in the examples. - -### Removed - -- Dead `/postmaster/target/` gitignore line and the inert `docs/book/` - gitattributes pattern (gitattributes has no dir-recursion syntax). -- Duplicated `key_var_for` test copies in keys/exec_config (the legs - live in adapter/mod.rs where the mapping lives). +Version `0.1.0` is the first planned release. +Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [0.1.0] - 2026-07-28 ### Added -- Standalone postmaster binary — a format-neutral local secret - materialization engine that decrypts encrypted inputs at process - launch time, injects them into a child process, and `execvp`s the - target binary. -- `.env` input adapter — wire-compatible with dotenvx-encrypted `.env` - files (ECIES/secp256k1 + HKDF-SHA256 + AES-256-GCM). -- `postmaster_bundle` JSON container format as a second input adapter. -- `KeyNaming` enum (Env, Bundle) for compile-time exhaustive adapter - dispatch — zero vtable overhead, controlled adapter set. -- Three injection modes: `env` (environment variables), `files` - (one-file-per-secret on RAM-backed filesystem), `credentials` - (systemd credentials via postmaster daemon). -- Four key sources: systemd credentials (`LoadCredential=`), files - (`.env.keys` on disk), macOS keychain, environment variables. -- `postmaster exec --check` for config shape validation (CI). -- `postmaster setup --recheck` for runtime key source verification - (host). -- `postmaster setup` interactive command — idempotent, creates keys - directory, verifies permissions, optionally seeds keychain (macOS). -- `postmaster cleanup --config ` subcommand for plaintext - secret file removal. Wired to `ExecStopPost` in systemd. -- `--verify-keys` flag on `exec` for stale key detection after rotation. -- `OFlags::CLOEXEC` on all `rustix::fs::open` call sites. -- RAM backing verification via `hdiutil info` on macOS. -- Pre-execvp zeroization of `KeyRing` and `Resolved` values. -- Symlink rejection at every secret path: `O_NOFOLLOW`, `fstat`, - `symlink_metadata`, `fchmod` on socket fd. -- External binary verification: `codesign -v` on macOS, root-owned - check on Linux. -- Input validation: NUL byte rejection, path traversal rejection, - identifier validation, no shell expansion invariant. -- Threat model documentation covering memory residency, hardening - inheritance across execvp, and the 5-stage secret pipeline. -- Nix flake with rust-overlay for hermetic builds independent of - nixpkgs channel rustc version. -- `preventSwap` defaults to `true` — per-service `MemorySwapMax=0`. -- Child reads secrets via `$KEY_FILE` pointers (Docker secrets / - systemd credentials / 12-factor `_FILE` convention). -- `verify_key_freshness` uses `KeyNaming::Env.metadata_prefix()`. +- Provides a standalone, format-neutral secret materialization engine for + Linux and macOS. Postmaster decrypts local inputs, injects values into the + application, and replaces the launcher with the target binary through + `execvp`. +- Decrypts dotenvx-compatible `.env` files with ECIES/secp256k1, + HKDF-SHA256, and AES-256-GCM. +- Reads encrypted `postmaster_bundle` JSON containers alongside dotenv + inputs in `env` and `files` modes. Bundle entries support UTF-8 and binary + values; UTF-8 entries must decode successfully. +- Binds each bundle ciphertext to its entry name with AES-GCM AAD under + the `ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad` suite. + Postmaster owns the envelope decoder and uses released ECIES curve/HKDF + helpers and RustCrypto AES-GCM with key-schedule zeroization. +- Uses an exhaustive `KeyNaming` enum for dotenv and bundle adapter + dispatch. The key ring admits only the namespaces required by the + configured inputs. +- Loads private keys from systemd credentials, local key files, macOS + Keychain, or environment variables. Dotenv inputs use + `DOTENV_PRIVATE_KEY*`; bundles use `POSTMASTER_KEY`. +- Reads macOS Keychain items through the Security.framework API. +- Selects key sources in order. Missing systemd credentials allow the next + source; file, Keychain, and environment sources are terminal and fail + closed when unavailable or invalid. +- Checks private key files through an opened descriptor for ownership and + restrictive permissions. It rejects final-component symlinks and private + key paths in the Nix store. +- Keeps runtime key loading and setup verification on the same + key-variable naming rules. Environment loading skips non-UTF-8 entries. +- Supports `env` mode for direct environment injection. +- Supports `files` mode with one file per secret, `KEY_FILE` pointers, + and optional environment passthrough. Deployment integrations provide + RAM-backed storage and configure swap, dump, and cleanup policies. +- Supports `credentials` mode with pointers to systemd credentials or + selected values fetched from local Postmaster sockets. +- Resolves dotenv files before bundles. The first file defining a name + wins unless `overload` selects the last; the last assignment within one + dotenv file wins. Existing environment values take precedence unless + overload is enabled. +- Rejects undecryptable dotenv values by default. With `strict: false`, + it logs and omits those values; `--verify-keys` makes any omission fatal. + Bundle authentication failures always abort the launch. +- Rejects private-key variable names in bundles and removes recognized + private-key variables from the application's environment after + projection, regardless of key source or mode. +- Validates identifiers, credential-source path components, and NUL bytes + at the relevant input and projection boundaries. Encrypted values reach + the application without shell evaluation. Plaintext dotenv values follow + dotenv parsing rules, including variable substitution. +- Zeroizes the key ring and resolved value buffers before launch. + `KeyRing` and `Resolution` debug output redacts secret material. +- Keeps the application as the service's main PID. A sibling monitor + forwards stop signals, allows a 250 ms grace period before SIGKILL, and + tracks service exit with Linux pidfds or macOS kqueue. It attempts file + cleanup after natural exit, forced termination, or a crash. +- Defers termination signals across the plaintext write window on Linux + and macOS. The monitor consumes signals synchronously; the launcher + restores its signal mask before exec. +- Pins the secrets directory for pruning, writes, cleanup, and monitoring. + File creation rejects final-component symlinks, sets mode `0600` through + the descriptor, and attempts to unlink partial output on write failure. +- Guards bulk cleanup with a `.postmaster-managed` sentinel. Bulk cleanup + retains the marker on failure so the operation can be retried. + Launch-failure cleanup uses the same pinned directory. +- Verifies macOS RAM backing through `mount` and `hdiutil info`. + The pinned directory must be beneath the configured mount, owned by the + service user, and on the verified RAM device. Mounted and partitioned + device rows stay associated with their own image; cross-device ancestor + symlinks fail the check. +- Opens ciphertext files with `O_NOFOLLOW` and sets `CLOEXEC` on the file + descriptors it opens. Config, bundle, and credential-response reads + enforce their documented size limits. +- Verifies external tools before use with macOS code-signature checks or + Linux ownership and permission checks. Linux `id` lookup uses verified + absolute paths. +- Validates daemon configuration at the root and nested credential + mappings. Startup rejects relative paths, symlinked socket parents, + and empty credentials. +- Applies a configured `peer_user` ACL independently of + `--allow-nonroot`. Socket permissions use a bind-time umask on macOS + and descriptor-based `fchmod` on Linux. +- Applies process hardening on secret-handling command paths and logs + failures. Help, version output, and structural config checks avoid + secret-path hardening work. +- Provides `postmaster exec --check` for offline config-shape validation. + The JSON Schema covers dotenv and bundle inputs, mode-specific fields, + and strict unknown-field handling. Tested examples exercise the parser + and guard schema agreement. +- Provides `postmaster exec --verify-keys` to check decryption before + launching with keys that may be stale after rotation. +- Provides interactive and unattended `postmaster setup` workflows. + Setup creates a `0700` keys directory, verifies owner-only key files, + and optionally seeds macOS Keychain items. +- Provides `setup --recheck` for key-source accessibility checks and + `--keys-dir` for an explicit key directory. `--force` re-prompts for + key files or re-seeds Keychain items; force with unattended mode fails + closed. +- Provides `postmaster cleanup --config ` for managed + plaintext-file cleanup and `fetch` for local credential retrieval. +- Separates key handling, CLI parsing, and adapters into focused modules. + Monitor tests live beside the monitor module, adapter mapping tests live + with the adapters, and binary conformance tests cover each launch mode. +- Uses registry dependencies including base64 0.23.1, ecies 0.2.13, + serde 1.0.229, serde_json 1.0.154, zeroize 1.9.1, rustix 1.1.6, and + libc 0.2.191. AES-GCM 0.11.1 handles bundle authentication. +- Requires Rust 1.99.1 or newer. Release builds use LTO, stripped symbols, + overflow checks, and `panic = "abort"`. +- Provides a Nix package and overlay with rust-overlay for toolchain + selection. Service-manager bindings live in deployment integrations. +- Provides native and cross builds through the Justfile build matrix. + Cross builds use `cargo zigbuild`; builds preserve compiler flags and + profile overrides, and `max` builds remap source paths. +- Uses Justfile recipes for local checks and GitHub workflow definitions. + In-repo setup actions configure toolchains; Nix installation verifies + the pinned installer digest before execution. Official GitHub actions + and helper tools use pinned versions. Nix installer temporary files + work with GNU and macOS `mktemp`. +- Runs formatting, Clippy, and Markdown lint from pre-commit hooks. + Pre-push hooks run the Rust gate, dependency policy, and advisory checks. + The Rust gate includes native, release, and Linux-target Clippy; the + toolchain configuration includes `x86_64-unknown-linux-gnu`. +- Keeps Markdown lint rules in `.markdownlint-cli2.jsonc` and excludes + generated Cargo and mdBook output. Dependency policy checks duplicate + crate versions, sources, licenses, and advisories, with a documented + allowance for the wasm-gated `syn` duplicate. +- Exercises daemon startup, socket permissions, and real `fetch` + roundtrips in binary conformance tests. Regression tests cover read + limits, symlink refusal, partial-write and launch-failure cleanup, NUL + handling, precedence, provisioning permissions, key-source selection, + and monitor lifecycle behavior. +- Documents the launcher contract, five-stage secret pipeline, threat + model, deployment requirements, and memory-residency limits. The book + includes an executive overview, configuration examples, and monitor + lifecycle diagrams. +- Documents unsafe-code boundaries for signal deferral, monitoring, + macOS libc calls, systemd descriptor ownership, and test-only + environment mutation. From 421a5936dcad48ec8dce669c960deb5721142f4b Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Sun, 8 Nov 2026 01:49:02 -0600 Subject: [PATCH 36/47] fix: redact key-file errors and synchronize monitor tests --- docs/src/unsafe-code/monitor.md | 5 ++++- src/keys/load.rs | 20 +++++++++++++++++++- src/keys/verify.rs | 4 ++++ src/monitor/tests.rs | 28 +++++++++++++++++++++++----- 4 files changed, 50 insertions(+), 7 deletions(-) diff --git a/docs/src/unsafe-code/monitor.md b/docs/src/unsafe-code/monitor.md index f5f2969..a24a7e4 100644 --- a/docs/src/unsafe-code/monitor.md +++ b/docs/src/unsafe-code/monitor.md @@ -142,6 +142,9 @@ mutation): natural `kill -9` death → cleanup + exit; TERM to the monitor → forwarded (service dies by TERM, proving no escalation) → cleanup + exit; a TERM-ignoring forked service (`SIG_IGN` + `pause`) → SIGKILL only after the grace → cleanup + exit; env-mode (no fd, empty names) → exit on -service death. The exec integration suites +service death. The TERM-ignoring child acknowledges readiness through a +pipe after installing `SIG_IGN`; it uses only async-signal-safe calls after +fork. The parent waits for that acknowledgement before starting the monitor. +The exec integration suites (`tests/exec_check.rs`, `tests/exec_conformance/`) exercise the full fork+exec path and assert the post-exit cleanup contract. diff --git a/src/keys/load.rs b/src/keys/load.rs index 817292d..1e60f4f 100644 --- a/src/keys/load.rs +++ b/src/keys/load.rs @@ -56,7 +56,9 @@ pub(super) fn load(path: &Path, namings: &[KeyNaming]) -> Result Pid { + let (mut ready_read, ready_write) = std::io::pipe().unwrap(); // SAFETY: fork(2) in the test process; the child executes only - // async-signal-safe calls (signal(2), pause(2)) and never returns - // into the test harness — no allocation, no stdio, no locks. + // async-signal-safe calls (close, signal, write, pause, _exit) and + // never returns into the test harness — no allocation, stdio, or locks. match unsafe { libc::fork() } { -1 => panic!("fork: {}", std::io::Error::last_os_error()), 0 => unsafe { + libc::close(ready_read.as_raw_fd()); // SAFETY: plain single-threaded signal op on this // process; SIG_IGN is the documented ignore-disposition // constant. pause(2) suspends until a caught signal // arrives; TERM is ignored, so only SIGKILL ends the loop. - libc::signal(libc::SIGTERM, libc::SIG_IGN); + if libc::signal(libc::SIGTERM, libc::SIG_IGN) == libc::SIG_ERR + || libc::write(ready_write.as_raw_fd(), b"R".as_ptr().cast(), 1) != 1 + { + libc::_exit(1); + } + libc::close(ready_write.as_raw_fd()); loop { libc::pause(); } }, - child => Pid::from_raw(child).unwrap(), + child => { + let pid = Pid::from_raw(child).unwrap(); + drop(ready_write); + if let Err(error) = ready_read.read_exact(&mut [0]) { + drop(ReapOnDrop(pid)); + panic!("service readiness: {error}"); + } + pid + } } } From f16e07bf3b611fdd0154ac7010191b505fc8d3cf Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Sun, 8 Nov 2026 05:29:43 -0600 Subject: [PATCH 37/47] fix: enforce socket modes and setup tool versions --- .github/actions/setup-rust/action.yml | 16 +-- .github/actions/setup-rust/install-tool.sh | 32 ++++++ .github/actions/setup-rust/test.py | 116 +++++++++++++++++++++ CHANGELOG.md | 4 +- docs/src/architecture/threat-model.md | 7 +- src/server.rs | 58 +++-------- tests/exec_conformance/daemon.rs | 49 +++++++-- 7 files changed, 210 insertions(+), 72 deletions(-) create mode 100644 .github/actions/setup-rust/install-tool.sh create mode 100644 .github/actions/setup-rust/test.py diff --git a/.github/actions/setup-rust/action.yml b/.github/actions/setup-rust/action.yml index 9edc86f..647efb6 100644 --- a/.github/actions/setup-rust/action.yml +++ b/.github/actions/setup-rust/action.yml @@ -112,9 +112,7 @@ runs: CARGO_INSTALL_TARGET_DIR: ${{ inputs.install-target-dir }} run: | set -euo pipefail - if ! command -v cargo-deny >/dev/null 2>&1; then - cargo install cargo-deny --version "$CARGO_DENY_VERSION" --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" - fi + bash "$GITHUB_ACTION_PATH/install-tool.sh" cargo-deny "$CARGO_DENY_VERSION" "$CARGO_INSTALL_TARGET_DIR" - name: Install cargo-audit if: ${{ inputs.install-cargo-audit == 'true' }} @@ -124,9 +122,7 @@ runs: CARGO_INSTALL_TARGET_DIR: ${{ inputs.install-target-dir }} run: | set -euo pipefail - if ! command -v cargo-audit >/dev/null 2>&1; then - cargo install cargo-audit --version "$CARGO_AUDIT_VERSION" --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" - fi + bash "$GITHUB_ACTION_PATH/install-tool.sh" cargo-audit "$CARGO_AUDIT_VERSION" "$CARGO_INSTALL_TARGET_DIR" - name: Install mdbook if: ${{ inputs.install-mdbook == 'true' }} @@ -137,9 +133,5 @@ runs: CARGO_INSTALL_TARGET_DIR: ${{ inputs.install-target-dir }} run: | set -euo pipefail - if ! command -v mdbook >/dev/null 2>&1; then - cargo install mdbook --version "$MDBOOK_VERSION" --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" - fi - if ! command -v mdbook-mermaid >/dev/null 2>&1; then - cargo install mdbook-mermaid --version "$MDBOOK_MERMAID_VERSION" --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" - fi + bash "$GITHUB_ACTION_PATH/install-tool.sh" mdbook "$MDBOOK_VERSION" "$CARGO_INSTALL_TARGET_DIR" + bash "$GITHUB_ACTION_PATH/install-tool.sh" mdbook-mermaid "$MDBOOK_MERMAID_VERSION" "$CARGO_INSTALL_TARGET_DIR" diff --git a/.github/actions/setup-rust/install-tool.sh b/.github/actions/setup-rust/install-tool.sh new file mode 100644 index 0000000..d296f98 --- /dev/null +++ b/.github/actions/setup-rust/install-tool.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Ensure a requested Cargo tool runs at its pinned version in later steps. +# Args: crate/binary name (string), version (string), build directory (path). +# Exits nonzero if installation fails or the resulting version differs. +set -euo pipefail + +tool="$1" +version="$2" +target_dir="$3" +install_root="${CARGO_INSTALL_ROOT:-${CARGO_HOME:-$HOME/.cargo}}" +tool_bin="$install_root/bin" +export PATH="$tool_bin:$PATH" + +version_matches() { + local reported + reported="$("$tool" --version 2>/dev/null)" || return 1 + [[ "$reported" == "$tool $version" || "$reported" == "$tool v$version" ]] +} + +if ! version_matches; then + cargo install "$tool" --version "$version" --locked --force \ + --root "$install_root" --target-dir "$target_dir" + hash -r +fi +if ! version_matches; then + echo "$tool: expected version $version after installation" >&2 + exit 1 +fi +if [[ -n "${GITHUB_PATH:-}" ]]; then + echo "$tool_bin" >> "$GITHUB_PATH" +fi +"$tool" --version diff --git a/.github/actions/setup-rust/test.py b/.github/actions/setup-rust/test.py new file mode 100644 index 0000000..ceefd6c --- /dev/null +++ b/.github/actions/setup-rust/test.py @@ -0,0 +1,116 @@ +"""Exercise optional tool setup without installing packages. + +Run: python3 .github/actions/setup-rust/test.py [path-to-bash] +""" + +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import textwrap + + +action_dir = Path(__file__).resolve().parent +action = (action_dir / "action.yml").read_text() +bash = Path(sys.argv[1] if len(sys.argv) > 1 else "/bin/bash").resolve() +tools = { + "cargo-deny": ("Install cargo-deny", "CARGO_DENY_VERSION", "0.20.2"), + "cargo-audit": ("Install cargo-audit", "CARGO_AUDIT_VERSION", "0.22.2"), + "mdbook": ("Install mdbook", "MDBOOK_VERSION", "0.5.4"), + "mdbook-mermaid": ("Install mdbook", "MDBOOK_MERMAID_VERSION", "0.17.0"), +} +scenarios = ( + "current", "outdated", "broken", "missing", "install-fails", "installed-wrong", + "custom-root", +) +failures = [] +for tool, (step, version_var, version) in tools.items(): + section = action.split(f" - name: {step}\n", 1)[1].split("\n - name:", 1)[0] + body = textwrap.dedent(section.split(" run: |\n", 1)[1]) + for scenario in scenarios: + with tempfile.TemporaryDirectory(prefix="postmaster-setup-") as tmp: + root = Path(tmp) + cargo_home = root / "cargo home" + install_root = root / "install root" if scenario == "custom-root" else cargo_home + bin_dir = install_root / "bin" + bin_dir.mkdir(parents=True) + shims = root / "shims" + shims.mkdir() + (shims / "bash").symlink_to(bash) + log = root / "install.log" + env = os.environ.copy() + env.pop("CARGO_INSTALL_ROOT", None) + env.update( + PATH=f"{shims}:/usr/bin:/bin", + CARGO_HOME=str(cargo_home), + CARGO_INSTALL_TARGET_DIR=str(root / "build target"), + GITHUB_ACTION_PATH=str(action_dir), + GITHUB_PATH=str(root / "github-path"), + TEST_TOOL=tool, + TEST_VERSION=version, + TEST_LOG=str(log), + TEST_SCENARIO=scenario, + TEST_INSTALL_ROOT=str(install_root), + ) + if scenario == "custom-root": + env["CARGO_INSTALL_ROOT"] = str(install_root) + for name, (_, var, pinned) in tools.items(): + env[var] = pinned + # The other mdBook executable remains available at its pin. + executable = shims / name + prefix = "v" if name == "mdbook" else "" + reported = f"{name} {prefix}{pinned}" + if name == tool: + if scenario == "missing": + continue + reported = f"{name} 0.0.0" if scenario != "current" else reported + executable.write_text( + "#!/bin/sh\n" + + ("exit 127\n" if name == tool and scenario == "broken" + else f"printf '%s\\n' '{reported}'\n") + ) + executable.chmod(0o755) + cargo = shims / "cargo" + cargo.write_text("""#!/bin/bash +set -eu +printf '%s\\n' "$@" > "$TEST_LOG" +[[ "$TEST_SCENARIO" != install-fails ]] || exit 1 +mkdir -p "$TEST_INSTALL_ROOT/bin" +version="$TEST_VERSION" +[[ "$TEST_SCENARIO" != installed-wrong ]] || version=0.0.0 +printf '#!/bin/sh\\nprintf "%%s\\n" "%s %s"\\n' "$TEST_TOOL" "$version" > "$TEST_INSTALL_ROOT/bin/$TEST_TOOL" +chmod +x "$TEST_INSTALL_ROOT/bin/$TEST_TOOL" +""") + cargo.chmod(0o755) + result = subprocess.run( + [str(bash), "-c", body], + env=env, capture_output=True, text=True, + ) + try: + should_fail = scenario in ("install-fails", "installed-wrong") + assert (result.returncode != 0) == should_fail, result.stdout + result.stderr + assert log.exists() == (scenario != "current"), "wrong install decision" + if log.exists(): + args = log.read_text().splitlines() + assert args[:2] == ["install", tool], args + assert args[args.index("--version") + 1] == version, args + assert "--locked" in args, args + assert args[args.index("--root") + 1] == str(install_root), args + assert args[args.index("--target-dir") + 1] == env["CARGO_INSTALL_TARGET_DIR"], args + if not should_fail: + paths = Path(env["GITHUB_PATH"]).read_text().splitlines() + assert str(bin_dir) in paths, "verified install directory absent from PATH" + check = subprocess.run( + [tool, "--version"], + env={**env, "PATH": os.pathsep.join(paths + [env["PATH"]])}, + capture_output=True, text=True, + ) + assert check.returncode == 0, check.stderr + assert check.stdout.strip() in (f"{tool} {version}", f"{tool} v{version}") + except (AssertionError, ValueError, FileNotFoundError) as error: + failures.append(f"{tool}/{scenario}: {error}") + +if failures: + raise SystemExit("\n".join(failures)) +print(f"Optional tool setup: {len(tools) * len(scenarios)} cases pass") diff --git a/CHANGELOG.md b/CHANGELOG.md index ef9882c..96d20c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -85,8 +85,8 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). mappings. Startup rejects relative paths, symlinked socket parents, and empty credentials. - Applies a configured `peer_user` ACL independently of - `--allow-nonroot`. Socket permissions use a bind-time umask on macOS - and descriptor-based `fchmod` on Linux. + `--allow-nonroot`. Socket permissions use a bind-time umask on Linux + and macOS, with the prior mask restored immediately afterward. - Applies process hardening on secret-handling command paths and logs failures. Help, version output, and structural config checks avoid secret-path hardening work. diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index d965745..1508cbd 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -199,9 +199,10 @@ where secret material is read or written: inode must also belong to the verified RAM device and service user. This checks intermediate-symlink targets as well. The launcher retains that handle for pruning, writes, cleanup, and monitoring. -- **Socket permissions** use `fchmod` on the socket fd on Linux. macOS rejects - that operation, so Postmaster sets the umask before binding there and - restores it afterward. +- **Socket permissions** use a bind-time umask on Linux and macOS, so the + pathname has its final mode from creation. Postmaster restores the prior + mask immediately afterward, including on bind failure. Binding runs + before serving threads start. ### External binary verification diff --git a/src/server.rs b/src/server.rs index 70bbaa4..9d40885 100644 --- a/src/server.rs +++ b/src/server.rs @@ -371,48 +371,32 @@ pub fn keys_path(source: &KeysSource) -> Result { /// RAII guard that sets the process umask so a bound unix socket is born /// with `mode` (sockets are created `0777 & ~umask`) and restores the -/// prior mask on drop. Darwin-only: Linux fchmod()s the already-bound -/// socket fd, which Darwin cannot do — fchmod(2) rejects socket fds -/// with EINVAL — and a path chmod would reopen the same TOCTOU (a -/// swapped-in symlink redirecting the chmod to an attacker-chosen -/// file). Being born with the right mode has no window at all. -#[cfg(target_os = "macos")] +/// prior mask on drop. Used only during single-threaded socket setup. #[derive(Debug)] -struct UmaskGuard(libc::mode_t); +struct UmaskGuard(rustix::fs::Mode); -#[cfg(target_os = "macos")] impl UmaskGuard { - fn around_bind(mode: u32) -> Self { - let mask = (!mode & 0o777) as libc::mode_t; - // SAFETY: umask(2) cannot fail and has no memory-safety surface. - // The call site is single-threaded (run() spawns the serve - // threads only after acquire_listeners returns), so the - // process-wide flip cannot race. - Self(unsafe { libc::umask(mask) }) + fn around_bind(mode: rustix::fs::Mode) -> Self { + let mask = !mode & rustix::fs::Mode::from_bits_truncate(0o777); + Self(rustix::process::umask(mask)) } } -#[cfg(target_os = "macos")] impl Drop for UmaskGuard { fn drop(&mut self) { - // SAFETY: restoring the mask captured at construction; same - // single-threaded window and no-failure contract as above. - unsafe { - libc::umask(self.0); - } + rustix::process::umask(self.0); } } /// Bind and listen on all configured credential sockets. Returns /// a vector of `(UnixListener, path)` pairs ready for serving (the entry /// is re-looked-up by the caller). +/// Call during single-threaded startup: bind mode temporarily changes umask. pub fn acquire_listeners( cfg: &Config, bind: bool, peer_uids: &std::collections::HashMap>, ) -> Result, String> { - #[cfg(not(target_os = "macos"))] - use std::os::fd::AsFd; if bind { let am_root = rustix::process::geteuid().is_root(); let mut out = Vec::new(); @@ -475,27 +459,13 @@ pub fn acquire_listeners( // connect(2) needs write on the socket inode; the reachability // gate is the 0500 parent dir plus the peer-credential check. let mode = if expected.is_some() { 0o666 } else { 0o600 }; - // Darwin has no fchmod(2) for socket fds (EINVAL — found by - // the T2 end-to-end conformance test, sweep 2026-08-07), and - // a path chmod would reopen the audit-#7 TOCTOU the fchmod - // below closes. Flip the process umask around the bind - // instead: the socket is born with `mode`, so there is no - // window at all. The process is single-threaded here — run() - // spawns the serve threads only after acquire_listeners - // returns — so the process-wide flip is race-free. - #[cfg(target_os = "macos")] - let _umask_guard = UmaskGuard::around_bind(mode); - let l = - UnixListener::bind(path).map_err(|e| format!("{}: bind: {e}", path.display()))?; - // Audit finding #7: use fchmod on the socket fd instead of - // set_permissions on the path to eliminate a TOCTOU between - // bind and chmod. Between those two path operations an attacker - // with directory write access could unlink the socket and - // create a symlink. fchmod operates on the already-bound fd, - // which is the socket inode we just created. - #[cfg(not(target_os = "macos"))] - rustix::fs::fchmod(l.as_fd(), rustix::fs::Mode::from_bits_truncate(mode)) - .map_err(|e| format!("{}: fchmod: {e}", path.display()))?; + // fchmod on Linux changes the sockfs inode, not the pathname; + // Darwin rejects it. Bind with the final mode to avoid a chmod race. + let l = { + let _umask_guard = + UmaskGuard::around_bind(rustix::fs::Mode::from_bits_truncate(mode)); + UnixListener::bind(path).map_err(|e| format!("{}: bind: {e}", path.display()))? + }; out.push((l, path.clone())); } return Ok(out); diff --git a/tests/exec_conformance/daemon.rs b/tests/exec_conformance/daemon.rs index 846fbaa..a5b9e60 100644 --- a/tests/exec_conformance/daemon.rs +++ b/tests/exec_conformance/daemon.rs @@ -54,6 +54,22 @@ fn wait_for_socket( #[test] fn daemon_serves_a_real_fetch_roundtrip() { + for mask in ["000", "022", "077"] { + daemon_roundtrip(mask, None); + } +} + +#[test] +fn daemon_serves_configured_peer_under_any_umask() { + let out = Command::new("/usr/bin/id").arg("-un").output().unwrap(); + assert!(out.status.success()); + let user = String::from_utf8(out.stdout).unwrap(); + for mask in ["000", "022", "077"] { + daemon_roundtrip(mask, Some(user.trim())); + } +} + +fn daemon_roundtrip(mask: &str, peer_user: Option<&str>) { let d = common::tmpdir("daemon"); let env = common::write_env_file( &d, @@ -70,19 +86,30 @@ fn daemon_serves_a_real_fetch_roundtrip() { let cfg = d.join("daemon.json"); std::fs::write( &cfg, - format!( - r#"{{"keys":{{"file":"{}"}},"credentials":{{"{}":{{"env_file":"{}","key":"DB_URL"}}}}}}"#, - keys.display(), - sock.display(), - env.display() - ), + serde_json::json!({ + "keys": {"file": keys}, + "credentials": {sock.to_str().unwrap(): { + "env_file": env, + "key": "DB_URL", + "peer_user": peer_user, + }}, + }) + .to_string(), ) .unwrap(); // The suite runs as the test user: --bind (no systemd activation // here) and --allow-nonroot (the peer ACL's root-only default would - // refuse our own fetch otherwise; no peer_user is configured). - let daemon = Command::new(env!("CARGO_BIN_EXE_postmaster")) + // refuse our own fetch when no peer_user is configured). + // The shell sets the child's mask without changing the test process. + let daemon = Command::new("/bin/sh") + .args([ + "-c", + "umask \"$1\"; shift; exec \"$@\"", + "postmaster-test", + mask, + env!("CARGO_BIN_EXE_postmaster"), + ]) .args(["--config"]) .arg(&cfg) .args(["--bind", "--allow-nonroot"]) @@ -92,11 +119,11 @@ fn daemon_serves_a_real_fetch_roundtrip() { let mut guard = KillOnDrop(Some(daemon)); wait_for_socket(guard.0.as_mut().unwrap(), &sock, Duration::from_secs(10)).unwrap(); - // The bind-time permission contract (audit finding #7; umask-borne on - // darwin, fchmod on Linux): no peer_user configured → owner-only. + // A configured peer needs write access; otherwise the socket is owner-only. use std::os::unix::fs::PermissionsExt as _; let mode = std::fs::metadata(&sock).unwrap().permissions().mode() & 0o777; - assert_eq!(mode, 0o600, "socket must be owner-only, got {mode:o}"); + let expected = if peer_user.is_some() { 0o666 } else { 0o600 }; + assert_eq!(mode, expected, "socket mode under umask {mask}"); let out = Command::new(env!("CARGO_BIN_EXE_postmaster")) .arg("fetch") From b530668146e87e3ba1f611fb8f0e4a390c2273b0 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Sun, 8 Nov 2026 10:59:29 -0600 Subject: [PATCH 38/47] fix: secure secret input and materialization boundaries --- CHANGELOG.md | 16 +- Cargo.lock | 44 +- Cargo.toml | 8 +- docs/src/architecture/threat-model.md | 36 +- docs/src/getting-started/injection-modes.md | 7 +- docs/src/getting-started/key-provisioning.md | 14 + docs/src/reference/cli.md | 34 ++ docs/src/reference/launcher-contract.md | 30 +- docs/src/unsafe-code/index.md | 7 +- docs/src/unsafe-code/macos-libc-boundary.md | 23 +- docs/src/unsafe-code/signal-deferral.md | 32 +- licenses/dotenvy-MIT.txt | 21 + src/cli/mod.rs | 22 +- src/keys/dotenv.rs | 583 +++++++++++++++++++ src/keys/load.rs | 24 +- src/keys/mod.rs | 164 ++++-- src/keys/provisioning/cleanup.rs | 20 +- src/keys/provisioning/input.rs | 202 +++++++ src/keys/provisioning/mod.rs | 311 +++++----- src/keys/source.rs | 19 +- src/keys/verify.rs | 16 +- src/launcher.rs | 72 ++- src/monitor/tests.rs | 9 +- src/ramdisk.rs | 11 +- src/secret_files.rs | 337 +++++++++-- src/secret_files/acl.rs | 186 ++++++ src/server.rs | 136 ++++- src/test_util.rs | 2 + src/test_util/pty.rs | 113 ++++ src/test_util/temp_dir.rs | 43 ++ tests/common/mod.rs | 13 +- tests/exec_check.rs | 10 +- tests/exec_conformance/daemon.rs | 31 +- tests/exec_conformance/main.rs | 15 + tests/exec_conformance/setup.rs | 160 +++++ 35 files changed, 2383 insertions(+), 388 deletions(-) create mode 100644 licenses/dotenvy-MIT.txt create mode 100644 src/keys/dotenv.rs create mode 100644 src/keys/provisioning/input.rs create mode 100644 src/secret_files/acl.rs create mode 100644 src/test_util/pty.rs create mode 100644 src/test_util/temp_dir.rs create mode 100644 tests/exec_conformance/setup.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 96d20c3..24d79f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,12 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Keychain, or environment variables. Dotenv inputs use `DOTENV_PRIVATE_KEY*`; bundles use `POSTMASTER_KEY`. - Reads macOS Keychain items through the Security.framework API. +- Hides private-key terminal input and restores settings before pending + termination or suspend signals. Forced key-file replacement verifies inode + identity and ownership before publishing a fresh owner-only file. +- Authorizes daemon dotenv files against trusted `env_file_sha256` hashes + before parsing or decryption, at startup and on every fetch. Multiple hashes + support staged rotation without changing the dotenvx ciphertext format. - Selects key sources in order. Missing systemd credentials allow the next source; file, Keychain, and environment sources are terminal and fail closed when unavailable or invalid. @@ -65,8 +71,10 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and macOS. The monitor consumes signals synchronously; the launcher restores its signal mask before exec. - Pins the secrets directory for pruning, writes, cleanup, and monitoring. - File creation rejects final-component symlinks, sets mode `0600` through - the descriptor, and attempts to unlink partial output on write failure. + File refreshes publish fresh 0600 inodes without writing new plaintext to + old open handles. Foreign, linked, and special existing entries fail closed. + Exported paths require trusted, protected ancestry; sticky shared parents + and trusted symlink aliases remain supported. - Guards bulk cleanup with a `.postmaster-managed` sentinel. Bulk cleanup retains the marker on failure so the operation can be retried. Launch-failure cleanup uses the same pinned directory. @@ -77,7 +85,9 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). symlinks fail the check. - Opens ciphertext files with `O_NOFOLLOW` and sets `CLOEXEC` on the file descriptors it opens. Config, bundle, and credential-response reads - enforce their documented size limits. + enforce their documented size limits. Dotenv sources must be regular files; + parsing bounds source bytes, assignments, and expanded values before growth, + while syntax errors omit input contents. - Verifies external tools before use with macOS code-signature checks or Linux ownership and permission checks. Linux `id` lookup uses verified absolute paths. diff --git a/Cargo.lock b/Cargo.lock index 97576cb..b5fe26a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -205,6 +205,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer", + "const-oid", "crypto-common", "ctutils", ] @@ -222,7 +223,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05585cd8ca04e63c7bb5d7308fd7583cc8df9fcf3e6ff9132562c57209a7f231" dependencies = [ "aes-gcm", - "getrandom", + "getrandom 0.2.17", "hkdf", "k256", "lock_api", @@ -262,6 +263,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "ff" version = "0.14.0" @@ -309,6 +316,17 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + [[package]] name = "ghash" version = "0.6.0" @@ -504,12 +522,15 @@ dependencies = [ "base64", "dotenvy", "ecies", + "getrandom 0.4.3", "hex", "libc", "rustix", "security-framework", "serde", "serde_json", + "sha2", + "tempfile", "zeroize", ] @@ -557,13 +578,19 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + [[package]] name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom", + "getrandom 0.2.17", ] [[package]] @@ -737,6 +764,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys", +] + [[package]] name = "typenum" version = "1.20.1" diff --git a/Cargo.toml b/Cargo.toml index 9464646..31e796d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ repository = "https://github.com/beardedeagle/postmaster" # syscall-boundary daemon and needs a handful of justified `unsafe` blocks: # getpeereid(2) and PT_DENY_ATTACH on macOS (Darwin's stable kernel ABI is # libc), signal-mask deferral around the plaintext-write window and the +# Darwin extended ACL inspection/clearing, test-only pseudo-terminals, and the # sibling launch monitor (fork + pidfd/kqueue liveness — see # docs/src/unsafe-code/monitor.md; on Linux the monitor's signal ops use # rustix's linux_raw `runtime` API, fork(2) is the single libc FFI call), @@ -108,10 +109,12 @@ serde_json = "1" base64 = "0.23" hex = "0.4" zeroize = "1" +sha2 = "0.11" +getrandom = "0.4" # Syscall layer: rustix's default linux_raw backend issues raw syscalls from # Rust — no libc FFI in these paths, and the unsafe surface collapses to the # single fd-ownership assertion at the systemd socket-activation boundary. -rustix = { version = "1", features = ["net", "process", "mm", "fs"] } +rustix = { version = "1", features = ["net", "process", "mm", "fs", "termios", "event"] } [target.'cfg(target_os = "linux")'.dependencies] # Linux-only additions for the sibling launch monitor @@ -138,6 +141,9 @@ libc = "0.2" libc = "0.2" security-framework = "3.7.0" +[dev-dependencies] +tempfile = "3.27" + [profile.release] # Everything here is stable-toolchain and arch-agnostic: safe under nixpkgs # rustPlatform on any Linux target. Microarch tuning (-C target-cpu=…) does diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index 1508cbd..cafa1d8 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -192,17 +192,33 @@ where secret material is read or written: before loading, rejecting symlinks at the path level. The `O_NOFOLLOW` open in `KeyRing::load` provides defense-in-depth at the fd level. -- **Secret files** are written with `O_NOFOLLOW | O_CREAT | O_TRUNC` - — a symlink planted at the target path is rejected, not followed. +- **Secret files** use fresh, exclusively created 0600 inodes and atomic + publication beneath the pinned directory. Refreshes never write new + plaintext into old inodes or read handles. Foreign, hardlinked, symlinked, + and special existing files fail before mutation. On macOS, inherited ACL + grants that could expose fresh files are rejected; new file ACLs are cleared. - **Secrets directory** is opened with `O_DIRECTORY | O_NOFOLLOW`, rejecting a final-component symlink. With `verify_ramdisk`, the opened inode must also belong to the verified RAM device and service user. This checks intermediate-symlink targets as well. The launcher retains - that handle for pruning, writes, cleanup, and monitoring. + that handle for pruning, writes, cleanup, and monitoring. Before exporting + consumer paths, Postmaster checks every lexical and resolved ancestor for + trusted ownership and protection against replacement. Trusted symlinks and + sticky shared directories remain usable; unsafe writable ancestors and + macOS ACL grants fail closed. - **Socket permissions** use a bind-time umask on Linux and macOS, so the pathname has its final mode from creation. Postmaster restores the prior mask immediately afterward, including on bind failure. Binding runs - before serving threads start. + before serving threads start. Distinct consumer ownership domains cannot + share a parent or sit beneath a parent controlled by another consumer. + Alias and dot-segment checks run before any directory or socket mutation. + +Daemon entries authorize the exact dotenv source bytes with trusted +`env_file_sha256` hashes before parsing, interpolation, or decryption. The +check runs at startup and on every fetch. A file from another entry cannot +be substituted merely because it uses the same private key. Expected hashes +belong in trusted configuration, separate from mutable artifacts. Exec mode +uses its configured application inputs as the trust boundary instead. ### External binary verification @@ -236,7 +252,9 @@ the secret path: - **No shell evaluation:** decrypted values and bundle plaintext are injected as bytes. Plaintext dotenv entries follow `dotenvy` parsing rules, including variable substitution in unquoted and double-quoted values. Single quotes - preserve `${VAR}` literally. `$(cmd)` is not executed. + preserve `${VAR}` literally. `$(cmd)` is not executed. Source bytes, expanded + values, assignments, and aggregate parsed output have fixed limits checked + before growth; parser errors omit input values. ### Key freshness verification @@ -548,10 +566,10 @@ cannot redirect those operations onto persistent storage. `OFlags::CLOEXEC` is set on every file descriptor postmaster opens (all `rustix::fs::open`/`openat` sites) — the kernel automatically closes these on execvp, preventing the child from inheriting postmaster's open -file descriptors. Third-party parsers never open their own fds in -postmaster's paths: dotenvy is only invoked as `dotenvy::from_read_iter` -on fds postmaster itself opened (`O_NOFOLLOW | CLOEXEC`). Postmaster's -own fds are fully covered. +file descriptors. Parsers receive bytes or descriptors Postmaster opens; they do +not open +paths themselves. Dotenv artifact reads also use nonblocking opens and reject +special files before reading. Postmaster's own fds are fully covered. ### Secrets directory path exposure — Mitigated diff --git a/docs/src/getting-started/injection-modes.md b/docs/src/getting-started/injection-modes.md index 1971880..a97213d 100644 --- a/docs/src/getting-started/injection-modes.md +++ b/docs/src/getting-started/injection-modes.md @@ -71,9 +71,10 @@ and ordinary inherited variables remain present. The application can also copy file contents into its own memory. A hand-written config must provide RAM-backed storage; setting `secrets_dir` alone does not verify it. -Each secret file is written with `O_NOFOLLOW | O_CREAT | O_TRUNC` and -`fchmod`'d to `0600` on the file descriptor (no TOCTOU window between -open and chmod). +Each secret refresh publishes a fresh 0600 inode beneath the pinned directory. +Old read handles keep the old contents. Foreign, linked, and special entries +fail closed, and exported paths require protected ancestry. Trusted symlink +aliases and sticky shared parents remain supported. For a mostly-file-capable app with a straggler that needs an env var: diff --git a/docs/src/getting-started/key-provisioning.md b/docs/src/getting-started/key-provisioning.md index 4d95678..f9742d4 100644 --- a/docs/src/getting-started/key-provisioning.md +++ b/docs/src/getting-started/key-provisioning.md @@ -114,6 +114,13 @@ No file on disk — keys live as generic-password items in the default keychain search list. Postmaster reads them natively via the Security.framework API (`security-framework` crate). +`postmaster setup` hides terminal input for both key files and Keychain values. +It restores terminal settings when input finishes, fails, or receives a +catchable termination or suspend signal. Redirected key-file input still +accepts multiple lines through EOF. `--force` publishes a fresh 0600 key-file +inode after confirmation and refuses a substituted, foreign, linked, or +special file. Existing open handles keep the old contents. + ## Rotation No `rotate` subcommand exists. The flow is manual, but @@ -148,3 +155,10 @@ failure: ```console $ postmaster exec --config exec.json --verify-keys -- /usr/bin/true ``` + +For daemon mode, authorize the new dotenv file's SHA-256 in each entry's +`env_file_sha256` list before deploying it. Keep both old and new hashes during +the rotation window, then remove the old hash. Hashes cover the complete file, +including plaintext, comments, and line endings. Compute them from the trusted +artifact; do not derive authorization from a runtime copy that can be changed. +Exec configurations continue to select application inputs through `env_files`. diff --git a/docs/src/reference/cli.md b/docs/src/reference/cli.md index f6bf731..f518192 100644 --- a/docs/src/reference/cli.md +++ b/docs/src/reference/cli.md @@ -46,6 +46,29 @@ unit owns the sockets and the daemon inherits them via `sd_listen_fds`. On macOS, `--bind` causes postmaster to create its own listener sockets. +### Daemon configuration + +Each socket maps to an entry with `env_file`, `key`, `env_file_sha256`, and +optional `peer_user`. `env_file_sha256` is a list of SHA-256 hashes, encoded +as 64 hex digits, for the exact dotenv file bytes authorized for that entry. +Postmaster checks the hash before parsing, interpolation, or decryption, both +at startup and on every fetch. An empty list authorizes nothing. This applies +to plaintext assignments too. + +Keep this configuration under trusted ownership. Compute hashes from the +trusted artifact before deployment, rather than from the writable runtime +copy. On Linux, use `sha256sum `; on macOS, use `shasum -a 256 `. +Line endings, whitespace, and metadata count toward the hash. Multiple hashes +allow old and new files during staged rotation; remove the old hash when that +window ends. The dotenvx ciphertext format and private-key rotation candidates +stay the same. + +When binding as root, sockets for different unprivileged peers need separate +parent directories. One peer's parent cannot contain another peer's socket +parent. Postmaster resolves aliases and checks these ownership domains before +changing directories or binding sockets. Sockets for the same user can share +a parent; root-only entries and `peer_user` resolving to uid 0 share a domain. + ## exec Decrypt and inject secrets, then `execvp` the target binary. @@ -104,6 +127,17 @@ Default keys directory: - macOS: `~/Library/Application Support/postmaster` (falls back to `/var/lib/postmaster` when `HOME` is unset) +Secret terminal input has echo disabled until the read finishes. Postmaster +restores terminal settings before delivering a pending termination or suspend +signal. Key files accept multiline input through EOF; Keychain values use one +trimmed line. Redirected input keeps the same format and buffering. + +Forced key-file replacement verifies ownership, regular-file type, and single +link count before changing permissions. It pins the parent, checks that the +original inode still occupies the name after input, and publishes a fresh +0600 inode. Existing read handles keep the old contents. A declined replacement +keeps the existing contents; unattended replacement fails without prompting. + ## cleanup Remove plaintext secret files from the secrets directory after the diff --git a/docs/src/reference/launcher-contract.md b/docs/src/reference/launcher-contract.md index 8eaa86a..af29ee5 100644 --- a/docs/src/reference/launcher-contract.md +++ b/docs/src/reference/launcher-contract.md @@ -254,6 +254,20 @@ Both adapters follow this contract: is `true`, process environment is not consulted at all — file values always win. +## Dotenv input limits + +Dotenv sources must be regular files; final symlinks and special files fail +before parsing. Each file is limited to 16 MiB. A resolution pass allows at +most 64 MiB of source bytes, 65,536 assignments, and 64 MiB of parsed names and +values across all dotenv files. Each expanded value is limited to 16 MiB. +Duplicate assignments and metadata count toward these limits before filtering. + +Expansion checks run before appending or retaining substituted values, so a +small substitution chain cannot allocate an unbounded result. Quoting, +multiline values, environment-first substitution, and precedence stay the +same. Syntax errors name the file and error category without including its +contents. Resource-limit failures abort even with `strict: false`. + ## `DOTENV_` filtering and identifier validation - Any raw key beginning with `DOTENV_` (not just the private/public key @@ -275,7 +289,7 @@ Both adapters follow this contract: ## Encrypted-value format -Values are first parsed by `dotenvy`, including its quoting and variable +Values are first parsed with dotenvy-compatible quoting and variable substitution rules. A parsed value without `encrypted:` needs no decryption and is passed through as bytes. A value that starts with `encrypted:` has the following payload base64-decoded and decrypted with `ecies` against each @@ -315,12 +329,14 @@ containing a NUL byte is a hard error closed rather than silently truncating. **`mode: "files"`.** Requires `secrets_dir`. If `verify_ramdisk` is set, -the ramdisk guard (below) runs first; otherwise `secrets_dir` merely has -to exist and be a directory. Each resolved value is written to -`/` with permissions forced to `0600` (via `fchmod` on -the file descriptor after `O_NOFOLLOW | O_CREAT | O_TRUNC` open, so the -permission is set atomically without a TOCTOU window) — unlike `env` mode, -values here may contain NUL; the file is written byte-exact. For each key +the ramdisk guard (below) runs first. The directory must exist and its complete +pathname must be protected from less-trusted replacement. Root and the +effective user are trusted owners; sticky shared parents and trusted symlink +aliases remain supported. The launcher exports the verified canonical path. +Each value is written byte-exact to a fresh exclusive 0600 inode and published +atomically as `/`. Existing handles keep the old contents; +foreign, hardlinked, symlinked, and special existing entries fail closed. +Values may contain NUL. For each key the launcher exports `_FILE` pointing at that path; if the key is also listed in `passthrough`, it is *additionally* exported as a real `=value` env var (and *that* copy is subject to the same NUL-rejection diff --git a/docs/src/unsafe-code/index.md b/docs/src/unsafe-code/index.md index 1bda367..e96b14b 100644 --- a/docs/src/unsafe-code/index.md +++ b/docs/src/unsafe-code/index.md @@ -4,7 +4,8 @@ Postmaster deliberately allows `unsafe` at the lint level (documented in `[lints.rust]` in `Cargo.toml`) because it is a syscall-boundary daemon: peer-credential checks, anti-debug hardening, signal-mask deferral, the sibling launch monitor (fork + pidfd/kqueue liveness), and the systemd -socket-activation contract cannot be expressed in safe Rust. +socket-activation contract cannot be expressed in safe Rust. Darwin extended +ACL access uses narrow libc bindings as well. This section documents every approved site. ## Policy @@ -22,11 +23,13 @@ Every `unsafe` block requires: | Location | Platform | Purpose | Page | |----------|----------|---------|------| -| `launcher.rs` (TerminationGuard: block/restore_mask/Drop) | macOS, Linux | Defer termination signals across the plaintext-write window; the fork-child monitor inherits the mask for life | [signal-deferral](./signal-deferral.md) | +| `launcher.rs` (TerminationGuard: block/block_input/input_pending/restore_mask/Drop) | macOS, Linux | Defer termination across plaintext writes and no-echo input; restore terminal settings before pending signal delivery | [signal-deferral](./signal-deferral.md) | | `launcher.rs` (fork(2)) | macOS, Linux | Fork the sibling monitor before exec — the single libc FFI call on Linux (doctrine exception) | [monitor](./monitor.md) | | `monitor.rs` (signal mask/wait ops, pidfd+poll / kqueue, `_exit`/`exit_group`, raw stderr write) | macOS, Linux | Sibling monitor: synchronous stop consumption, liveness watch, cleanup on every death path | [monitor](./monitor.md) | | `server.rs` (`peer_euid`) | macOS | Peer credential check via `getpeereid(2)` | [macos-libc-boundary](./macos-libc-boundary.md) | | `server.rs` (`harden_process`) | macOS, release only | `PT_DENY_ATTACH` anti-debug hardening | [macos-libc-boundary](./macos-libc-boundary.md) | +| `secret_files/acl.rs` | macOS | Inspect directory ACL grants and clear new private-file ACLs | [macos-libc-boundary](./macos-libc-boundary.md#extended-acls) | +| `test_util/pty.rs` | all, test-only | Create and own pseudo-terminal descriptors for input restoration tests | [signal-deferral](./signal-deferral.md#tests) | | `server.rs` (socket activation) | Linux | `UnixListener::from_raw_fd` on systemd-inherited sockets | [systemd-fd-ownership](./systemd-fd-ownership.md) | | `keys/source.rs`, `keys/env.rs`, `keys/provisioning/mod.rs` (test modules) | all, test-only | `set_var`/`remove_var` (unsafe on edition 2024) | [test-env-mutation](./test-env-mutation.md) | diff --git a/docs/src/unsafe-code/macos-libc-boundary.md b/docs/src/unsafe-code/macos-libc-boundary.md index 2505e0c..dcb1384 100644 --- a/docs/src/unsafe-code/macos-libc-boundary.md +++ b/docs/src/unsafe-code/macos-libc-boundary.md @@ -2,8 +2,9 @@ On Darwin the stable kernel ABI *is* libc, so these calls have no raw-syscall route (contrast with Linux, where rustix's `linux_raw` -backend avoids libc FFI except `fork(2)`). This page covers the daemon's -two sites; the launcher's signal-mask guard and the sibling monitor's +backend avoids libc FFI except `fork(2)`). This page covers peer checks, anti- +debug hardening, and extended ACLs; the launcher's signal-mask guard and the +sibling monitor's kqueue/signal ops share the same justification and live on their own pages ([signal deferral](./signal-deferral.md), [sibling launch monitor](./monitor.md)). @@ -66,3 +67,21 @@ macOS. `PT_DENY_ATTACH` cannot be meaningfully unit-tested (success means a subsequent attach fails); its release-only gating is pinned by `debug-assertions = false` in `[profile.release]` and verified by release-profile clippy in the standard battery. + +## Extended ACLs + +`src/secret_files/acl.rs` binds the Darwin ACL and membership APIs that rustix +does not expose. Mode bits alone do not restrict extended ACL grants on macOS. +Directory checks reject grants to principals other than root or the effective +user that permit replacement or inherited reads of fresh files. Fresh private +files have their ACLs cleared before plaintext writes. + +The wrapper owns each ACL and qualifier allocation and frees it once with +`acl_free`. Entry pointers borrow the live ACL; output pointers have initialized +storage and stay valid through each call. Qualifiers use Darwin's fixed +16-byte UUID layout and are compared with UUIDs resolved for trusted users. +Descriptor borrows keep the file open throughout each call. Failures return +errors before plaintext is written. + +Native tests install replacement and inheritance grants in private fixtures, +verify rejection, and check that published files have no extended entries. diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md index eef0b4a..f536770 100644 --- a/docs/src/unsafe-code/signal-deferral.md +++ b/docs/src/unsafe-code/signal-deferral.md @@ -9,7 +9,7 @@ ```text src/launcher.rs — struct TerminationGuard (macOS and Linux legs) -Blocks: block() (sigmask), restore_mask() (sigmask), Drop (restore) +Blocks: block()/block_input() (sigmask), input_pending(), restore_mask(), Drop ``` ## Purpose @@ -29,19 +29,14 @@ mask and keeps it for life** — the fork-child's guard is never dropped running no destructors). The parent calls `restore_mask()` before `execvp` so the service starts with a clean signal state. -The guard previously also carried a sigaction flag-recording handler -(`disarm`/`recorded`) and a second pre-exec gate to close the -check/exec race. Both were **retired with the sibling-monitor -design**: the monitor owns stop semantics on every death path, so no -async handler is needed anywhere and the handler's forever-purity -constraint is gone with it. What remains — `block()` and -`restore_mask()` — is what this page covers. - -The guard became real on Linux with the same change: the fork+monitor -model runs there too, and the blocked mask is the monitor's inheritance. -The Linux leg uses rustix's raw `rt_sigprocmask` (`runtime` module — the -experimental API; see the monitor page for the doctrinal discussion), so -the Linux exec path adds no libc signal FFI. +Setup reuses the guard while reading secrets from a terminal. `block_input()` +also blocks SIGTSTP, so suspension cannot hand back a terminal with echo disabled. +Terminal reads use nonblocking stdin, including buffered and noncanonical +input. The loop checks pending signals while polling, restores terminal +settings and stdin flags, then restores the saved signal mask. Setup refuses +terminal input if +masking fails. Redirected input keeps stdin's existing buffer and normal signal +behavior. Linux uses rustix's raw signal APIs; Darwin uses libc. ## Why Unsafe @@ -60,7 +55,7 @@ holds only standard signals no libc reserves. | Invalid `sigset_t` | Uninitialized set passed to the mask call | `zeroed()` (valid empty representation) then `sigemptyset` on Darwin; `KernelSigSet::empty()` on Linux | | Dangling pointers | set/old must outlive each call | Locals live for the full block; no pointers escape | | Thread-model mismatch | `sigprocmask` is unspecified in multithreaded processes | `pthread_sigmask` form on Darwin; on Linux the launcher is single-threaded at this point (worker threads exist only in serve mode) | -| libc-reserved signals | Masking a signal a libc reserves is UB (rustix `runtime` safety note) | The set holds only TERM/INT/HUP/QUIT — none reserved (glibc reserves 32/33) | +| libc-reserved signals | Masking a signal a libc reserves is UB (rustix `runtime` safety note) | The set holds only TERM/INT/HUP/QUIT, plus TSTP for input — none reserved (glibc reserves 32/33) | | Mask clobber | Restoring a mask never captured | Both legs are Option-shaped and store `None` on block failure (logged); restore then no-ops | | Mask leak to the service | Service inheriting blocked termination signals | Mask restored before `execvp` on every path (explicit + `Drop` on early-Err) — the monitor *wants* the mask and is the only inheritor | @@ -85,3 +80,10 @@ The guard's contract is exercised end-to-end by the monitor tests mirroring production) and by the exec integration suites (`tests/exec_check.rs`, `tests/exec_conformance/`). The retired flag-handler test was removed with the handler. + +Input tests use pseudo-terminals to check hidden single-line and multiline +input, read failures, and terminal restoration. Real setup subprocesses cover +initial files, forced rotation, redirected input, and SIGTERM during input. +The test-only `openpty` call receives valid output pointers and null optional +settings; each returned descriptor transfers exactly once into an owning +`File`. The harness kills and waits for its child on teardown. diff --git a/licenses/dotenvy-MIT.txt b/licenses/dotenvy-MIT.txt new file mode 100644 index 0000000..11e157d --- /dev/null +++ b/licenses/dotenvy-MIT.txt @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +Copyright (c) 2014 Santiago Lapresta and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 4a10605..462728d 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -45,6 +45,10 @@ pub struct Entry { pub env_file: PathBuf, /// Which key inside it to serve. pub key: String, + /// Trusted SHA-256 hashes of the exact dotenv file bytes, as 64-digit hex strings. + /// A hash must match before parsing, interpolation or decryption. + #[serde(deserialize_with = "deserialize_env_file_hashes")] + pub env_file_sha256: Vec<[u8; 32]>, /// Additionally allow this (non-root) user to fetch the credential. /// Used by the darwin module, where consumers are launchd daemons /// connecting as their own service user rather than uid 0 (root). @@ -52,6 +56,22 @@ pub struct Entry { pub peer_user: Option, } +fn deserialize_env_file_hashes<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + Vec::::deserialize(deserializer)? + .into_iter() + .map(|value| { + let mut hash = [0; 32]; + hex::decode_to_slice(value, &mut hash).map_err(|_| { + serde::de::Error::custom("env_file_sha256 requires 64-digit hex hashes") + })?; + Ok(hash) + }) + .collect() +} + /// Parsed command-line arguments for the `serve` invocation. #[derive(Debug)] pub struct Args { @@ -468,7 +488,7 @@ mod tests { let raw = serde_json::json!({ "keys": {"credential": "postmaster-keys"}, "credentials": { - "/run/cred.sock": {"env_file": "/nix/store/x/.env", "key": "DB_URL", "peer_user": "_www"} + "/run/cred.sock": {"env_file": "/nix/store/x/.env", "key": "DB_URL", "env_file_sha256": ["0000000000000000000000000000000000000000000000000000000000000000"], "peer_user": "_www"} } }); serde_json::from_value::(raw).unwrap(); diff --git a/src/keys/dotenv.rs b/src/keys/dotenv.rs new file mode 100644 index 0000000..8dfffc4 --- /dev/null +++ b/src/keys/dotenv.rs @@ -0,0 +1,583 @@ +//! Dotenv syntax from dotenvy 0.15.7 with bounded expansion and redacted errors. +//! MIT notice: `licenses/dotenvy-MIT.txt`. + +use std::io::{BufRead, BufReader}; +use std::path::Path; + +use std::collections::HashMap; +use std::env; + +use zeroize::Zeroizing; + +type Result = std::result::Result; +type Error = &'static str; +const INVALID: &str = "invalid dotenv syntax"; +const LIMIT: &str = "dotenv resource limit exceeded"; +const MAX_VALUE_BYTES: usize = 16 * 1024 * 1024; +const MAX_PARSED_BYTES: usize = 64 * 1024 * 1024; +const MAX_ENTRIES: usize = 65_536; + +// for readability's sake +type ParsedLine = Result)>>; + +fn parse_line( + line: &str, + substitution_data: &mut HashMap>>, + budget: &mut Budget, +) -> ParsedLine { + let mut parser = LineParser::new(line, substitution_data, budget); + parser.parse_line() +} + +struct LineParser<'parse> { + substitution_data: &'parse mut HashMap>>, + line: &'parse str, + budget: &'parse mut Budget, +} + +impl<'parse> LineParser<'parse> { + fn new( + line: &'parse str, + substitution_data: &'parse mut HashMap>>, + budget: &'parse mut Budget, + ) -> LineParser<'parse> { + LineParser { + substitution_data, + line: line.trim_end(), // we don’t want trailing whitespace + budget, + } + } + + fn err(&self) -> Error { + INVALID + } + + fn parse_line(&mut self) -> ParsedLine { + self.skip_whitespace(); + // if its an empty line or a comment, skip it + if self.line.is_empty() || self.line.starts_with('#') { + return Ok(None); + } + + self.budget.entry()?; + let mut key = self.parse_key()?; + self.skip_whitespace(); + + // export can be either an optional prefix or a key itself + if key == "export" { + // here we check for an optional `=`, below we throw directly when it’s not found. + if self.expect_equal().is_err() { + key = self.parse_key()?; + self.skip_whitespace(); + self.expect_equal()?; + } + } else { + self.expect_equal()?; + } + self.skip_whitespace(); + + if self.line.is_empty() || self.line.starts_with('#') { + self.budget.retain(key.len())?; + self.substitution_data.insert(key.clone(), None); + return Ok(Some((key, Zeroizing::new(String::new())))); + } + + let parsed_value = parse_value(self.line, self.substitution_data)?; + self.budget.retain(key.len() + parsed_value.len())?; + self.substitution_data + .insert(key.clone(), Some(parsed_value.clone())); + + Ok(Some((key, parsed_value))) + } + + fn parse_key(&mut self) -> Result { + if !self + .line + .starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') + { + return Err(self.err()); + } + let index = match self + .line + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '.')) + { + Some(index) => index, + None => self.line.len(), + }; + let key = String::from(&self.line[..index]); + self.line = &self.line[index..]; + Ok(key) + } + + fn expect_equal(&mut self) -> Result<()> { + if !self.line.starts_with('=') { + return Err(self.err()); + } + self.line = &self.line[1..]; + Ok(()) + } + + fn skip_whitespace(&mut self) { + if let Some(index) = self.line.find(|c: char| !c.is_whitespace()) { + self.line = &self.line[index..]; + } else { + self.line = ""; + } + } +} + +#[derive(Eq, PartialEq)] +enum SubstitutionMode { + None, + Block, + EscapedBlock, +} + +fn parse_value( + input: &str, + substitution_data: &mut HashMap>>, +) -> Result> { + let mut strong_quote = false; // ' + let mut weak_quote = false; // " + let mut escaped = false; + let mut expecting_end = false; + + //FIXME can this be done without yet another allocation per line? + let mut output = Zeroizing::new(String::new()); + + let mut substitution_mode = SubstitutionMode::None; + let mut substitution_name = String::new(); + + for c in input.chars() { + //the regex _should_ already trim whitespace off the end + //expecting_end is meant to permit: k=v #comment + //without affecting: k=v#comment + //and throwing on: k=v w + if expecting_end { + if c == ' ' || c == '\t' { + continue; + } else if c == '#' { + break; + } else { + return Err(INVALID); + } + } else if escaped { + //TODO I tried handling literal \r but various issues + //imo not worth worrying about until there's a use case + //(actually handling backslash 0x10 would be a whole other matter) + //then there's \v \f bell hex... etc + match c { + '\\' | '\'' | '"' | '$' | ' ' => push_char(&mut output, c)?, + 'n' => push_char(&mut output, '\n')?, // handle \n case + _ => { + return Err(INVALID); + } + } + + escaped = false; + } else if strong_quote { + if c == '\'' { + strong_quote = false; + } else { + push_char(&mut output, c)?; + } + } else if substitution_mode != SubstitutionMode::None { + if c.is_alphanumeric() { + substitution_name.push(c); + } else { + match substitution_mode { + SubstitutionMode::None => unreachable!(), + SubstitutionMode::Block => { + if c == '{' && substitution_name.is_empty() { + substitution_mode = SubstitutionMode::EscapedBlock; + } else { + apply_substitution(substitution_data, &substitution_name, &mut output)?; + substitution_name.clear(); + if c == '$' { + substitution_mode = if !strong_quote && !escaped { + SubstitutionMode::Block + } else { + SubstitutionMode::None + } + } else { + substitution_mode = SubstitutionMode::None; + push_char(&mut output, c)?; + } + } + } + SubstitutionMode::EscapedBlock => { + if c == '}' { + substitution_mode = SubstitutionMode::None; + apply_substitution(substitution_data, &substitution_name, &mut output)?; + substitution_name.clear(); + } else { + substitution_name.push(c); + } + } + } + } + } else if c == '$' { + substitution_mode = if !strong_quote && !escaped { + SubstitutionMode::Block + } else { + SubstitutionMode::None + } + } else if weak_quote { + if c == '"' { + weak_quote = false; + } else if c == '\\' { + escaped = true; + } else { + push_char(&mut output, c)?; + } + } else if c == '\'' { + strong_quote = true; + } else if c == '"' { + weak_quote = true; + } else if c == '\\' { + escaped = true; + } else if c == ' ' || c == '\t' { + expecting_end = true; + } else { + push_char(&mut output, c)?; + } + } + + //XXX also fail if escaped? or... + if substitution_mode == SubstitutionMode::EscapedBlock || strong_quote || weak_quote { + Err(INVALID) + } else { + apply_substitution(substitution_data, &substitution_name, &mut output)?; + Ok(output) + } +} + +fn apply_substitution( + substitution_data: &HashMap>>, + substitution_name: &str, + output: &mut String, +) -> Result<()> { + if let Ok(value) = env::var(substitution_name) { + let value = Zeroizing::new(value); + push_str(output, &value)?; + } else if let Some(Some(value)) = substitution_data.get(substitution_name) { + push_str(output, value)?; + } + Ok(()) +} + +fn push_str(output: &mut String, value: &str) -> Result<()> { + if value.len() > MAX_VALUE_BYTES.saturating_sub(output.len()) { + return Err(LIMIT); + } + output.push_str(value); + Ok(()) +} + +fn push_char(output: &mut String, value: char) -> Result<()> { + let mut bytes = [0; 4]; + push_str(output, value.encode_utf8(&mut bytes)) +} +struct QuotedLines { + buf: B, +} + +enum ParseState { + Complete, + Escape, + StrongOpen, + StrongOpenEscape, + WeakOpen, + WeakOpenEscape, + Comment, + WhiteSpace, +} + +fn eval_end_state(prev_state: ParseState, buf: &str) -> (usize, ParseState) { + let mut cur_state = prev_state; + let mut cur_pos: usize = 0; + + for (pos, c) in buf.char_indices() { + cur_pos = pos; + cur_state = match cur_state { + ParseState::WhiteSpace => match c { + '#' => return (cur_pos, ParseState::Comment), + '\\' => ParseState::Escape, + '"' => ParseState::WeakOpen, + '\'' => ParseState::StrongOpen, + _ => ParseState::Complete, + }, + ParseState::Escape => ParseState::Complete, + ParseState::Complete => match c { + c if c.is_whitespace() && c != '\n' && c != '\r' => ParseState::WhiteSpace, + '\\' => ParseState::Escape, + '"' => ParseState::WeakOpen, + '\'' => ParseState::StrongOpen, + _ => ParseState::Complete, + }, + ParseState::WeakOpen => match c { + '\\' => ParseState::WeakOpenEscape, + '"' => ParseState::Complete, + _ => ParseState::WeakOpen, + }, + ParseState::WeakOpenEscape => ParseState::WeakOpen, + ParseState::StrongOpen => match c { + '\\' => ParseState::StrongOpenEscape, + '\'' => ParseState::Complete, + _ => ParseState::StrongOpen, + }, + ParseState::StrongOpenEscape => ParseState::StrongOpen, + // Comments last the entire line. + ParseState::Comment => return (cur_pos, ParseState::Comment), + }; + } + (cur_pos, cur_state) +} + +impl Iterator for QuotedLines { + type Item = Result>; + + fn next(&mut self) -> Option>> { + let mut buf = Zeroizing::new(String::new()); + let mut cur_state = ParseState::Complete; + let mut buf_pos; + let mut cur_pos; + loop { + buf_pos = buf.len(); + match self.buf.read_line(&mut buf) { + Ok(0) => match cur_state { + ParseState::Complete => return None, + _ => { + return Some(Err(INVALID)); + } + }, + Ok(_n) => { + // Skip lines which start with a # before iteration + // This optimizes parsing a bit. + if buf.trim_start().starts_with('#') { + return Some(Ok(Zeroizing::new(String::new()))); + } + let result = eval_end_state(cur_state, &buf[buf_pos..]); + cur_pos = result.0; + cur_state = result.1; + + match cur_state { + ParseState::Complete => { + if buf.ends_with('\n') { + buf.pop(); + if buf.ends_with('\r') { + buf.pop(); + } + } + return Some(Ok(buf)); + } + ParseState::Escape + | ParseState::StrongOpen + | ParseState::StrongOpenEscape + | ParseState::WeakOpen + | ParseState::WeakOpenEscape + | ParseState::WhiteSpace => {} + ParseState::Comment => { + buf.truncate(buf_pos + cur_pos); + return Some(Ok(buf)); + } + } + } + Err(_) => return Some(Err(INVALID)), + } + } + } +} + +/// Cumulative work across every dotenv file, including shadowed and metadata entries. +#[derive(Default)] +pub(super) struct Budget { + entries: usize, + bytes: usize, + input_bytes: usize, +} + +impl Budget { + fn entry(&mut self) -> Result<()> { + if self.entries == MAX_ENTRIES { + return Err(LIMIT); + } + self.entries += 1; + Ok(()) + } + + fn retain(&mut self, bytes: usize) -> Result<()> { + if bytes > MAX_PARSED_BYTES.saturating_sub(self.bytes) { + return Err(LIMIT); + } + self.bytes += bytes; + Ok(()) + } +} + +/// Read a regular, non-symlink file with a byte cap, then parse with bounded substitutions. +pub(super) fn read( + path: &Path, + budget: &mut Budget, + authorized: Option<&[[u8; 32]]>, +) -> std::result::Result)>, String> { + use rustix::fs::{FileType, Mode, OFlags, fstat, open}; + let fd = open( + path, + OFlags::RDONLY | OFlags::NONBLOCK | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::empty(), + ) + .map_err(|e| format!("{}: {e} (refusing to follow a symlink)", path.display()))?; + let stat = fstat(&fd).map_err(|e| format!("{}: stat: {e}", path.display()))?; + if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile { + return Err(format!("{}: not a regular file", path.display())); + } + let raw = Zeroizing::new(crate::server::read_capped(std::fs::File::from(fd), path)?); + if raw.len() > MAX_PARSED_BYTES.saturating_sub(budget.input_bytes) { + return Err(format!("{}: {LIMIT}", path.display())); + } + budget.input_bytes += raw.len(); + if let Some(authorized) = authorized { + use sha2::Digest as _; + let hash: [u8; 32] = sha2::Sha256::digest(&raw).into(); + if !authorized.contains(&hash) { + return Err(format!( + "{}: dotenv source is not authorized", + path.display() + )); + } + } + parse(&raw, budget).map_err(|e| format!("{}: {e}", path.display())) +} + +fn parse(raw: &[u8], budget: &mut Budget) -> Result)>> { + let lines = QuotedLines { + buf: BufReader::new(raw), + }; + let mut substitutions = HashMap::new(); + let mut values = Vec::new(); + for line in lines { + if let Some(pair) = parse_line(&line?, &mut substitutions, budget)? { + values.push(pair); + } + } + Ok(values) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic)] +mod tests { + use super::*; + + #[test] + fn matches_dotenv_grammar_and_substitution() { + let _guard = crate::test_util::ENV_LOCK.lock().unwrap(); + let corpus = [ + "", + "# comment\n", + "A=\n", + "export A=one\n", + "export=one\n", + "A=one#two\n", + "A=one # two\n", + "A='one\ntwo'\n", + "A=\"one\\ntwo\"\n", + "A=one\\ two\n", + "A='x'\"y\"z\n", + "A=x\nB=${A}${A}\n", + "A=x\nA=y\nB=$A\n", + "A=x\nB=$A-$A\n", + "A=x\nB=\"${A}z\"\n", + "A=x\nB='${A}'\n", + "A=x\nB=\\$A\n", + "A=x\nB=${MISSING}\n", + "A=\nB=${A}\n", + "A=x\nB=$A$A\n", + "A=x\nB=${A}\nC=${B}\n", + "A=\"unterminated", + "A=one two\n", + "A='unterminated", + "A=\"bad\\q\"\n", + "A=${oops\n", + "1A=x\n", + "A.B=x\n", + "A=x\r\nB=y\r\n", + "\u{feff}A=x\n", + "A=x\\\n", + "A=\"x\n# inside\ny\"\n", + "A=\"x\" trailing\n", + "A=\"λ\"\n", + "A=${PATH}\n", + "A='x\\'\n", + "A=x \nB=y\n", + ]; + for input in corpus { + let expected = dotenvy::from_read_iter(input.as_bytes()) + .collect::, _>>(); + let actual = parse(input.as_bytes(), &mut Budget::default()); + match (expected, actual) { + (Ok(expected), Ok(actual)) => assert_eq!( + expected, + actual + .into_iter() + .map(|(k, v)| (k, (*v).clone())) + .collect::>(), + "{input:?}" + ), + (Err(_), Err(INVALID)) => {} + _ => panic!("parser outcome differs for {input:?}"), + } + } + } + + #[test] + fn bounds_expansion_and_counts_shadowed_metadata() { + let mut input = "A0=x\n".to_string(); + for i in 1..40 { + input.push_str(&format!("A{i}=${{A{}}}${{A{}}}\n", i - 1, i - 1)); + } + assert!(input.len() < 2048); + assert_eq!( + parse(input.as_bytes(), &mut Budget::default()).unwrap_err(), + LIMIT + ); + let input = "DOTENV_METADATA=\n".repeat(MAX_ENTRIES + 1); + assert_eq!( + parse(input.as_bytes(), &mut Budget::default()).unwrap_err(), + LIMIT + ); + let mut budget = Budget { + bytes: MAX_PARSED_BYTES, + ..Budget::default() + }; + assert_eq!(parse(b"A=x\n", &mut budget).unwrap_err(), LIMIT); + } + + #[test] + fn rejects_special_and_oversized_sources() { + let dir = crate::test_util::temp_dir::TestDir::new("dotenv-source"); + let fifo = dir.join("fifo"); + assert!( + std::process::Command::new("mkfifo") + .arg(&fifo) + .status() + .unwrap() + .success() + ); + assert!( + read(&fifo, &mut Budget::default(), None) + .unwrap_err() + .contains("not a regular file") + ); + let path = dir.join("large"); + std::fs::File::create(&path) + .unwrap() + .set_len(16 * 1024 * 1024 + 1) + .unwrap(); + assert!( + read(&path, &mut Budget::default(), None) + .unwrap_err() + .contains("size cap") + ); + } +} diff --git a/src/keys/load.rs b/src/keys/load.rs index 1e60f4f..87ebe83 100644 --- a/src/keys/load.rs +++ b/src/keys/load.rs @@ -110,12 +110,8 @@ mod tests { #[test] fn load_rejects_world_readable_keys_file() { use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir(); - let path = dir.join(format!( - "postmaster-test-keys-worldread-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); + let dir = crate::test_util::temp_dir::TestDir::new("load"); + let path = dir.join("fixture"); { let mut f = std::fs::File::create(&path).unwrap(); writeln!(f, "DOTENV_PRIVATE_KEY={}", "11".repeat(32)).unwrap(); @@ -132,12 +128,8 @@ mod tests { #[test] fn load_rejects_group_readable_keys_file() { use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir(); - let path = dir.join(format!( - "postmaster-test-keys-groupread-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); + let dir = crate::test_util::temp_dir::TestDir::new("load"); + let path = dir.join("fixture"); { let mut f = std::fs::File::create(&path).unwrap(); writeln!(f, "DOTENV_PRIVATE_KEY={}", "11".repeat(32)).unwrap(); @@ -180,12 +172,8 @@ mod tests { #[test] fn load_accepts_0400_keys_file() { use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir(); - let path = dir.join(format!( - "postmaster-test-keys-0400-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); + let dir = crate::test_util::temp_dir::TestDir::new("load"); + let path = dir.join("fixture"); { let mut f = std::fs::File::create(&path).unwrap(); writeln!(f, "DOTENV_PRIVATE_KEY={}", "11".repeat(32)).unwrap(); diff --git a/src/keys/mod.rs b/src/keys/mod.rs index e960729..3a7aed0 100644 --- a/src/keys/mod.rs +++ b/src/keys/mod.rs @@ -17,6 +17,7 @@ use zeroize::{Zeroize, Zeroizing}; use crate::adapter::KeyNaming; use crate::config::Entry; +mod dotenv; mod env; #[cfg(target_os = "macos")] mod keychain; @@ -232,25 +233,12 @@ pub fn resolve( ring: &KeyRing, naming: KeyNaming, ) -> Result>, String> { - // O_NOFOLLOW on the ciphertext open (audit 2026-08-02 A13): refuse - // to read through a planted symlink. - let fd = rustix::fs::open( - &entry.env_file, - rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC, - rustix::fs::Mode::empty(), - ) - .map_err(|e| { - format!( - "{}: {e} (refusing to follow a symlink)", - entry.env_file.display() - ) - })?; - let iter = dotenvy::from_read_iter(std::fs::File::from(fd)); + let mut budget = dotenv::Budget::default(); + let iter = dotenv::read(&entry.env_file, &mut budget, Some(&entry.env_file_sha256))?; // Last assignment wins, matching dotenv semantics within one file. let mut found: Option> = None; for item in iter { - let (k, v) = item.map_err(|e| format!("{}: {e}", entry.env_file.display()))?; - let v = Zeroizing::new(v); + let (k, v) = item; if k == entry.key { found = Some(v); } @@ -312,21 +300,13 @@ pub fn resolve_all( let metadata_prefix = naming.metadata_prefix(); let mut order: Vec = Vec::new(); let mut merged: HashMap)> = HashMap::new(); + let mut budget = dotenv::Budget::default(); for f in files { - // O_NOFOLLOW on the ciphertext open (audit 2026-08-02 A13): - // refuse to read through a planted symlink. - let fd = rustix::fs::open( - f, - rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC, - rustix::fs::Mode::empty(), - ) - .map_err(|e| format!("{}: {e} (refusing to follow a symlink)", f.display()))?; - let iter = dotenvy::from_read_iter(std::fs::File::from(fd)); + let iter = dotenv::read(f, &mut budget, None)?; let mut file_vals: HashMap> = HashMap::new(); let mut file_order: Vec = Vec::new(); for item in iter { - let (k, v) = item.map_err(|e| format!("{}: {e}", f.display()))?; - let v = Zeroizing::new(v); + let (k, v) = item; if let Some(prefix) = metadata_prefix && k.starts_with(prefix) { @@ -412,12 +392,8 @@ pub mod tests { /// Shared with the `load` submodule's tests. pub fn with_temp_keys(content: &str, f: impl FnOnce(&Path)) { use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir(); - let path = dir.join(format!( - "postmaster-test-keys-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); + let dir = crate::test_util::temp_dir::TestDir::new("mod"); + let path = dir.join("fixture"); { let mut f = std::fs::File::create(&path).unwrap(); writeln!(f, "{}", content).unwrap(); @@ -430,22 +406,121 @@ pub mod tests { } /// Shared with the `load` submodule's tests. - pub fn tdir(tag: &str) -> std::path::PathBuf { - let d = std::env::temp_dir().join(format!("pm-keys-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d + pub fn tdir(tag: &str) -> crate::test_util::temp_dir::TestDir { + crate::test_util::temp_dir::TestDir::new(tag) + } + + #[test] + fn malformed_dotenv_diagnostics_do_not_contain_values() { + use sha2::Digest as _; + let dir = tdir("redaction"); + let path = dir.join(".env"); + let ring = KeyRing(HashMap::new()); + for value in [ + "\"PRIVATE_SENTINEL", + "\"PRIVATE_SENTINEL\" trailing", + "\"PRIVATE_SENTINEL\\q\"", + "\"PRIVATE_SENTINEL\nsecond", + ] { + std::fs::write(&path, format!("SECRET={value}\n")).unwrap(); + let entry = Entry { + env_file: path.clone(), + key: "SECRET".into(), + env_file_sha256: vec![sha2::Sha256::digest(std::fs::read(&path).unwrap()).into()], + peer_user: None, + }; + let error = resolve(&entry, &ring, KeyNaming::Env).unwrap_err(); + assert!(!error.contains("PRIVATE_SENTINEL")); + assert!(error.contains(path.to_str().unwrap())); + for strict in [false, true] { + let error = resolve_all( + std::slice::from_ref(&path), + &ring, + false, + strict, + &|_| false, + KeyNaming::Env, + ) + .unwrap_err(); + assert!(!error.contains("PRIVATE_SENTINEL")); + assert!(error.contains(path.to_str().unwrap())); + } + } + } + + #[test] + fn daemon_authorizes_source_before_interpolation_or_decryption() { + use sha2::Digest as _; + let dir = tdir("authorized"); + let path = dir.join(".env"); + let (sk, pk) = ecies::utils::generate_keypair(); + let ring = KeyRing::from_pairs( + [( + "DOTENV_PRIVATE_KEY".into(), + Zeroizing::new(format!( + "{},{}", + "11".repeat(32), + hex::encode(sk.serialize()) + )), + )], + &[KeyNaming::Env], + ) + .unwrap(); + let allowed = ecies::encrypt(&pk.serialize(), b"allowed").unwrap(); + let foreign = ecies::encrypt(&pk.serialize(), b"foreign").unwrap(); + let encoded = BASE64.encode(&allowed); + let wrapped = encoded + .as_bytes() + .chunks(7) + .map(|c| std::str::from_utf8(c).unwrap()) + .collect::>() + .join(" \n"); + std::fs::write( + &path, + format!("SECRET=discarded\nSOURCE='encrypted:{wrapped}'\nSECRET=${{SOURCE}}\n"), + ) + .unwrap(); + let mut entry = Entry { + env_file: path.clone(), + key: "SECRET".into(), + env_file_sha256: vec![sha2::Sha256::digest(std::fs::read(&path).unwrap()).into()], + peer_user: None, + }; + assert_eq!( + &*resolve(&entry, &ring, KeyNaming::Env).unwrap(), + b"allowed" + ); + // Both authentic foreign ciphertext and plaintext substitutions are unauthorized. + for raw in [ + format!("SECRET='encrypted:{}'\n", BASE64.encode(&foreign)), + "SECRET=${PATH}\n".into(), + "SECRET=chosen\n".into(), + ] { + std::fs::write(&path, raw).unwrap(); + assert!( + resolve(&entry, &ring, KeyNaming::Env) + .unwrap_err() + .contains("not authorized") + ); + } + entry + .env_file_sha256 + .push(sha2::Sha256::digest(std::fs::read(&path).unwrap()).into()); + assert_eq!(&*resolve(&entry, &ring, KeyNaming::Env).unwrap(), b"chosen"); + entry.env_file_sha256.clear(); + assert!( + resolve(&entry, &ring, KeyNaming::Env) + .unwrap_err() + .contains("not authorized") + ); } #[test] fn resolve_plaintext_passthrough_with_empty_ring() { + use sha2::Digest as _; // Create a real .env file with a plaintext value (simulating --plain) - let env_dir = std::env::temp_dir(); - let env_path = env_dir.join(format!( - "postmaster-test-env-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); + let env_dir = crate::test_util::temp_dir::TestDir::new("mod"); + let env_path = env_dir.join("fixture"); { let mut f = std::fs::File::create(&env_path).unwrap(); writeln!(f, "PLAIN=hello-world").unwrap(); @@ -454,6 +529,7 @@ pub mod tests { let entry = Entry { env_file: env_path.clone(), key: "PLAIN".to_string(), + env_file_sha256: vec![sha2::Sha256::digest(std::fs::read(&env_path).unwrap()).into()], peer_user: None, }; // Ring can be empty for plaintext path diff --git a/src/keys/provisioning/cleanup.rs b/src/keys/provisioning/cleanup.rs index 4dc7bde..c91a46c 100644 --- a/src/keys/provisioning/cleanup.rs +++ b/src/keys/provisioning/cleanup.rs @@ -147,9 +147,7 @@ mod tests { #[test] fn cleanup_removes_all_files_from_secrets_dir() { - let dir = std::env::temp_dir().join(format!("pm-keyprov-cleanup-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); + let dir = crate::test_util::temp_dir::TestDir::new("cleanup"); // cleanup requires a postmaster-managed (owner-only) dir // (audit 2026-08-02 A19); match real deployments. use std::os::unix::fs::PermissionsExt; @@ -185,9 +183,7 @@ mod tests { // audit 2026-08-02 A19: a non-empty dir without the sentinel was // never written by postmaster; cleanup must refuse to bulk-delete // there (foreign files could be present). - let dir = std::env::temp_dir().join(format!("pm-keyprov-unmanaged-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); + let dir = crate::test_util::temp_dir::TestDir::new("cleanup"); fs::write(dir.join("FOREIGN"), b"not-ours").unwrap(); let cfg_path = dir.join("exec.json"); fs::write( @@ -207,9 +203,7 @@ mod tests { #[test] fn cleanup_nonexistent_dir_is_ok() { - let dir = std::env::temp_dir().join(format!("pm-keyprov-missing-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); + let dir = crate::test_util::temp_dir::TestDir::new("cleanup"); let cfg_path = dir.join("exec.json"); fs::write( &cfg_path, @@ -231,9 +225,7 @@ mod tests { return; } use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir().join(format!("pm-keyprov-partial-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); + let dir = crate::test_util::temp_dir::TestDir::new("cleanup"); fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); fs::write(dir.join("KEY_A"), b"secret-a").unwrap(); fs::write(dir.join(MANAGED_SENTINEL), b"").unwrap(); @@ -269,9 +261,7 @@ mod tests { #[test] fn finish_cleanup_removes_sentinel_only_without_failures() { use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir().join(format!("pm-keyprov-finish-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); + let dir = crate::test_util::temp_dir::TestDir::new("cleanup"); fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); fs::write(dir.join(MANAGED_SENTINEL), b"").unwrap(); let dir_fd = open_secrets_dir(&dir).unwrap(); diff --git a/src/keys/provisioning/input.rs b/src/keys/provisioning/input.rs new file mode 100644 index 0000000..15e80b0 --- /dev/null +++ b/src/keys/provisioning/input.rs @@ -0,0 +1,202 @@ +//! Secret stdin input with terminal echo suppressed and restored before signal delivery. + +use std::io::{BufRead as _, IsTerminal as _, Read as _}; + +use rustix::termios::{LocalModes, OptionalActions, Termios, tcgetattr, tcsetattr}; +use zeroize::Zeroizing; + +struct EchoGuard { + terminal: Option, + flags: Option, +} + +impl EchoGuard { + fn restore(&mut self) -> Result<(), String> { + let terminal = if let Some(original) = &self.terminal { + tcsetattr(std::io::stdin(), OptionalActions::Now, original) + .map_err(|e| format!("cannot restore terminal settings: {e}")) + } else { + Ok(()) + }; + if terminal.is_ok() { + self.terminal = None; + } + let flags = if let Some(original) = self.flags { + rustix::fs::fcntl_setfl(std::io::stdin(), original) + .map_err(|e| format!("cannot restore stdin flags: {e}")) + } else { + Ok(()) + }; + if flags.is_ok() { + self.flags = None; + } + terminal.and(flags) + } +} + +impl Drop for EchoGuard { + fn drop(&mut self) { + if let Err(e) = self.restore() { + crate::server::log(&e); + } + } +} + +/// Read one line or a multiline EOF-terminated value without terminal echo. +/// Redirected input uses stdin's existing buffer. Errors never include input values. +#[allow(clippy::print_stderr)] +pub(super) fn read_secret(prompt: &str, single_line: bool) -> Result, String> { + let stdin = std::io::stdin(); + let mut value = Zeroizing::new(String::new()); + if !stdin.is_terminal() { + eprintln!("{prompt}"); + let mut input = stdin.lock(); + if single_line { + input.read_line(&mut value) + } else { + input.read_to_string(&mut value) + } + .map_err(|_| "cannot read secret input")?; + return Ok(value); + } + // Drop order matters: restore echo before unblocking a pending termination or suspend. + let signals = crate::launcher::TerminationGuard::block_input(); + if !signals.active() { + return Err("cannot protect terminal input from interruption".into()); + } + let original = tcgetattr(&stdin).map_err(|e| format!("cannot read terminal settings: {e}"))?; + let flags = + rustix::fs::fcntl_getfl(&stdin).map_err(|e| format!("cannot read stdin flags: {e}"))?; + let mut no_echo = original.clone(); + no_echo + .local_modes + .remove(LocalModes::ECHO | LocalModes::ECHONL); + let mut echo = EchoGuard { + terminal: Some(original), + flags: Some(flags), + }; + rustix::fs::fcntl_setfl(&stdin, flags | rustix::fs::OFlags::NONBLOCK) + .map_err(|e| format!("cannot make terminal input nonblocking: {e}"))?; + tcsetattr(&stdin, OptionalActions::Now, &no_echo) + .map_err(|e| format!("cannot suppress terminal echo: {e}"))?; + eprintln!("{prompt}"); + let mut input = stdin.lock(); + loop { + if signals.input_pending()? { + return Err("secret input interrupted".into()); + } + // Read buffered data first. NONBLOCK also protects partial noncanonical lines. + match input.read_line(&mut value) { + Ok(0) => break, + Ok(_) if single_line => break, + Ok(_) => continue, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {} + Err(_) => return Err("cannot read secret input".into()), + } + let mut fds = [rustix::event::PollFd::new( + &stdin, + rustix::event::PollFlags::IN, + )]; + let timeout = rustix::event::Timespec { + tv_sec: 0, + tv_nsec: 100_000_000, + }; + match rustix::event::poll(&mut fds, Some(&timeout)) { + Ok(0) | Err(rustix::io::Errno::INTR) => continue, + Ok(_) => {} + Err(e) => return Err(format!("cannot wait for secret input: {e}")), + } + } + echo.restore()?; + Ok(value) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic)] +mod tests { + use super::*; + + #[test] + fn input_child() { + let Ok(style) = std::env::var("POSTMASTER_TEST_INPUT") else { + return; + }; + let result = read_secret("secret-ready", style == "line"); + assert!(result.is_ok(), "input failed"); + assert_eq!(result.unwrap().trim(), "PRIVATE_SENTINEL"); + } + + #[test] + fn terminal_echo_is_restored_after_success_and_error() { + for style in ["line", "multiline"] { + for outcome in ["success", "invalid-utf8"] { + let mut pty = crate::test_util::pty::TestPty::new(); + let original = tcgetattr(&pty.slave).unwrap().local_modes; + let flags = rustix::fs::fcntl_getfl(&pty.slave).unwrap(); + pty.spawn( + std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "keys::provisioning::input::tests::input_child", + "--nocapture", + ]) + .env("POSTMASTER_TEST_INPUT", style), + ); + pty.expect("secret-ready"); + assert!( + !tcgetattr(&pty.slave) + .unwrap() + .local_modes + .contains(LocalModes::ECHO) + ); + match outcome { + "success" => { + pty.send(b"PRIVATE_SENTINEL\n"); + if style == "multiline" { + pty.send(&[4]); + } + } + "invalid-utf8" => pty.send(&[0xff, b'\n']), + _ => pty.signal(rustix::process::Signal::TERM), + } + assert_eq!(pty.wait().success(), outcome == "success"); + assert_eq!(tcgetattr(&pty.slave).unwrap().local_modes, original); + // Darwin adds an internal status bit when the slave is written to. + assert_eq!( + rustix::fs::fcntl_getfl(&pty.slave) + .unwrap() + .contains(rustix::fs::OFlags::NONBLOCK), + flags.contains(rustix::fs::OFlags::NONBLOCK) + ); + assert!(!String::from_utf8_lossy(&pty.output).contains("PRIVATE_SENTINEL")); + } + } + } + + #[test] + fn noncanonical_single_line_retains_partial_buffered_input() { + let mut pty = crate::test_util::pty::TestPty::new(); + let mut mode = tcgetattr(&pty.slave).unwrap(); + mode.local_modes.remove(LocalModes::ICANON); + mode.special_codes[rustix::termios::SpecialCodeIndex::VMIN] = 1; + mode.special_codes[rustix::termios::SpecialCodeIndex::VTIME] = 0; + tcsetattr(&pty.slave, OptionalActions::Now, &mode).unwrap(); + pty.spawn( + std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "keys::provisioning::input::tests::input_child", + "--nocapture", + ]) + .env("POSTMASTER_TEST_INPUT", "line"), + ); + pty.expect("secret-ready"); + pty.send(b"PRIVATE_"); + std::thread::sleep(std::time::Duration::from_millis(100)); + pty.send(b"SENTINEL\n"); + assert!(pty.wait().success()); + assert_eq!(tcgetattr(&pty.slave).unwrap().local_modes, mode.local_modes); + assert!(!String::from_utf8_lossy(&pty.output).contains("PRIVATE_SENTINEL")); + } +} diff --git a/src/keys/provisioning/mod.rs b/src/keys/provisioning/mod.rs index ae608fd..ef43402 100644 --- a/src/keys/provisioning/mod.rs +++ b/src/keys/provisioning/mod.rs @@ -5,13 +5,13 @@ //! commands, plus the key-provisioning helpers they depend on. use std::fs; -use std::io::Read; use std::path::{Path, PathBuf}; use crate::exec_config::{ExecConfig, KeySourceSpec}; use crate::server::log; mod cleanup; +mod input; mod setup; /// The `postmaster cleanup` command, re-exported at the crate root for @@ -64,6 +64,12 @@ fn ensure_keys_dir(keys_dir: &Path, _force: bool) -> Result<(), String> { })?; let stat = rustix::fs::fstat(&dir_fd) .map_err(|e| format!("{}: fstat: {e}", keys_dir.display()))?; + if stat.st_uid != rustix::process::geteuid().as_raw() { + return Err(format!( + "{}: keys directory is owned by another user", + keys_dir.display() + )); + } let mode = rustix::fs::Mode::from_bits_truncate(stat.st_mode); if mode.intersects(rustix::fs::Mode::RWXG | rustix::fs::Mode::RWXO) { // Fix permissions if we can @@ -107,6 +113,14 @@ fn ensure_keys_dir(keys_dir: &Path, _force: bool) -> Result<(), String> { rustix::fs::Mode::empty(), ) .map_err(|e| format!("{}: cannot open keys directory: {e}", keys_dir.display()))?; + let stat = + rustix::fs::fstat(&dir_fd).map_err(|e| format!("{}: stat: {e}", keys_dir.display()))?; + if stat.st_uid != rustix::process::geteuid().as_raw() { + return Err(format!( + "{}: keys directory is owned by another user", + keys_dir.display() + )); + } rustix::fs::fchmod(&dir_fd, rustix::fs::Mode::RWXU) .map_err(|e| format!("{}: cannot set permissions: {e}", keys_dir.display()))?; log(&format!( @@ -126,142 +140,136 @@ fn ensure_keys_dir(keys_dir: &Path, _force: bool) -> Result<(), String> { /// interactive mode: unattended has no operator to paste contents. #[allow(clippy::print_stderr)] fn ensure_keys_file(path: &Path, force: bool, unattended: bool) -> Result<(), String> { - if path.exists() { - // Verify permissions and ownership (same checks as setup_recheck) - let oflags = - rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC; - let fd = rustix::fs::open(path, oflags, rustix::fs::Mode::empty()) - .map_err(|e| format!("{}: {e} (refusing to follow a symlink)", path.display()))?; - let stat = rustix::fs::fstat(&fd).map_err(|e| format!("{}: fstat: {e}", path.display()))?; - let mode = rustix::fs::Mode::from_bits_truncate(stat.st_mode); - if mode.intersects(rustix::fs::Mode::RWXG | rustix::fs::Mode::RWXO) { - // Fix permissions - rustix::fs::fchmod(&fd, rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR) - .map_err(|e| format!("{}: cannot fix permissions: {e}", path.display()))?; - log(&format!( - "{}: permissions corrected to 0600", - path.display() - )); - } - let euid = rustix::process::geteuid().as_raw(); - if stat.st_uid != euid { - return Err(format!( - "{}: owned by uid {} but postmaster euid is {euid} (cannot fix ownership automatically)", - path.display(), - stat.st_uid - )); - } - drop(fd); - if !force { - log(&format!("{}: keys file verified", path.display())); - return Ok(()); + use crate::secret_files::{ + open_secrets_dir, replace_file, validate_directory_path, validate_projection, + }; + use rustix::fs::{AtFlags, FileType, Mode, OFlags, fstat, openat, statat}; + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let parent = validate_directory_path(parent)?; + let dir_fd = + open_secrets_dir(&parent).map_err(|e| format!("{}: parent: {e}", path.display()))?; + validate_projection(&dir_fd, &parent)?; + let name = path.file_name().ok_or("keys path requires a filename")?; + let original = match openat( + &dir_fd, + name, + OFlags::RDONLY | OFlags::NONBLOCK | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::empty(), + ) { + Ok(fd) => { + let st = fstat(&fd).map_err(|e| format!("{}: stat: {e}", path.display()))?; + if FileType::from_raw_mode(st.st_mode) != FileType::RegularFile + || st.st_uid != rustix::process::geteuid().as_raw() + || st.st_nlink != 1 + { + return Err(format!( + "{}: refusing foreign, linked or non-regular keys file", + path.display() + )); + } + if st.st_mode & 0o077 != 0 { + rustix::fs::fchmod(&fd, Mode::RUSR | Mode::WUSR) + .map_err(|e| format!("{}: chmod: {e}", path.display()))?; + log(&format!( + "{}: permissions corrected to 0600", + path.display() + )); + } + crate::secret_files::clear_file_acl(&fd)?; + if !force { + log(&format!("{}: keys file verified", path.display())); + return Ok(()); + } + Some((fd, st)) } - // --force: re-prompt for the contents even though the file is - // already correct (sweep 2026-08-07 K7). - if unattended { + Err(rustix::io::Errno::NOENT) => None, + Err(e) => { return Err(format!( - "{}: --force re-prompts for key contents, which unattended mode cannot do (fail closed)", + "{}: {e} (refusing to follow a symlink)", path.display() )); } + }; + if unattended { + return Err(format!( + "{}: {} (unattended mode cannot prompt)", + path.display(), + if original.is_some() { + "--force re-prompts for key contents" + } else { + "keys file not found" + } + )); + } + if original.is_some() { eprintln!("{}: keys file exists and is valid.", path.display()); eprintln!("--force given: replace its contents now? [y/N] "); - let mut input = String::new(); - if std::io::stdin().read_line(&mut input).is_err() { - return Err(format!("{}: cannot read input", path.display())); - } - if !input.trim().eq_ignore_ascii_case("y") { + } else { + eprintln!("{}: keys file not found.", path.display()); + eprintln!( + "Create it now? You will need to paste the key contents (DOTENV_PRIVATE_KEY=<64-hex>...). [y/N] " + ); + } + let mut input = String::new(); + std::io::stdin() + .read_line(&mut input) + .map_err(|_| format!("{}: cannot read input", path.display()))?; + if !input.trim().eq_ignore_ascii_case("y") { + if original.is_some() { log(&format!( "{}: --force declined; existing keys file kept", path.display() )); return Ok(()); } - eprintln!("Paste the keys file contents (Ctrl+D to finish):"); - // Zeroizing: operator-pasted key material must not linger in freed - // heap pages (audit 2026-08-02 O4). - let mut contents = zeroize::Zeroizing::new(String::new()); - if std::io::stdin().read_to_string(&mut contents).is_err() { - return Err(format!("{}: cannot read key contents", path.display())); - } - // Overwrite in place: WRONLY|TRUNC|NOFOLLOW on the just-verified - // path, perms forced back to 0600 on the fd before the write. - let oflags = rustix::fs::OFlags::WRONLY - | rustix::fs::OFlags::TRUNC - | rustix::fs::OFlags::NOFOLLOW - | rustix::fs::OFlags::CLOEXEC; - let fd = rustix::fs::open(path, oflags, rustix::fs::Mode::empty()).map_err(|e| { - format!( - "{}: cannot open for replacement: {e} (refusing to follow a symlink)", - path.display() - ) - })?; - rustix::fs::fchmod(&fd, rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR) - .map_err(|e| format!("{}: cannot fix permissions: {e}", path.display()))?; - let mut file = fs::File::from(fd); - use std::io::Write; - file.write_all(contents.as_bytes()) - .map_err(|e| format!("{}: cannot write: {e}", path.display()))?; - log(&format!( - "{}: keys file contents replaced (--force)", - path.display() - )); - return Ok(()); - } - - // File doesn't exist - if unattended { return Err(format!( - "{}: keys file not found (unattended mode — cannot prompt; create the file manually before running setup)", + "{}: operator declined to create keys file", path.display() )); } - - // Interactive: prompt the operator - eprintln!("{}: keys file not found.", path.display()); - eprintln!( - "Create it now? You will need to paste the key contents (DOTENV_PRIVATE_KEY=<64-hex>...). [y/N] " - ); - let mut input = String::new(); - if std::io::stdin().read_line(&mut input).is_err() { - return Err(format!("{}: cannot read input", path.display())); - } - if !input.trim().eq_ignore_ascii_case("y") { - return Err(format!( - "{}: operator declined to create keys file", + let contents = input::read_secret("Paste the keys file contents (Ctrl+D to finish):", false)?; + if let Some((_fd, original)) = original { + let current = statat(&dir_fd, name, AtFlags::SYMLINK_NOFOLLOW) + .map_err(|e| format!("{}: stat: {e}", path.display()))?; + if current.st_dev != original.st_dev || current.st_ino != original.st_ino { + return Err(format!( + "{}: keys file changed while awaiting input", + path.display() + )); + } + replace_file(&dir_fd, name, contents.as_bytes()) + .map_err(|e| format!("{}: {e}", path.display()))?; + log(&format!( + "{}: keys file contents replaced (--force)", path.display() )); - } - - eprintln!("Paste the keys file contents (Ctrl+D to finish):"); - // Zeroizing: operator-pasted key material must not linger in freed - // heap pages (audit 2026-08-02 O4). - let mut contents = zeroize::Zeroizing::new(String::new()); - if std::io::stdin().read_to_string(&mut contents).is_err() { - return Err(format!("{}: cannot read key contents", path.display())); - } - - // Write the file with 0600. O_EXCL | O_NOFOLLOW makes creation - // fail-closed: it refuses to overwrite anything already at the path - // and refuses to follow a planted symlink. - let oflags = rustix::fs::OFlags::WRONLY - | rustix::fs::OFlags::CREATE - | rustix::fs::OFlags::EXCL - | rustix::fs::OFlags::NOFOLLOW - | rustix::fs::OFlags::CLOEXEC; - let fd = rustix::fs::open(path, oflags, rustix::fs::Mode::from_bits_truncate(0o600)).map_err( - |e| { + } else { + let fd = openat( + &dir_fd, + name, + OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::RUSR | Mode::WUSR, + ) + .map_err(|e| { format!( "{}: cannot create: {e} (refusing to overwrite or follow a symlink)", path.display() ) - }, - )?; - let mut file = fs::File::from(fd); - use std::io::Write; - file.write_all(contents.as_bytes()) - .map_err(|e| format!("{}: cannot write: {e}", path.display()))?; - log(&format!("{}: keys file created with 0600", path.display())); + })?; + crate::secret_files::clear_file_acl(&fd)?; + rustix::fs::fchmod(&fd, Mode::RUSR | Mode::WUSR) + .map_err(|e| format!("{}: chmod: {e}", path.display()))?; + let mut file = fs::File::from(fd); + use std::io::Write as _; + if let Err(e) = file.write_all(contents.as_bytes()) { + let _ = rustix::fs::unlinkat(&dir_fd, name, AtFlags::empty()); + return Err(format!("{}: cannot write: {e}", path.display())); + } + log(&format!("{}: keys file created with 0600", path.display())); + } Ok(()) } @@ -325,13 +333,7 @@ fn ensure_keychain_items( } for var in &to_seed { - eprint!("Paste value for {var}: "); - // Zeroizing: pasted key material must not linger in freed - // heap pages (audit 2026-08-02 O4). `trim()` borrows, no copy. - let mut value = zeroize::Zeroizing::new(String::new()); - if std::io::stdin().read_line(&mut value).is_err() { - return Err(format!("cannot read value for {var}")); - } + let value = input::read_secret(&format!("Paste value for {var}:"), true)?; let value = value.trim(); if value.is_empty() { return Err(format!("{var}: empty value, refusing to seed")); @@ -571,8 +573,7 @@ mod tests { // sweep 2026-08-07 K4: verification must not pass what resolution // rejects — exists() followed symlinks; the loader refuses them. use std::os::unix::fs::PermissionsExt; - let d = std::env::temp_dir().join(format!("pm-verify-cred-symlink-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); + let d = crate::test_util::temp_dir::TestDir::new("mod"); let cred_dir = d.join("creds"); fs::create_dir_all(&cred_dir).unwrap(); let real = d.join("real-keys"); @@ -607,9 +608,7 @@ mod tests { // unattended mode cannot do — fail closed rather than silently // skipping the re-create the operator asked for. use std::os::unix::fs::PermissionsExt; - let d = std::env::temp_dir().join(format!("pm-force-unattended-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); + let d = crate::test_util::temp_dir::TestDir::new("mod"); let keys = d.join(".env.keys"); fs::write(&keys, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); fs::set_permissions(&keys, fs::Permissions::from_mode(0o600)).unwrap(); @@ -716,11 +715,7 @@ mod tests { // Canonicalize the temp base: on macOS it sits under /var → // /private/var, and the O5 prefix walk would (correctly) refuse // the symlinked /var component for reasons unrelated to this test. - let d = fs::canonicalize(std::env::temp_dir()) - .unwrap() - .join(format!("pm-ensure-dir-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); + let d = crate::test_util::temp_dir::TestDir::new("mod"); let created = d.join("new-keys"); ensure_keys_dir(&created, false).expect("create should succeed"); @@ -745,11 +740,7 @@ mod tests { // Canonicalize the temp base (macOS /var → /private/var) so the // walk reaches OUR planted symlink instead of refusing the // OS-provided /var component first. - let d = fs::canonicalize(std::env::temp_dir()) - .unwrap() - .join(format!("pm-ensure-dir-link-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); + let d = crate::test_util::temp_dir::TestDir::new("mod"); let real = d.join("real"); fs::create_dir_all(&real).unwrap(); std::os::unix::fs::symlink(&real, d.join("link")).unwrap(); @@ -770,9 +761,7 @@ mod tests { // sweep 2026-08-07 T7: a 0644 keys file is corrected to 0600; a // missing file in unattended mode fails closed (no prompt). use std::os::unix::fs::PermissionsExt; - let d = std::env::temp_dir().join(format!("pm-ensure-file-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); + let d = crate::test_util::temp_dir::TestDir::new("mod"); let keys = d.join(".env.keys"); fs::write(&keys, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); fs::set_permissions(&keys, fs::Permissions::from_mode(0o644)).unwrap(); @@ -788,4 +777,48 @@ mod tests { let _ = fs::remove_dir_all(&d); } + + #[test] + fn keys_files_reject_linked_special_and_foreign_inodes_before_mutation() { + use std::os::unix::fs::PermissionsExt as _; + let dir = crate::test_util::temp_dir::TestDir::new("key-custody"); + let path = dir.join("keys"); + fs::write(&path, b"unchanged").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + fs::hard_link(&path, dir.join("link")).unwrap(); + assert!(ensure_keys_file(&path, false, true).is_err()); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o644 + ); + fs::remove_file(&path).unwrap(); + assert!( + std::process::Command::new("mkfifo") + .arg(&path) + .status() + .unwrap() + .success() + ); + assert!(ensure_keys_file(&path, false, true).is_err()); + if rustix::process::geteuid().is_root() { + fs::remove_file(&path).unwrap(); + fs::write(&path, b"foreign").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + rustix::fs::chown(&path, Some(rustix::fs::Uid::from_raw(65534)), None).unwrap(); + assert!(ensure_keys_file(&path, false, true).is_err()); + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o644 + ); + let foreign = dir.join("directory"); + fs::create_dir(&foreign).unwrap(); + fs::set_permissions(&foreign, fs::Permissions::from_mode(0o755)).unwrap(); + rustix::fs::chown(&foreign, Some(rustix::fs::Uid::from_raw(65534)), None).unwrap(); + assert!(ensure_keys_dir(&foreign, false).is_err()); + assert_eq!( + fs::metadata(&foreign).unwrap().permissions().mode() & 0o777, + 0o755 + ); + } + } } diff --git a/src/keys/source.rs b/src/keys/source.rs index 0b9ac87..4baf2f4 100644 --- a/src/keys/source.rs +++ b/src/keys/source.rs @@ -147,9 +147,7 @@ mod tests { // Audit finding #2: a symlink planted at // $CREDENTIALS_DIRECTORY/ must be rejected, not followed. use std::os::unix::fs::PermissionsExt; - let d = std::env::temp_dir().join(format!("pm-keysource-symlink-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); + let d = crate::test_util::temp_dir::TestDir::new("source"); let real = d.join("real-keys"); fs::write(&real, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); fs::set_permissions(&real, fs::Permissions::from_mode(0o600)).unwrap(); @@ -187,8 +185,7 @@ mod tests { // unobservable in a root test run. return; } - let d = std::env::temp_dir().join(format!("pm-keysource-eacces-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); + let d = crate::test_util::temp_dir::TestDir::new("source"); let cred_dir = d.join("locked"); fs::create_dir_all(&cred_dir).unwrap(); fs::set_permissions(&cred_dir, fs::Permissions::from_mode(0o000)).unwrap(); @@ -220,9 +217,7 @@ mod tests { fn load_ring_credential_rejects_non_file() { // A directory as a credential source name should be rejected, // not silently skipped or treated as a file. - let d = std::env::temp_dir().join(format!("pm-keysource-dir-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); + let d = crate::test_util::temp_dir::TestDir::new("source"); let cred_dir = d.join("creds"); fs::create_dir_all(&cred_dir).unwrap(); let sub = cred_dir.join("subdir"); @@ -253,9 +248,8 @@ mod tests { // by putting a valid "environment" source after the bad file source: // if file were skippable, load_ring would try environment and fail // with "environment:" — instead it must fail with the file path. - let ghost_path = std::env::temp_dir() - .join(format!("pm-keysource-terminal-{}", std::process::id())) - .join("ghost.keys"); + let fixture = crate::test_util::temp_dir::TestDir::new("missing-source"); + let ghost_path = fixture.join("ghost.keys"); let specs = vec![ KeySourceSpec::File(ghost_path.clone()), KeySourceSpec::Environment, @@ -376,8 +370,7 @@ mod tests { // well-formed credential file loads through the same selection // path the negative legs reject. use std::os::unix::fs::PermissionsExt; - let d = std::env::temp_dir().join(format!("pm-keysource-load-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); + let d = crate::test_util::temp_dir::TestDir::new("source"); let cred_dir = d.join("creds"); fs::create_dir_all(&cred_dir).unwrap(); let cred = cred_dir.join("dotenv-keys"); diff --git a/src/keys/verify.rs b/src/keys/verify.rs index 5ec90bb..2f9ddd5 100644 --- a/src/keys/verify.rs +++ b/src/keys/verify.rs @@ -92,12 +92,8 @@ mod tests { #[cfg(target_os = "macos")] fn verify_external_binary_rejects_unsigned_file() { // A temp file with no code signature must be rejected by codesign -v. - let dir = std::env::temp_dir(); - let path = dir.join(format!( - "postmaster-test-unsigned-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); + let dir = crate::test_util::temp_dir::TestDir::new("verify"); + let path = dir.join("fixture"); std::fs::write(&path, b"not a signed binary").unwrap(); let result = verify_external_binary(&path); let _ = std::fs::remove_file(&path); @@ -115,12 +111,8 @@ mod tests { return; } // On Linux, a non-root-owned binary in /tmp must be rejected. - let dir = std::env::temp_dir(); - let path = dir.join(format!( - "postmaster-test-binary-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); + let dir = crate::test_util::temp_dir::TestDir::new("verify"); + let path = dir.join("fixture"); std::fs::write(&path, b"fake binary").unwrap(); use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); diff --git a/src/launcher.rs b/src/launcher.rs index beb1f5e..78ae244 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -51,12 +51,30 @@ pub(crate) struct TerminationGuard { #[cfg(target_os = "macos")] impl TerminationGuard { pub(crate) fn block() -> Self { + Self::block_signals(&STOP_SIGNALS) + } + + pub(crate) fn block_input() -> Self { + Self::block_signals(&[ + STOP_SIGNALS[0], + STOP_SIGNALS[1], + STOP_SIGNALS[2], + STOP_SIGNALS[3], + rustix::process::Signal::TSTP, + ]) + } + + pub(crate) fn active(&self) -> bool { + self.old.is_some() + } + + fn block_signals(signals: &[rustix::process::Signal]) -> Self { unsafe { // SAFETY: zeroed sigset_t is a valid empty set representation; // all pointers are valid and outlive the calls. let mut set: libc::sigset_t = std::mem::zeroed(); libc::sigemptyset(&mut set); - for sig in STOP_SIGNALS { + for sig in signals { libc::sigaddset(&mut set, sig.as_raw()); } let mut old: libc::sigset_t = std::mem::zeroed(); @@ -72,6 +90,20 @@ impl TerminationGuard { } } + pub(crate) fn input_pending(&self) -> Result { + // SAFETY: sigpending initializes valid storage; sigismember receives that set. + unsafe { + let mut pending: libc::sigset_t = std::mem::zeroed(); + if libc::sigpending(&mut pending) != 0 { + return Err("cannot check pending input signals".into()); + } + Ok(STOP_SIGNALS + .iter() + .any(|s| libc::sigismember(&pending, s.as_raw()) == 1) + || libc::sigismember(&pending, libc::SIGTSTP) == 1) + } + } + /// Restore the saved signal mask. The parent calls this before /// execvp — the child must not inherit blocked termination signals. pub(crate) fn restore_mask(&self) { @@ -103,9 +135,27 @@ pub(crate) struct TerminationGuard { #[cfg(target_os = "linux")] impl TerminationGuard { pub(crate) fn block() -> Self { + Self::block_signals(&STOP_SIGNALS) + } + + pub(crate) fn block_input() -> Self { + Self::block_signals(&[ + STOP_SIGNALS[0], + STOP_SIGNALS[1], + STOP_SIGNALS[2], + STOP_SIGNALS[3], + rustix::process::Signal::TSTP, + ]) + } + + pub(crate) fn active(&self) -> bool { + self.old.is_some() + } + + fn block_signals(signals: &[rustix::process::Signal]) -> Self { let mut set = runtime::KernelSigSet::empty(); - for sig in STOP_SIGNALS { - set.insert(sig); + for sig in signals { + set.insert(*sig); } // SAFETY: the set holds only the four standard termination // signals — none reserved by any libc in the process (glibc @@ -125,6 +175,12 @@ impl TerminationGuard { } } + pub(crate) fn input_pending(&self) -> Result { + let pending = runtime::kernel_sigpending(); + Ok(STOP_SIGNALS.iter().any(|s| pending.contains(*s)) + || pending.contains(rustix::process::Signal::TSTP)) + } + /// Restore the saved signal mask (see the macOS docs). pub(crate) fn restore_mask(&self) { if let Some(old) = &self.old { @@ -341,6 +397,8 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() format!("{}: {e} (refusing to follow a symlink)", dir.display()) })?, }; + let projected_dir = crate::secret_files::validate_projection(&dir_fd, dir)?; + let dir = projected_dir.as_path(); let (resolved, failed) = decrypt(&cfg)?; if verify_keys { verify_key_freshness(&failed)?; @@ -383,7 +441,7 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() // systemd path: pid 1 already materialized the credentials. let dir = std::env::var_os("CREDENTIALS_DIRECTORY") .ok_or("postmaster credentials expected but CREDENTIALS_DIRECTORY is unset")?; - let dir = PathBuf::from(dir); + let dir = crate::secret_files::validate_directory_path(&PathBuf::from(dir))?; for k in &cfg.credential_keys { extra.push(( OsString::from(format!("{k}_FILE")), @@ -402,6 +460,8 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() format!("{}: {e} (refusing to follow a symlink)", dir.display()) })?, }; + let projected_dir = crate::secret_files::validate_projection(&dir_fd, dir)?; + let dir = projected_dir.as_path(); let sockets: &HashMap = &cfg.sockets; // Prune stale credential files from a prior launch. prune_stale_at(&dir_fd, dir, &cfg.credential_keys)?; @@ -548,9 +608,7 @@ mod tests { // A config that resolves cleanly in "env" mode (no ramdisk/creds // machinery involved) so the empty-argv guard is what's exercised, // not an earlier, unrelated failure. - let d = std::env::temp_dir().join(format!("pm-launcher-emptyargv-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); + let d = crate::test_util::temp_dir::TestDir::new("launcher"); let keys_path = d.join(".env.keys"); fs::write( &keys_path, diff --git a/src/monitor/tests.rs b/src/monitor/tests.rs index a24f230..f27d073 100644 --- a/src/monitor/tests.rs +++ b/src/monitor/tests.rs @@ -8,7 +8,7 @@ use std::fs; use std::io::Read; use std::os::fd::AsRawFd; use std::os::unix::process::ExitStatusExt; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::process::Command; use rustix::process::{WaitOptions, waitpid}; @@ -16,11 +16,8 @@ use rustix::process::{WaitOptions, waitpid}; use crate::launcher::TerminationGuard; use crate::secret_files::open_secrets_dir; -fn tdir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("pm-monitor-{tag}-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); - d +fn tdir(tag: &str) -> crate::test_util::temp_dir::TestDir { + crate::test_util::temp_dir::TestDir::new(tag) } /// Fork a monitor watching `service_pid`, mirroring the production diff --git a/src/ramdisk.rs b/src/ramdisk.rs index 5e0eabd..f589c6d 100644 --- a/src/ramdisk.rs +++ b/src/ramdisk.rs @@ -309,15 +309,8 @@ image-type : read/write )); } - fn test_dir(tag: &str) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!( - "pm-ramdisk-{tag}-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - dir + fn test_dir(tag: &str) -> crate::test_util::temp_dir::TestDir { + crate::test_util::temp_dir::TestDir::new(tag) } #[test] diff --git a/src/secret_files.rs b/src/secret_files.rs index 42f74aa..0382f9b 100644 --- a/src/secret_files.rs +++ b/src/secret_files.rs @@ -16,6 +16,18 @@ use std::path::{Path, PathBuf}; use zeroize::Zeroizing; +#[cfg(target_os = "macos")] +mod acl; + +/// Remove extended grants before writing private file contents. +pub(crate) fn clear_file_acl(fd: impl AsFd) -> Result<(), String> { + #[cfg(target_os = "macos")] + acl::clear(fd)?; + #[cfg(not(target_os = "macos"))] + let _ = fd; + Ok(()) +} + /// Resolved values keyed by name, each zeroized on drop. pub type Resolved = Vec<(String, Zeroizing>)>; @@ -57,6 +69,77 @@ pub(crate) fn open_secrets_dir(dir: &Path) -> rustix::io::Result { ) } +/// Verify every lexical and resolved ancestor before exporting a pathname. +/// Root and the effective user are trusted; sticky shared parents protect their entries. +pub(crate) fn validate_directory_path(dir: &Path) -> Result { + use std::os::unix::fs::MetadataExt as _; + let absolute = if dir.is_absolute() { + dir.to_path_buf() + } else { + std::env::current_dir() + .map_err(|e| format!("current directory: {e}"))? + .join(dir) + }; + let euid = rustix::process::geteuid().as_raw(); + let check = |path: &Path, symlink: bool| -> Result<(), String> { + let md = fs::symlink_metadata(path).map_err(|e| format!("{}: {e}", path.display()))?; + if md.uid() != 0 && md.uid() != euid { + return Err(format!( + "{}: directory path is owned by an untrusted user", + path.display() + )); + } + if symlink && md.file_type().is_symlink() { + return Ok(()); + } + if !md.is_dir() || md.mode() & 0o022 != 0 && md.mode() & 0o1000 == 0 { + return Err(format!( + "{}: directory path permits untrusted replacement", + path.display() + )); + } + #[cfg(target_os = "macos")] + { + let fd = open_secrets_dir(path).map_err(|e| format!("{}: {e}", path.display()))?; + acl::validate(&fd).map_err(|e| format!("{}: {e}", path.display()))?; + } + Ok(()) + }; + let mut lexical = PathBuf::new(); + for component in absolute.components() { + lexical.push(component); + check(&lexical, true)?; + // Check symlink targets too: trusting the link alone does not protect its target. + let resolved = + fs::canonicalize(&lexical).map_err(|e| format!("{}: {e}", lexical.display()))?; + let mut prefix = PathBuf::new(); + for component in resolved.components() { + prefix.push(component); + check(&prefix, false)?; + } + } + fs::canonicalize(&absolute).map_err(|e| format!("{}: {e}", absolute.display())) +} + +/// Check that an exported directory still names the inode used for writes. +pub(crate) fn validate_projection(dir_fd: impl AsFd, dir: &Path) -> Result { + use std::os::unix::fs::MetadataExt as _; + let canonical = validate_directory_path(dir)?; + let pinned = rustix::fs::fstat(dir_fd).map_err(|e| format!("{}: stat: {e}", dir.display()))?; + let named = fs::metadata(&canonical).map_err(|e| format!("{}: {e}", dir.display()))?; + #[cfg(target_os = "macos")] + let device = pinned.st_dev as u64; + #[cfg(target_os = "linux")] + let device = pinned.st_dev; + if device != named.dev() || pinned.st_ino != named.ino() { + return Err(format!( + "{}: directory changed during validation", + dir.display() + )); + } + Ok(canonical) +} + /// Enumerate entry names beneath an already-pinned directory fd, /// excluding `.` and `..`. `Dir::read_from` re-opens `.` beneath the /// fd, so enumeration is relative to the pinned inode and the caller's @@ -81,71 +164,98 @@ pub(crate) fn read_dir_names(dir_fd: impl AsFd) -> rustix::io::Result Result<(), String> { + use rustix::fs::{AtFlags, FileType, statat}; + match statat(dir_fd, name, AtFlags::SYMLINK_NOFOLLOW) { + Ok(st) + if FileType::from_raw_mode(st.st_mode) == FileType::RegularFile + && st.st_uid == rustix::process::geteuid().as_raw() + && st.st_nlink == 1 => + { + Ok(()) + } + Ok(_) => Err("refusing foreign, linked or non-regular file".into()), + Err(rustix::io::Errno::NOENT) => Ok(()), + Err(e) => Err(format!("stat: {e}")), + } +} + +/// Publish a fresh owner-only inode beneath a pinned directory. +/// Existing read handles retain the old contents. Failed writes remove only the new inode. +pub(crate) fn replace_file( + dir_fd: impl AsFd, + name: &std::ffi::OsStr, + value: &[u8], +) -> Result<(), String> { + use rustix::fs::{AtFlags, Mode, OFlags, openat, renameat, unlinkat}; + let dir_fd = dir_fd.as_fd(); + check_file(dir_fd, name)?; + #[cfg(target_os = "macos")] + acl::validate(dir_fd)?; + let mut random = [0; 16]; + getrandom::fill(&mut random).map_err(|e| format!("random temporary name: {e}"))?; + let temporary = format!(".postmaster-{}", hex::encode(random)); + let fd = openat( + dir_fd, + temporary.as_str(), + OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::RUSR | Mode::WUSR, + ) + .map_err(|e| format!("create temporary file: {e}"))?; + let result = (|| { + rustix::fs::fchmod(&fd, Mode::RUSR | Mode::WUSR).map_err(|e| format!("fchmod: {e}"))?; + clear_file_acl(&fd)?; + let mut file = fs::File::from(fd); + file.write_all(value) + .and_then(|()| file.flush()) + .map_err(|e| format!("write: {e}"))?; + check_file(dir_fd, name)?; + renameat(dir_fd, temporary.as_str(), dir_fd, name).map_err(|e| format!("publish: {e}")) + })(); + if result.is_err() { + let _ = unlinkat(dir_fd, temporary.as_str(), AtFlags::empty()); + } + result +} + +/// Write a fresh 0600 file beneath the pinned directory and return its consumer path. +/// Refuse foreign, linked and special existing entries; refresh regular owner-held files atomically. pub fn write_secret_file( dir_fd: impl AsFd, dir: &Path, key: &str, value: &[u8], ) -> Result { + if !crate::keys::is_ident(key) { + return Err("secret filename must be an identifier".into()); + } let dir_fd = dir_fd.as_fd(); let path = dir.join(key); - // Drop the managed-dir sentinel (audit 2026-08-02 A19): prune_stale - // and cleanup refuse to bulk-delete in a non-empty dir lacking it. - let _sentinel_fd = rustix::fs::openat( + let sentinel = std::ffi::OsStr::new(MANAGED_SENTINEL); + check_file(dir_fd, sentinel).map_err(|e| format!("{}: sentinel: {e}", path.display()))?; + let sentinel_fd = rustix::fs::openat( dir_fd, - MANAGED_SENTINEL, + sentinel, rustix::fs::OFlags::WRONLY | rustix::fs::OFlags::CREATE + | rustix::fs::OFlags::EXCL | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC, - rustix::fs::Mode::from_bits_truncate(0o600), - ) - .map_err(|e| format!("{}: sentinel: {e}", path.display()))?; - let oflags = rustix::fs::OFlags::WRONLY - | rustix::fs::OFlags::CREATE - | rustix::fs::OFlags::TRUNC - | rustix::fs::OFlags::NOFOLLOW - | rustix::fs::OFlags::CLOEXEC; - // `key` is a validated identifier (no separators), so this opens - // exactly `dir/key` beneath the pinned directory fd. - let fd = rustix::fs::openat( - dir_fd, - key, - oflags, - rustix::fs::Mode::from_bits_truncate(0o600), - ) - .map_err(|e| format!("{}: {e} (refusing to follow a symlink)", path.display()))?; - // Use fchmod on the fd (not set_permissions on the path) to eliminate a - // TOCTOU: between open(O_NOFOLLOW) and a path-based chmod, an attacker - // with directory write access could unlink the file and create a symlink - // at the same path. fchmod operates on the already-opened fd, which is - // the file we just created — no path re-resolution occurs. - if let Err(e) = rustix::fs::fchmod(&fd, rustix::fs::Mode::from_bits_truncate(0o600)) { - // Post-open failure: unlink the just-created target fd-relative - // so partial plaintext never survives a failed write. - let _ = rustix::fs::unlinkat(dir_fd, key, rustix::fs::AtFlags::empty()); - return Err(format!("{}: fchmod: {e}", path.display())); - } - let mut f = fs::File::from(fd); - if let Err(e) = f.write_all(value).and_then(|()| f.flush()) { - // Same invariant: the truncated/partially-written target must - // not persist as stale plaintext on the ramdisk. - let _ = rustix::fs::unlinkat(dir_fd, key, rustix::fs::AtFlags::empty()); - return Err(format!("{}: write: {e}", path.display())); + rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR, + ); + match sentinel_fd { + Ok(fd) => { + clear_file_acl(&fd)?; + } + Err(rustix::io::Errno::EXIST) => { + check_file(dir_fd, sentinel) + .map_err(|e| format!("{}: sentinel: {e}", path.display()))?; + } + Err(e) => return Err(format!("{}: sentinel: {e}", path.display())), } + replace_file(dir_fd, std::ffi::OsStr::new(key), value) + .map_err(|e| format!("{}: {e}", path.display()))?; Ok(path) } @@ -264,10 +374,8 @@ pub(crate) fn prune_stale_at( mod tests { use super::*; - fn tdir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("pm-secretfiles-{tag}-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); + fn tdir(tag: &str) -> crate::test_util::temp_dir::TestDir { + let d = crate::test_util::temp_dir::TestDir::new(tag); // prune_stale requires a postmaster-managed (owner-only) dir // (audit 2026-08-02 A19); match real deployments. use std::os::unix::fs::PermissionsExt; @@ -327,6 +435,125 @@ mod tests { ); } + #[test] + fn refresh_does_not_write_to_old_handles_or_linked_inodes() { + use std::io::Read as _; + use std::os::unix::fs::MetadataExt as _; + let dir = tdir("refresh"); + let fd = open_secrets_dir(&dir).unwrap(); + let path = write_secret_file(&fd, &dir, "KEY", b"old").unwrap(); + let old_inode = fs::metadata(&path).unwrap().ino(); + let mut old_handle = fs::File::open(&path).unwrap(); + write_secret_file(&fd, &dir, "KEY", b"new").unwrap(); + assert_ne!(old_inode, fs::metadata(&path).unwrap().ino()); + let mut old = Vec::new(); + old_handle.read_to_end(&mut old).unwrap(); + assert_eq!(old, b"old"); + assert_eq!(fs::read(&path).unwrap(), b"new"); + fs::hard_link(&path, dir.join("LINK")).unwrap(); + assert!(write_secret_file(&fd, &dir, "KEY", b"never").is_err()); + assert_eq!(fs::read(dir.join("LINK")).unwrap(), b"new"); + assert!( + !read_dir_names(&fd) + .unwrap() + .iter() + .any(|n| n.to_string_lossy().starts_with(".postmaster-") && n != MANAGED_SENTINEL) + ); + } + + #[test] + fn special_secret_and_sentinel_files_fail_without_opening() { + let dir = tdir("special"); + let fd = open_secrets_dir(&dir).unwrap(); + assert!( + std::process::Command::new("mkfifo") + .arg(dir.join("KEY")) + .status() + .unwrap() + .success() + ); + assert!(write_secret_file(&fd, &dir, "KEY", b"never").is_err()); + fs::remove_file(dir.join(MANAGED_SENTINEL)).unwrap(); + std::os::unix::fs::symlink(dir.join("target"), dir.join(MANAGED_SENTINEL)).unwrap(); + assert!(write_secret_file(&fd, &dir, "OTHER", b"never").is_err()); + assert!(!dir.join("target").exists()); + } + + #[test] + fn projection_checks_ancestors_and_preserves_sticky_and_trusted_aliases() { + use std::os::unix::fs::PermissionsExt as _; + let dir = tdir("ancestry"); + let shared = dir.join("shared"); + let secret = shared.join("service"); + fs::create_dir_all(&secret).unwrap(); + fs::set_permissions(&shared, fs::Permissions::from_mode(0o777)).unwrap(); + let fd = open_secrets_dir(&secret).unwrap(); + let error = validate_projection(&fd, &secret).unwrap_err(); + assert!(error.contains("untrusted replacement"), "{error}"); + fs::set_permissions(&shared, fs::Permissions::from_mode(0o1777)).unwrap(); + assert_eq!(validate_projection(&fd, &secret).unwrap(), secret); + std::os::unix::fs::symlink(&shared, dir.join("alias")).unwrap(); + assert_eq!( + validate_projection(&fd, &dir.join("alias/service")).unwrap(), + secret + ); + write_secret_file(&fd, &secret, "KEY", b"secret").unwrap(); + let child = std::process::Command::new("/bin/sh") + .args(["-c", "cat \"$KEY_FILE\""]) + .env("KEY_FILE", secret.join("KEY")) + .output() + .unwrap(); + assert!(child.status.success()); + assert_eq!(child.stdout, b"secret"); + } + + #[test] + fn untrusted_user_cannot_replace_exported_sticky_paths_or_receive_refreshes() { + use std::os::unix::fs::PermissionsExt as _; + use std::os::unix::process::CommandExt as _; + if !rustix::process::geteuid().is_root() { + return; + } + let dir = tdir("projection-user"); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap(); + let shared = dir.join("shared"); + let service = shared.join("service"); + fs::create_dir_all(&service).unwrap(); + fs::set_permissions(&shared, fs::Permissions::from_mode(0o1777)).unwrap(); + let fd = open_secrets_dir(&service).unwrap(); + let projected = validate_projection(&fd, &service).unwrap(); + write_secret_file(&fd, &projected, "KEY", b"protected").unwrap(); + let attempt = std::process::Command::new("/bin/mv") + .arg(&service) + .arg(shared.join("replaced")) + .uid(65534) + .gid(65534) + .output() + .unwrap(); + assert!(!attempt.status.success()); + let child = std::process::Command::new("/bin/sh") + .args([ + "-c", + "test \"$(cat \"$KEY_FILE\")\" = protected && cat \"$CREDENTIALS_DIRECTORY/KEY\"", + ]) + .env("KEY_FILE", projected.join("KEY")) + .env("CREDENTIALS_DIRECTORY", &projected) + .output() + .unwrap(); + assert!(child.status.success()); + assert_eq!(child.stdout, b"protected"); + let foreign = service.join("FOREIGN"); + fs::write(&foreign, b"old").unwrap(); + fs::set_permissions(&foreign, fs::Permissions::from_mode(0o644)).unwrap(); + rustix::fs::chown(&foreign, Some(rustix::fs::Uid::from_raw(65534)), None).unwrap(); + assert!(write_secret_file(&fd, &service, "FOREIGN", b"never").is_err()); + assert_eq!(fs::read(&foreign).unwrap(), b"old"); + assert_eq!( + fs::metadata(&foreign).unwrap().permissions().mode() & 0o777, + 0o644 + ); + } + #[test] fn prune_stale_removes_unconfigured_files() { let dir = tdir("prune"); diff --git a/src/secret_files/acl.rs b/src/secret_files/acl.rs new file mode 100644 index 0000000..7bbab0c --- /dev/null +++ b/src/secret_files/acl.rs @@ -0,0 +1,186 @@ +//! Darwin extended ACL checks; POSIX mode bits alone do not describe access. + +use std::ffi::{c_int, c_void}; +use std::os::fd::{AsFd, AsRawFd as _}; + +const EXTENDED: c_int = 0x100; +const ALLOW: c_int = 1; +const FILE_INHERIT: c_int = 1 << 5; +// sys/acl.h: add file/subdirectory, delete, delete child, write attributes/security, change owner. +const MUTATE: u64 = + (1 << 2) | (1 << 4) | (1 << 5) | (1 << 6) | (1 << 8) | (1 << 10) | (1 << 12) | (1 << 13); + +unsafe extern "C" { + fn acl_get_fd_np(fd: c_int, kind: c_int) -> *mut c_void; + fn acl_init(count: c_int) -> *mut c_void; + fn acl_set_fd_np(fd: c_int, acl: *mut c_void, kind: c_int) -> c_int; + fn acl_free(value: *mut c_void) -> c_int; + fn acl_get_entry(acl: *mut c_void, index: c_int, entry: *mut *mut c_void) -> c_int; + fn acl_get_tag_type(entry: *mut c_void, tag: *mut c_int) -> c_int; + fn acl_get_permset_mask_np(entry: *mut c_void, mask: *mut u64) -> c_int; + fn acl_get_qualifier(entry: *mut c_void) -> *mut c_void; + fn acl_get_flagset_np(entry: *mut c_void, flags: *mut *mut c_void) -> c_int; + fn acl_get_flag_np(flags: *mut c_void, flag: c_int) -> c_int; + fn mbr_uid_to_uuid(uid: u32, uuid: *mut u8) -> c_int; +} + +struct Allocation(*mut c_void); + +impl Drop for Allocation { + fn drop(&mut self) { + // SAFETY: owned allocations returned by the ACL API are released exactly once. + unsafe { + acl_free(self.0); + } + } +} + +/// Clear inherited extended grants before writing plaintext to a fresh inode. +pub(super) fn clear(fd: impl AsFd) -> Result<(), String> { + // SAFETY: live fd and owned ACL storage; the API copies the ACL before storage is freed. + unsafe { + let acl = Allocation(acl_init(0)); + if acl.0.is_null() { + return Err("cannot allocate empty ACL".into()); + } + if acl_set_fd_np(fd.as_fd().as_raw_fd(), acl.0, EXTENDED) != 0 { + let e = std::io::Error::last_os_error(); + if e.raw_os_error() != Some(libc::ENOTSUP) { + return Err(format!("cannot clear file ACL: {e}")); + } + } + } + Ok(()) +} + +/// Reject extended grants that let another principal replace directory entries. +pub(super) fn validate(fd: impl AsFd) -> Result<(), String> { + // SAFETY: every out pointer is initialized storage, entry pointers borrow the live ACL, + // and qualifiers are owned UUID allocations with the platform's fixed 16-byte layout. + unsafe { + let acl = Allocation(acl_get_fd_np(fd.as_fd().as_raw_fd(), EXTENDED)); + if acl.0.is_null() { + let e = std::io::Error::last_os_error(); + // Darwin reports ENOENT when a live inode has no extended ACL. + return if matches!(e.raw_os_error(), Some(libc::ENOTSUP | libc::ENOENT)) { + Ok(()) + } else { + Err(format!("cannot read directory ACL: {e}")) + }; + } + let mut root = [0; 16]; + let mut user = [0; 16]; + if mbr_uid_to_uuid(0, root.as_mut_ptr()) != 0 + || mbr_uid_to_uuid(rustix::process::geteuid().as_raw(), user.as_mut_ptr()) != 0 + { + return Err("cannot resolve trusted ACL principals".into()); + } + for index in 0..=1024 { + let mut entry = std::ptr::null_mut(); + if acl_get_entry(acl.0, index, &mut entry) != 0 { + let e = std::io::Error::last_os_error(); + return if e.raw_os_error() == Some(libc::EINVAL) { + Ok(()) + } else { + Err(format!("cannot read ACL entry: {e}")) + }; + } + if index == 1024 { + return Err("directory ACL has too many entries".into()); + } + let mut tag = 0; + let mut permissions = 0; + if acl_get_tag_type(entry, &mut tag) != 0 + || acl_get_permset_mask_np(entry, &mut permissions) != 0 + { + return Err("cannot inspect directory ACL permissions".into()); + } + if tag != ALLOW { + continue; + } + let mut flags = std::ptr::null_mut(); + if acl_get_flagset_np(entry, &mut flags) != 0 { + return Err("cannot inspect directory ACL inheritance".into()); + } + let inherited = acl_get_flag_np(flags, FILE_INHERIT); + if inherited < 0 { + return Err("cannot inspect directory ACL inheritance".into()); + } + // An inherited grant can expose a fresh inode before its ACL is cleared. + if permissions & MUTATE == 0 && !(inherited == 1 && permissions & (1 << 1) != 0) { + continue; + } + let qualifier = Allocation(acl_get_qualifier(entry)); + if qualifier.0.is_null() { + return Err("cannot read ACL principal".into()); + } + let uuid = std::slice::from_raw_parts(qualifier.0.cast::(), 16); + if uuid != root && uuid != user { + return Err("directory ACL permits untrusted replacement".into()); + } + } + } + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic)] +mod tests { + use super::*; + + #[test] + fn extended_grants_cannot_replace_paths_or_reach_new_plaintext() { + let dir = crate::test_util::temp_dir::TestDir::new("acl"); + let fd = crate::secret_files::open_secrets_dir(&dir).unwrap(); + assert!( + std::process::Command::new("/bin/chmod") + .args(["+a", "everyone allow add_file,delete_child"]) + .arg(&*dir) + .status() + .unwrap() + .success() + ); + assert!(validate(&fd).unwrap_err().contains("untrusted replacement")); + assert!( + std::process::Command::new("/bin/chmod") + .arg("-N") + .arg(&*dir) + .status() + .unwrap() + .success() + ); + assert!( + std::process::Command::new("/bin/chmod") + .args(["+a", "everyone allow read,file_inherit"]) + .arg(&*dir) + .status() + .unwrap() + .success() + ); + assert!(validate(&fd).is_err()); + assert!(crate::secret_files::write_secret_file(&fd, &dir, "KEY", b"private").is_err()); + assert!( + std::process::Command::new("/bin/chmod") + .arg("-N") + .arg(&*dir) + .status() + .unwrap() + .success() + ); + validate(&fd).unwrap(); + crate::secret_files::write_secret_file(&fd, &dir, "KEY", b"private").unwrap(); + let file = std::fs::File::open(dir.join("KEY")).unwrap(); + // SAFETY: the returned owned ACL remains live while its first entry is queried. + unsafe { + let acl = Allocation(acl_get_fd_np(file.as_raw_fd(), EXTENDED)); + if !acl.0.is_null() { + let mut entry = std::ptr::null_mut(); + assert_eq!(acl_get_entry(acl.0, 0, &mut entry), -1); + assert_eq!( + std::io::Error::last_os_error().raw_os_error(), + Some(libc::EINVAL) + ); + } + } + } +} diff --git a/src/server.rs b/src/server.rs index 9d40885..2e0dfd7 100644 --- a/src/server.rs +++ b/src/server.rs @@ -114,7 +114,7 @@ const MAX_READ_BYTES: u64 = 16 * 1024 * 1024; /// truncated secret must never be served as if complete. pub(crate) fn read_capped(reader: R, path: &Path) -> Result, String> { let mut limited = reader.take(MAX_READ_BYTES + 1); - let mut buf = Vec::new(); + let mut buf = Zeroizing::new(Vec::new()); limited .read_to_end(&mut buf) .map_err(|e| format!("{}: read: {e}", path.display()))?; @@ -125,7 +125,7 @@ pub(crate) fn read_capped(reader: R, path: &Path) -> Result, St MAX_READ_BYTES )); } - Ok(buf) + Ok(std::mem::take(&mut *buf)) } /// Connect, read one credential to EOF (hard-capped by `read_capped`). @@ -388,6 +388,71 @@ impl Drop for UmaskGuard { } } +struct SocketDomain { + parent: PathBuf, + traversed: std::collections::HashSet, + uid: u32, +} + +/// Resolve aliases while retaining each directory traversed by the consumer's pathname. +fn socket_domain(path: &Path, uid: u32) -> Result { + let mut resolved = PathBuf::new(); + let mut traversed = std::collections::HashSet::new(); + for part in path + .parent() + .ok_or("socket requires a parent directory")? + .components() + { + if part == std::path::Component::ParentDir { + resolved.pop(); + continue; + } + resolved.push(part); + match fs::canonicalize(&resolved) { + Ok(path) => resolved = path, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("{}: socket parent: {e}", path.display())), + } + traversed.extend(resolved.ancestors().map(Path::to_path_buf)); + } + Ok(SocketDomain { + parent: resolved, + traversed, + uid, + }) +} + +/// Reject ownership domains where one consumer could replace another's sockets. +fn validate_socket_domains( + cfg: &Config, + peer_uids: &std::collections::HashMap>, + euid: u32, +) -> Result<(), String> { + let mut domains: Vec = Vec::new(); + for path in cfg.credentials.keys() { + let uid = if euid == 0 { + peer_uids.get(path).copied().flatten().unwrap_or(0) + } else { + euid + }; + let domain = socket_domain(path, uid)?; + for other in &domains { + let same = domain.parent == other.parent; + let controlled = other.uid != 0 && domain.traversed.contains(&other.parent) + || uid != 0 && other.traversed.contains(&domain.parent); + if uid != other.uid && (same || controlled) { + return Err(format!( + "{} and {}: socket parents have conflicting ownership domains", + domain.parent.display(), + other.parent.display() + )); + } + } + domains.push(domain); + } + Ok(()) +} + /// Bind and listen on all configured credential sockets. Returns /// a vector of `(UnixListener, path)` pairs ready for serving (the entry /// is re-looked-up by the caller). @@ -398,6 +463,7 @@ pub fn acquire_listeners( peer_uids: &std::collections::HashMap>, ) -> Result, String> { if bind { + validate_socket_domains(cfg, peer_uids, rustix::process::geteuid().as_raw())?; let am_root = rustix::process::geteuid().is_root(); let mut out = Vec::new(); for path in cfg.credentials.keys() { @@ -654,9 +720,7 @@ mod tests { #[test] fn fetch_bytes_roundtrip_and_empty_fails_closed() { - let dir = std::env::temp_dir().join(format!("pm-fetch-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); + let dir = crate::test_util::temp_dir::TestDir::new("server"); let sock = dir.join("t.sock"); let listener = UnixListener::bind(&sock).unwrap(); let t = thread::spawn(move || { @@ -680,7 +744,8 @@ mod tests { // runs trip the root-ownership check, root runs trip the // write-bits check — either way the file is refused. use std::os::unix::fs::PermissionsExt; - let path = std::env::temp_dir().join(format!("pm-idfake-{}", std::process::id())); + let fixture = crate::test_util::temp_dir::TestDir::new("server"); + let path = fixture.join("fixture"); fs::write(&path, b"fake id").unwrap(); fs::set_permissions(&path, fs::Permissions::from_mode(0o666)).unwrap(); let p = path.to_str().unwrap().to_string(); @@ -708,9 +773,7 @@ mod tests { fn preflight_rejects_empty_resolved_value() { // sweep 2026-08-07 D4: zero bytes means refusal on the wire, so // an empty value must fail at startup, not at first fetch. - let dir = std::env::temp_dir().join(format!("pm-preflight-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); + let dir = crate::test_util::temp_dir::TestDir::new("server"); let env_file = dir.join(".env"); fs::write(&env_file, "KEY=\n").unwrap(); let mut credentials = std::collections::HashMap::new(); @@ -719,6 +782,10 @@ mod tests { Entry { env_file, key: "KEY".to_string(), + env_file_sha256: vec![{ + use sha2::Digest as _; + sha2::Sha256::digest(b"KEY=\n").into() + }], peer_user: None, }, ); @@ -748,6 +815,7 @@ mod tests { Entry { env_file: PathBuf::from("/x/.env"), key: "K".to_string(), + env_file_sha256: Vec::new(), peer_user: None, }, ); @@ -781,4 +849,54 @@ mod tests { let err = read_capped(over_cap, Path::new("/test")).unwrap_err(); assert!(err.contains("size cap"), "{err}"); } + + #[test] + fn socket_domains_are_checked_before_mutation_including_aliases() { + let dir = crate::test_util::temp_dir::TestDir::new("socket-domains"); + let parent = dir.join("sockets"); + fs::create_dir(&parent).unwrap(); + std::os::unix::fs::symlink(&parent, dir.join("alias")).unwrap(); + fs::create_dir_all(dir.join("outside/sub")).unwrap(); + std::os::unix::fs::symlink(dir.join("outside"), parent.join("escape")).unwrap(); + for second in [ + parent.join("B.sock"), + parent.join("nested/B.sock"), + dir.join("alias/B.sock"), + parent.join("unused/../B.sock"), + parent.join("escape/sub/B.sock"), + ] { + let first = parent.join("A.sock"); + let cfg = Config { + keys: KeysSource::File(dir.join(".env.keys")), + credentials: [first.clone(), second.clone()] + .into_iter() + .map(|p| { + ( + p, + Entry { + env_file: dir.join(".env"), + key: "KEY".into(), + env_file_sha256: Vec::new(), + peer_user: None, + }, + ) + }) + .collect(), + }; + let mut peers = [(first.clone(), Some(1001)), (second.clone(), Some(1002))] + .into_iter() + .collect(); + assert!( + validate_socket_domains(&cfg, &peers, 0) + .unwrap_err() + .contains("conflicting ownership") + ); + assert_eq!(fs::read_dir(&parent).unwrap().count(), 1); + peers.insert(second.clone(), Some(1001)); + validate_socket_domains(&cfg, &peers, 0).unwrap(); + peers.insert(first.clone(), None); + peers.insert(second, Some(0)); + validate_socket_domains(&cfg, &peers, 0).unwrap(); + } + } } diff --git a/src/test_util.rs b/src/test_util.rs index 7823a91..9ee49b0 100644 --- a/src/test_util.rs +++ b/src/test_util.rs @@ -1,6 +1,8 @@ //! Test-only shared utilities (compiled under `#[cfg(test)]` only). pub(crate) mod aad_fixture; +pub(crate) mod pty; +pub(crate) mod temp_dir; /// Process-wide lock serializing every unit test that mutates — or /// wholesale snapshots — the process-global environment. The test diff --git a/src/test_util/pty.rs b/src/test_util/pty.rs new file mode 100644 index 0000000..6762948 --- /dev/null +++ b/src/test_util/pty.rs @@ -0,0 +1,113 @@ +//! A bounded pseudo-terminal harness for secret-input regression tests. + +#![allow(dead_code, clippy::unwrap_used, clippy::panic)] + +use std::fs::File; +use std::io::{Read as _, Write as _}; +use std::os::fd::FromRawFd as _; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::time::{Duration, Instant}; + +pub struct TestPty { + master: File, + pub slave: File, + pub output: Vec, + child: Option, +} + +impl TestPty { + pub fn new() -> Self { + let (mut master, mut slave) = (-1, -1); + // SAFETY: valid output pointers; null optional arguments request default settings. + assert_eq!( + unsafe { + libc::openpty( + &mut master, + &mut slave, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }, + 0 + ); + // SAFETY: openpty returned two new descriptors, each transferred once to File. + let (master, slave) = unsafe { (File::from_raw_fd(master), File::from_raw_fd(slave)) }; + Self { + master, + slave, + output: Vec::new(), + child: None, + } + } + + pub fn spawn(&mut self, command: &mut Command) { + self.child = Some( + command + .stdin(Stdio::from(self.slave.try_clone().unwrap())) + .stdout(Stdio::from(self.slave.try_clone().unwrap())) + .stderr(Stdio::from(self.slave.try_clone().unwrap())) + .spawn() + .unwrap(), + ); + } + + pub fn send(&mut self, bytes: &[u8]) { + self.master.write_all(bytes).unwrap(); + } + + fn receive(&mut self) { + let mut fds = [rustix::event::PollFd::new( + &self.master, + rustix::event::PollFlags::IN, + )]; + let timeout = rustix::event::Timespec { + tv_sec: 0, + tv_nsec: 20_000_000, + }; + if rustix::event::poll(&mut fds, Some(&timeout)).unwrap() != 0 { + let mut bytes = [0; 4096]; + if let Ok(count) = self.master.read(&mut bytes) { + self.output.extend_from_slice(&bytes[..count]); + } + } + } + + pub fn expect(&mut self, needle: &str) { + let deadline = Instant::now() + Duration::from_secs(5); + while !String::from_utf8_lossy(&self.output).contains(needle) { + assert!( + Instant::now() < deadline, + "missing {needle:?}: {}", + String::from_utf8_lossy(&self.output) + ); + self.receive(); + } + } + + pub fn signal(&self, signal: rustix::process::Signal) { + let pid = rustix::process::Pid::from_raw(self.child.as_ref().unwrap().id() as i32).unwrap(); + rustix::process::kill_process(pid, signal).unwrap(); + } + + pub fn wait(&mut self) -> ExitStatus { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + self.receive(); + if let Some(status) = self.child.as_mut().unwrap().try_wait().unwrap() { + self.receive(); + return status; + } + assert!(Instant::now() < deadline, "child did not exit"); + } + } +} + +impl Drop for TestPty { + fn drop(&mut self) { + if let Some(child) = &mut self.child { + let _ = child.kill(); + let _ = child.wait(); + } + } +} diff --git a/src/test_util/temp_dir.rs b/src/test_util/temp_dir.rs new file mode 100644 index 0000000..7ba00a6 --- /dev/null +++ b/src/test_util/temp_dir.rs @@ -0,0 +1,43 @@ +//! Private, atomically created test workspaces with scoped cleanup. +#![allow(dead_code, clippy::unwrap_used, clippy::panic)] + +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; + +/// A private test directory; path access never releases its cleanup guard. +#[derive(Debug)] +pub struct TestDir { + path: PathBuf, + _guard: tempfile::TempDir, +} + +impl TestDir { + /// Create a fresh owner-only workspace, or fail before any fixture writes. + pub fn new(tag: &str) -> Self { + // Short names leave room for Unix socket paths on Darwin. + let guard = tempfile::Builder::new() + .prefix("pm-") + .permissions(std::fs::Permissions::from_mode(0o700)) + .tempdir() + .unwrap_or_else(|e| panic!("test directory ({tag}): {e}")); + let path = std::fs::canonicalize(guard.path()).unwrap(); + Self { + path, + _guard: guard, + } + } +} + +impl std::ops::Deref for TestDir { + type Target = PathBuf; + + fn deref(&self) -> &PathBuf { + &self.path + } +} + +impl AsRef for TestDir { + fn as_ref(&self) -> &Path { + &self.path + } +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index ef85a58..5b168ed 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -6,6 +6,8 @@ #[path = "../../src/test_util/aad_fixture.rs"] pub mod aad_fixture; +#[path = "../../src/test_util/temp_dir.rs"] +pub mod temp_dir; use std::fs; use std::path::{Path, PathBuf}; @@ -31,15 +33,8 @@ pub fn enc(value: &str) -> String { format!("encrypted:{}", BASE64.encode(ct)) } -pub fn tmpdir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!( - "postmaster-exec-{tag}-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); - d +pub fn tmpdir(tag: &str) -> temp_dir::TestDir { + temp_dir::TestDir::new(tag) } pub fn write_env_file(dir: &Path, name: &str, lines: &[String]) -> PathBuf { diff --git a/tests/exec_check.rs b/tests/exec_check.rs index 3a515b2..afeb06a 100644 --- a/tests/exec_check.rs +++ b/tests/exec_check.rs @@ -1,5 +1,8 @@ #![allow(clippy::unwrap_used, clippy::panic, missing_docs)] +#[path = "../src/test_util/temp_dir.rs"] +mod temp_dir; + use std::path::{Path, PathBuf}; use std::process::Command; @@ -13,11 +16,8 @@ fn fixture(path: &str) -> PathBuf { repo_root().join(path) } -fn tmpdir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("pm-exec-check-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d +fn tmpdir(tag: &str) -> temp_dir::TestDir { + temp_dir::TestDir::new(tag) } fn run_check(config: &Path) -> std::process::Output { diff --git a/tests/exec_conformance/daemon.rs b/tests/exec_conformance/daemon.rs index a5b9e60..1935f1e 100644 --- a/tests/exec_conformance/daemon.rs +++ b/tests/exec_conformance/daemon.rs @@ -3,6 +3,7 @@ //! serve/fetch roundtrip and the startup preflight refusal, which the //! unit tests only exercise in-process. +use sha2::Digest as _; use std::process::Command; use std::time::{Duration, Instant}; @@ -71,14 +72,16 @@ fn daemon_serves_configured_peer_under_any_umask() { fn daemon_roundtrip(mask: &str, peer_user: Option<&str>) { let d = common::tmpdir("daemon"); + let encrypted = common::enc("postgres://real-roundtrip"); let env = common::write_env_file( &d, ".env.production", &[ format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), - format!("DB_URL=\"{}\"", common::enc("postgres://real-roundtrip")), + format!("DB_URL=\"{}\"", encrypted), ], ); + let hash = hex::encode(sha2::Sha256::digest(std::fs::read(&env).unwrap())); let keys = common::write_keys_file(&d, "PRODUCTION", &[common::TEST_SK_HEX]); // Bound directly under the tmpdir: unix socket paths are length-capped // (104 bytes on darwin), and the tmpdir path is already long. @@ -92,6 +95,7 @@ fn daemon_roundtrip(mask: &str, peer_user: Option<&str>) { "env_file": env, "key": "DB_URL", "peer_user": peer_user, + "env_file_sha256": [hash], }}, }) .to_string(), @@ -136,6 +140,29 @@ fn daemon_roundtrip(mask: &str, peer_user: Option<&str>) { String::from_utf8_lossy(&out.stderr) ); assert_eq!(out.stdout, b"postgres://real-roundtrip"); + + let original = std::fs::read(&env).unwrap(); + for replacement in [ + format!("DB_URL='{}'\n", common::enc("foreign-secret")), + "DB_URL=${PATH}\n".into(), + ] { + std::fs::write(&env, replacement).unwrap(); + let refused = Command::new(env!("CARGO_BIN_EXE_postmaster")) + .arg("fetch") + .arg(&sock) + .output() + .unwrap(); + assert!(!refused.status.success()); + assert!(refused.stdout.is_empty()); + } + std::fs::write(&env, original).unwrap(); + let restored = Command::new(env!("CARGO_BIN_EXE_postmaster")) + .arg("fetch") + .arg(&sock) + .output() + .unwrap(); + assert!(restored.status.success()); + assert_eq!(restored.stdout, b"postgres://real-roundtrip"); } #[test] @@ -152,7 +179,7 @@ fn daemon_preflight_refuses_an_empty_credential_at_startup() { std::fs::write( &cfg, format!( - r#"{{"keys":{{"file":"{}"}},"credentials":{{"{}":{{"env_file":"{}","key":"EMPTY"}}}}}}"#, + r#"{{"keys":{{"file":"{}"}},"credentials":{{"{}":{{"env_file":"{}","key":"EMPTY","env_file_sha256":["7819c04858487b8325a083235e0697f271991cb446086084807fec586dc27427"]}}}}}}"#, keys.display(), sock.display(), env.display() diff --git a/tests/exec_conformance/main.rs b/tests/exec_conformance/main.rs index dfd14cf..88d3764 100644 --- a/tests/exec_conformance/main.rs +++ b/tests/exec_conformance/main.rs @@ -7,12 +7,27 @@ mod daemon; mod env_mode; mod files_mode; mod keys_verify; +mod setup; use postmaster::adapter::KeyNaming; use std::path::Path; use std::process::Command; +#[test] +fn fixture_directories_are_private_and_unique() { + use std::os::unix::fs::PermissionsExt; + let first = common::tmpdir("private"); + std::fs::write(first.join("sentinel"), b"retained").unwrap(); + let second = common::tmpdir("private"); + assert_ne!(first.as_path(), second.as_path()); + assert_eq!( + std::fs::metadata(&first).unwrap().permissions().mode() & 0o777, + 0o700 + ); + assert_eq!(std::fs::read(first.join("sentinel")).unwrap(), b"retained"); +} + #[test] fn helper_ciphertext_decrypts_with_test_key() { let v = common::enc("hello $(rm -rf /) `x` \"q\" \nline2"); diff --git a/tests/exec_conformance/setup.rs b/tests/exec_conformance/setup.rs new file mode 100644 index 0000000..99ebf95 --- /dev/null +++ b/tests/exec_conformance/setup.rs @@ -0,0 +1,160 @@ +//! Exercise real setup input and rotation, including terminal interruption. + +#[path = "../../src/test_util/pty.rs"] +mod pty; + +use std::io::{Read as _, Write as _}; +use std::os::unix::fs::PermissionsExt as _; +use std::process::{Command, Stdio}; + +use crate::common; + +fn setup_command(dir: &std::path::Path, force: bool) -> Command { + let config = dir.join("setup.json"); + std::fs::write(&config, serde_json::json!({"mode":"env", "keys":[{"file":dir.join(".env.keys")}], "env_files":[dir.join(".env")]}).to_string()).unwrap(); + let mut command = Command::new(env!("CARGO_BIN_EXE_postmaster")); + command + .args(["setup", "--config"]) + .arg(config) + .arg("--keys-dir") + .arg(dir.join("provisioning")); + if force { + command.arg("--force"); + } + command +} + +#[test] +fn file_input_hides_secrets_and_restores_echo_before_termination() { + for force in [false, true] { + for interrupt in [false, true] { + let dir = common::tmpdir("setup-tty"); + if force { + common::write_keys_file(&dir, "", &[common::TEST_SK_HEX]); + } + let mut pty = pty::TestPty::new(); + let original = rustix::termios::tcgetattr(&pty.slave).unwrap().local_modes; + pty.spawn(&mut setup_command(&dir, force)); + pty.expect("[y/N]"); + pty.send(b"y\n"); + pty.expect("Paste the keys file contents"); + assert!( + !rustix::termios::tcgetattr(&pty.slave) + .unwrap() + .local_modes + .contains(rustix::termios::LocalModes::ECHO) + ); + if interrupt { + pty.send(b"PRIVATE_SENTINEL\n"); + pty.signal(rustix::process::Signal::TERM); + } else { + pty.send( + format!( + "# PRIVATE_SENTINEL\nDOTENV_PRIVATE_KEY={}\n", + common::TEST_SK_HEX + ) + .as_bytes(), + ); + pty.send(&[4]); + } + assert_eq!( + pty.wait().success(), + !interrupt, + "{}", + String::from_utf8_lossy(&pty.output) + ); + assert_eq!( + rustix::termios::tcgetattr(&pty.slave).unwrap().local_modes, + original + ); + assert!(!String::from_utf8_lossy(&pty.output).contains("PRIVATE_SENTINEL")); + if interrupt && !force { + assert!(!dir.join(".env.keys").exists()); + } + } + } +} + +#[test] +fn rotation_rejects_inode_substitution_after_confirmation() { + let dir = common::tmpdir("rotation-swap"); + let keys = common::write_keys_file(&dir, "", &[common::TEST_SK_HEX]); + let target = dir.join("sentinel"); + std::fs::write(&target, b"untouched").unwrap(); + let mut pty = pty::TestPty::new(); + pty.spawn(&mut setup_command(&dir, true)); + pty.expect("[y/N]"); + pty.send(b"y\n"); + pty.expect("Paste the keys file contents"); + std::fs::rename(&keys, dir.join("original")).unwrap(); + std::os::unix::fs::symlink(&target, &keys).unwrap(); + pty.send(format!("DOTENV_PRIVATE_KEY={}\n", "22".repeat(32)).as_bytes()); + pty.send(&[4]); + assert!(!pty.wait().success()); + assert_eq!(std::fs::read(&target).unwrap(), b"untouched"); + assert!(String::from_utf8_lossy(&pty.output).contains("changed while awaiting input")); +} + +#[test] +fn partial_noncanonical_input_does_not_delay_terminal_restoration() { + use rustix::termios::{LocalModes, OptionalActions, SpecialCodeIndex, tcgetattr, tcsetattr}; + let dir = common::tmpdir("raw-input"); + let mut pty = pty::TestPty::new(); + let mut original = tcgetattr(&pty.slave).unwrap(); + original.local_modes.remove(LocalModes::ICANON); + original.special_codes[SpecialCodeIndex::VMIN] = 1; + original.special_codes[SpecialCodeIndex::VTIME] = 0; + tcsetattr(&pty.slave, OptionalActions::Now, &original).unwrap(); + pty.spawn(&mut setup_command(&dir, false)); + pty.expect("[y/N]"); + pty.send(b"y\n"); + pty.expect("Paste the keys file contents"); + pty.send(b"PRIVATE_SENTINEL"); + std::thread::sleep(std::time::Duration::from_millis(100)); + pty.signal(rustix::process::Signal::TERM); + assert!(!pty.wait().success()); + assert_eq!( + tcgetattr(&pty.slave).unwrap().local_modes, + original.local_modes + ); + assert!(!String::from_utf8_lossy(&pty.output).contains("PRIVATE_SENTINEL")); + assert!(!dir.join(".env.keys").exists()); +} + +#[test] +fn redirected_rotation_preserves_old_handles_and_read_only_files() { + for mode in [0o400, 0o600] { + let dir = common::tmpdir("rotation-pipe"); + let keys = common::write_keys_file(&dir, "", &[common::TEST_SK_HEX]); + std::fs::set_permissions(&keys, std::fs::Permissions::from_mode(mode)).unwrap(); + let old = std::fs::read(&keys).unwrap(); + let mut handle = std::fs::File::open(&keys).unwrap(); + let mut child = setup_command(&dir, true) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let contents = format!("DOTENV_PRIVATE_KEY={}\n", "22".repeat(32)); + child + .stdin + .take() + .unwrap() + .write_all(format!("y\n{contents}").as_bytes()) + .unwrap(); + let output = child.wait_with_output().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let mut retained = Vec::new(); + handle.read_to_end(&mut retained).unwrap(); + assert_eq!(retained, old); + assert_eq!(std::fs::read(&keys).unwrap(), contents.as_bytes()); + assert_eq!( + std::fs::metadata(&keys).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } +} From b76a780b79ae9ea9794c6ba8693d3a4fc8488a7c Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Sun, 8 Nov 2026 13:42:29 -0600 Subject: [PATCH 39/47] fix: validate key access and restore terminal input safely --- .github/actions/setup-rust/action.yml | 27 +---- .github/actions/setup-rust/test.py | 14 ++- CHANGELOG.md | 15 ++- docs/src/architecture/threat-model.md | 11 +- docs/src/getting-started/key-provisioning.md | 15 ++- docs/src/reference/cli.md | 4 +- docs/src/reference/launcher-contract.md | 9 +- docs/src/unsafe-code/index.md | 2 +- docs/src/unsafe-code/macos-libc-boundary.md | 7 +- docs/src/unsafe-code/signal-deferral.md | 16 ++- src/keys/dotenv.rs | 23 +--- src/keys/load.rs | 76 ++++++++++++ src/keys/mod.rs | 2 + src/keys/provisioning/input.rs | 120 +++++++++++++++++-- src/keys/provisioning/mod.rs | 2 + src/keys/verify.rs | 29 ++++- src/launcher.rs | 4 +- src/secret_files.rs | 13 +- src/secret_files/acl.rs | 36 ++++-- src/server.rs | 68 ++++++++--- src/test_util/pty.rs | 6 +- tests/exec_conformance/setup.rs | 25 ++++ 22 files changed, 412 insertions(+), 112 deletions(-) diff --git a/.github/actions/setup-rust/action.yml b/.github/actions/setup-rust/action.yml index 647efb6..3a686bc 100644 --- a/.github/actions/setup-rust/action.yml +++ b/.github/actions/setup-rust/action.yml @@ -77,32 +77,7 @@ runs: CARGO_INSTALL_TARGET_DIR: ${{ inputs.install-target-dir }} run: | set -euo pipefail - # Probe by actually running `just`, not `command -v just`: a mise/asdf - # shim on PATH satisfies `command -v` but fails at call time with - # "No version is set for shim: just" when no version is pinned. If it - # does not run, or runs but reports a version other than the pin, install - # the pinned just and prepend ~/.cargo/bin so the real binary shadows - # any lingering shim for the rest of the job. - install_pinned_just() { - cargo install just --version "$JUST_VERSION" --locked --target-dir "$CARGO_INSTALL_TARGET_DIR" - if [[ -n "${GITHUB_PATH:-}" ]]; then - echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" - fi - "$HOME/.cargo/bin/just" --version - } - if found="$(just --version 2>/dev/null)"; then - # `just --version` reports "just X.Y.Z" - found_version="${found#just }" - if [[ "$found_version" == "$JUST_VERSION" ]]; then - echo "just already available at pinned version: $(command -v just) -> $found" - else - echo "just version mismatch: found '$found', pinned is 'just $JUST_VERSION'; installing pinned version" - install_pinned_just - fi - else - echo "no runnable just found; installing pinned just $JUST_VERSION" - install_pinned_just - fi + bash "$GITHUB_ACTION_PATH/install-tool.sh" just "$JUST_VERSION" "$CARGO_INSTALL_TARGET_DIR" - name: Install cargo-deny if: ${{ inputs.install-cargo-deny == 'true' }} diff --git a/.github/actions/setup-rust/test.py b/.github/actions/setup-rust/test.py index ceefd6c..009dcee 100644 --- a/.github/actions/setup-rust/test.py +++ b/.github/actions/setup-rust/test.py @@ -1,4 +1,4 @@ -"""Exercise optional tool setup without installing packages. +"""Exercise Cargo tool setup without installing packages. Run: python3 .github/actions/setup-rust/test.py [path-to-bash] """ @@ -15,6 +15,7 @@ action = (action_dir / "action.yml").read_text() bash = Path(sys.argv[1] if len(sys.argv) > 1 else "/bin/bash").resolve() tools = { + "just": ("Install just", "JUST_VERSION", "1.51.0"), "cargo-deny": ("Install cargo-deny", "CARGO_DENY_VERSION", "0.20.2"), "cargo-audit": ("Install cargo-audit", "CARGO_AUDIT_VERSION", "0.22.2"), "mdbook": ("Install mdbook", "MDBOOK_VERSION", "0.5.4"), @@ -22,7 +23,7 @@ } scenarios = ( "current", "outdated", "broken", "missing", "install-fails", "installed-wrong", - "custom-root", + "custom-root", "default-home", ) failures = [] for tool, (step, version_var, version) in tools.items(): @@ -31,8 +32,10 @@ for scenario in scenarios: with tempfile.TemporaryDirectory(prefix="postmaster-setup-") as tmp: root = Path(tmp) + home = root / "home" + home.mkdir() cargo_home = root / "cargo home" - install_root = root / "install root" if scenario == "custom-root" else cargo_home + install_root = root / "install root" if scenario == "custom-root" else (home / ".cargo" if scenario == "default-home" else cargo_home) bin_dir = install_root / "bin" bin_dir.mkdir(parents=True) shims = root / "shims" @@ -42,6 +45,7 @@ env = os.environ.copy() env.pop("CARGO_INSTALL_ROOT", None) env.update( + HOME=str(home), PATH=f"{shims}:/usr/bin:/bin", CARGO_HOME=str(cargo_home), CARGO_INSTALL_TARGET_DIR=str(root / "build target"), @@ -53,6 +57,8 @@ TEST_SCENARIO=scenario, TEST_INSTALL_ROOT=str(install_root), ) + if scenario == "default-home": + env.pop("CARGO_HOME", None) if scenario == "custom-root": env["CARGO_INSTALL_ROOT"] = str(install_root) for name, (_, var, pinned) in tools.items(): @@ -113,4 +119,4 @@ if failures: raise SystemExit("\n".join(failures)) -print(f"Optional tool setup: {len(tools) * len(scenarios)} cases pass") +print(f"Cargo tool setup: {len(tools) * len(scenarios)} cases pass") diff --git a/CHANGELOG.md b/CHANGELOG.md index 24d79f9..67782f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,10 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). `DOTENV_PRIVATE_KEY*`; bundles use `POSTMASTER_KEY`. - Reads macOS Keychain items through the Security.framework API. - Hides private-key terminal input and restores settings before pending - termination or suspend signals. Forced key-file replacement verifies inode + termination or suspend signals. Failed or interrupted terminal reads discard + unread input; successful reads retain queued values. Idle noncanonical reads + wait for input, and prompt failures restore settings before returning errors. + Forced key-file replacement verifies inode identity and ownership before publishing a fresh owner-only file. - Authorizes daemon dotenv files against trusted `env_file_sha256` hashes before parsing or decryption, at startup and on every fetch. Multiple hashes @@ -38,7 +41,8 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). closed when unavailable or invalid. - Checks private key files through an opened descriptor for ownership and restrictive permissions. It rejects final-component symlinks and private - key paths in the Nix store. + key paths in the Nix store. On macOS, runtime loading and file-source setup + rechecks reject untrusted read or mutation ACL grants without changing files. - Keeps runtime key loading and setup verification on the same key-variable naming rules. Environment loading skips non-UTF-8 entries. - Supports `env` mode for direct environment injection. @@ -89,8 +93,9 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). parsing bounds source bytes, assignments, and expanded values before growth, while syntax errors omit input contents. - Verifies external tools before use with macOS code-signature checks or - Linux ownership and permission checks. Linux `id` lookup uses verified - absolute paths. + Linux ownership and permission checks. Linux helpers reject group or other + write permissions. `id` lookup resolves system aliases, including NixOS + profiles, verifies the target and its directory ancestry, then invokes it. - Validates daemon configuration at the root and nested credential mappings. Startup rejects relative paths, symlinked socket parents, and empty credentials. @@ -133,6 +138,8 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). the pinned installer digest before execution. Official GitHub actions and helper tools use pinned versions. Nix installer temporary files work with GNU and macOS `mktemp`. + Cargo tool installation honors `CARGO_INSTALL_ROOT` and `CARGO_HOME` and + verifies the selected executables before adding their directory to `PATH`. - Runs formatting, Clippy, and Markdown lint from pre-commit hooks. Pre-push hooks run the Rust gate, dependency policy, and advisory checks. The Rust gate includes native, release, and Linux-target Clippy; the diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index cafa1d8..fac1a8b 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -187,7 +187,10 @@ where secret material is read or written: (`mode & 0o077 == 0`) and that the owner matches the current effective user ID. This fd-based approach eliminates the TOCTOU window between open - and permission check. + and permission check. On macOS, the same descriptor is checked for ACL + grants that let principals other than root or the effective user read or + modify the file. File-source setup rechecks use the same validation. + Both checks leave source ACLs intact. - **Credential source paths** are checked with `symlink_metadata` before loading, rejecting symlinks at the path level. The `O_NOFOLLOW` open in `KeyRing::load` provides defense-in-depth at @@ -229,8 +232,10 @@ does invoke in secret-adjacent paths (`/usr/bin/id`, `/sbin/mount`, - **macOS:** `codesign -v` verifies a valid Apple code signature (defense-in-depth; the binaries are also SIP-protected). -- **Linux:** verified as regular files owned by root (uid 0) and not - world-writable. +- **Linux:** verified as regular files owned by root (uid 0) with no group + or other write permissions. `id` lookup resolves system aliases, including + the NixOS system profile, verifies the target and its directory ancestry, + then invokes the resolved target. ### Input validation diff --git a/docs/src/getting-started/key-provisioning.md b/docs/src/getting-started/key-provisioning.md index f9742d4..3aa1c9a 100644 --- a/docs/src/getting-started/key-provisioning.md +++ b/docs/src/getting-started/key-provisioning.md @@ -48,6 +48,11 @@ by the effective uid of the loading process, so `chown` it to the service user (or run the file-owning step as that user) — a root-owned keys file fails closed for a service running as a normal user. +On macOS, runtime loading and file-source `setup --recheck` also reject ACL +grants that let anyone other than root or the effective user read or modify the +key file. +These checks leave the file and its ACL intact, including read-only files. + ## Strategy B: TPM2 / host-sealed blob Fully declarative — the key is sealed to the host's TPM2 and can only @@ -116,10 +121,12 @@ Security.framework API (`security-framework` crate). `postmaster setup` hides terminal input for both key files and Keychain values. It restores terminal settings when input finishes, fails, or receives a -catchable termination or suspend signal. Redirected key-file input still -accepts multiple lines through EOF. `--force` publishes a fresh 0600 key-file -inode after confirmation and refuses a substituted, foreign, linked, or -special file. Existing open handles keep the old contents. +catchable termination or suspend signal. Failed or interrupted terminal reads +discard unread input before restoration, so a partial secret cannot reach the +next terminal reader. Successful reads retain queued values. Redirected +key-file input still accepts multiple lines through EOF. `--force` publishes +a fresh 0600 key-file inode after confirmation and refuses a substituted, +foreign, linked, or special file. Existing open handles keep the old contents. ## Rotation diff --git a/docs/src/reference/cli.md b/docs/src/reference/cli.md index f518192..7f5976a 100644 --- a/docs/src/reference/cli.md +++ b/docs/src/reference/cli.md @@ -130,7 +130,9 @@ Default keys directory: Secret terminal input has echo disabled until the read finishes. Postmaster restores terminal settings before delivering a pending termination or suspend signal. Key files accept multiline input through EOF; Keychain values use one -trimmed line. Redirected input keeps the same format and buffering. +trimmed line. Failed or interrupted terminal reads discard unread input before +restoration. Successful reads retain queued values. Redirected input keeps the +same format and buffering. Forced key-file replacement verifies ownership, regular-file type, and single link count before changing permissions. It pins the parent, checks that the diff --git a/docs/src/reference/launcher-contract.md b/docs/src/reference/launcher-contract.md index af29ee5..595fe21 100644 --- a/docs/src/reference/launcher-contract.md +++ b/docs/src/reference/launcher-contract.md @@ -395,13 +395,18 @@ this mode — it dispatches on whether `sockets` is empty: - **Keys file permissions and ownership.** `KeyRing::load` opens the keys file with `O_NOFOLLOW` and `fstat`s the fd to verify: no group/world access (`mode & 0o077 == 0`), and owned by the current - euid. A world-readable or symlinked keys file fails closed. + euid. A world-readable or symlinked keys file fails closed. On macOS, + runtime loading and file-source setup rechecks also reject ACL grants that let + principals other than root or the effective user read or modify the file. + These checks do not change the source file's ACL. - **External binary verification.** Keychain access uses the Security.framework API in-process — no external binary is invoked for it. The external binaries postmaster does invoke (`/usr/bin/id`, `/sbin/mount`, `/usr/bin/hdiutil` on macOS) are verified first: `codesign -v` on macOS; on Linux, verified as regular files owned by - root (uid 0) and not world-writable. + root (uid 0) with no group or other write permissions. Linux `id` lookup + resolves system aliases, verifies the target and its directory ancestry, + then invokes that resolved target. This includes the NixOS system profile. - **`verify_ramdisk` (darwin ramdisk guard).** When set, before any plaintext is written the launcher runs two checks: it shells out to `/sbin/mount` and requires the configured mount point to appear as an diff --git a/docs/src/unsafe-code/index.md b/docs/src/unsafe-code/index.md index e96b14b..aaa0cc4 100644 --- a/docs/src/unsafe-code/index.md +++ b/docs/src/unsafe-code/index.md @@ -28,7 +28,7 @@ Every `unsafe` block requires: | `monitor.rs` (signal mask/wait ops, pidfd+poll / kqueue, `_exit`/`exit_group`, raw stderr write) | macOS, Linux | Sibling monitor: synchronous stop consumption, liveness watch, cleanup on every death path | [monitor](./monitor.md) | | `server.rs` (`peer_euid`) | macOS | Peer credential check via `getpeereid(2)` | [macos-libc-boundary](./macos-libc-boundary.md) | | `server.rs` (`harden_process`) | macOS, release only | `PT_DENY_ATTACH` anti-debug hardening | [macos-libc-boundary](./macos-libc-boundary.md) | -| `secret_files/acl.rs` | macOS | Inspect directory ACL grants and clear new private-file ACLs | [macos-libc-boundary](./macos-libc-boundary.md#extended-acls) | +| `secret_files/acl.rs` | macOS | Inspect directory and key-file ACL grants; clear new private-file ACLs | [macos-libc-boundary](./macos-libc-boundary.md#extended-acls) | | `test_util/pty.rs` | all, test-only | Create and own pseudo-terminal descriptors for input restoration tests | [signal-deferral](./signal-deferral.md#tests) | | `server.rs` (socket activation) | Linux | `UnixListener::from_raw_fd` on systemd-inherited sockets | [systemd-fd-ownership](./systemd-fd-ownership.md) | | `keys/source.rs`, `keys/env.rs`, `keys/provisioning/mod.rs` (test modules) | all, test-only | `set_var`/`remove_var` (unsafe on edition 2024) | [test-env-mutation](./test-env-mutation.md) | diff --git a/docs/src/unsafe-code/macos-libc-boundary.md b/docs/src/unsafe-code/macos-libc-boundary.md index dcb1384..017fa5f 100644 --- a/docs/src/unsafe-code/macos-libc-boundary.md +++ b/docs/src/unsafe-code/macos-libc-boundary.md @@ -75,13 +75,18 @@ does not expose. Mode bits alone do not restrict extended ACL grants on macOS. Directory checks reject grants to principals other than root or the effective user that permit replacement or inherited reads of fresh files. Fresh private files have their ACLs cleared before plaintext writes. +Runtime key-file loading and file-source setup rechecks use the same +descriptor-based inspection to reject untrusted read or mutation grants without +changing the source ACL. Root and the effective user remain trusted principals. The wrapper owns each ACL and qualifier allocation and frees it once with `acl_free`. Entry pointers borrow the live ACL; output pointers have initialized storage and stay valid through each call. Qualifiers use Darwin's fixed 16-byte UUID layout and are compared with UUIDs resolved for trusted users. Descriptor borrows keep the file open throughout each call. Failures return -errors before plaintext is written. +errors before plaintext is read or written. Native tests install replacement and inheritance grants in private fixtures, verify rejection, and check that published files have no extended entries. +Key-file tests cover read/write grants, trusted-user grants, read-only modes, +and repeated runtime loads and file-source setup rechecks without ACL mutation. diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md index f536770..a22b8e9 100644 --- a/docs/src/unsafe-code/signal-deferral.md +++ b/docs/src/unsafe-code/signal-deferral.md @@ -32,10 +32,13 @@ running no destructors). The parent calls `restore_mask()` before Setup reuses the guard while reading secrets from a terminal. `block_input()` also blocks SIGTSTP, so suspension cannot hand back a terminal with echo disabled. Terminal reads use nonblocking stdin, including buffered and noncanonical -input. The loop checks pending signals while polling, restores terminal -settings and stdin flags, then restores the saved signal mask. Setup refuses -terminal input if -masking fails. Redirected input keeps stdin's existing buffer and normal signal +input. Noncanonical reads temporarily use `VMIN=1` and `VTIME=0`, so an idle +read does not look like EOF. The loop checks pending signals while polling. +Failed or interrupted reads flush unread terminal input before restoring +terminal settings, stdin flags, and the saved signal mask. Successful reads +retain queued values. Prompt writes return errors, allowing restoration even +when stderr fails. Setup refuses terminal input if masking fails. +Redirected input keeps stdin's existing buffer and normal signal behavior. Linux uses rustix's raw signal APIs; Darwin uses libc. ## Why Unsafe @@ -82,8 +85,11 @@ mirroring production) and by the exec integration suites flag-handler test was removed with the handler. Input tests use pseudo-terminals to check hidden single-line and multiline -input, read failures, and terminal restoration. Real setup subprocesses cover +input, idle noncanonical reads, prompt failures, queued values, and terminal +restoration. Real setup subprocesses cover initial files, forced rotation, redirected input, and SIGTERM during input. +The interrupted canonical-input test checks what the next terminal reader +receives. The test-only `openpty` call receives valid output pointers and null optional settings; each returned descriptor transfers exactly once into an owning `File`. The harness kills and waits for its child on teardown. diff --git a/src/keys/dotenv.rs b/src/keys/dotenv.rs index 8dfffc4..9107c1c 100644 --- a/src/keys/dotenv.rs +++ b/src/keys/dotenv.rs @@ -10,14 +10,12 @@ use std::env; use zeroize::Zeroizing; type Result = std::result::Result; -type Error = &'static str; const INVALID: &str = "invalid dotenv syntax"; const LIMIT: &str = "dotenv resource limit exceeded"; const MAX_VALUE_BYTES: usize = 16 * 1024 * 1024; const MAX_PARSED_BYTES: usize = 64 * 1024 * 1024; const MAX_ENTRIES: usize = 65_536; -// for readability's sake type ParsedLine = Result)>>; fn parse_line( @@ -43,15 +41,11 @@ impl<'parse> LineParser<'parse> { ) -> LineParser<'parse> { LineParser { substitution_data, - line: line.trim_end(), // we don’t want trailing whitespace + line: line.trim_end(), budget, } } - fn err(&self) -> Error { - INVALID - } - fn parse_line(&mut self) -> ParsedLine { self.skip_whitespace(); // if its an empty line or a comment, skip it @@ -95,7 +89,7 @@ impl<'parse> LineParser<'parse> { .line .starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') { - return Err(self.err()); + return Err(INVALID); } let index = match self .line @@ -111,7 +105,7 @@ impl<'parse> LineParser<'parse> { fn expect_equal(&mut self) -> Result<()> { if !self.line.starts_with('=') { - return Err(self.err()); + return Err(INVALID); } self.line = &self.line[1..]; Ok(()) @@ -142,17 +136,13 @@ fn parse_value( let mut escaped = false; let mut expecting_end = false; - //FIXME can this be done without yet another allocation per line? let mut output = Zeroizing::new(String::new()); let mut substitution_mode = SubstitutionMode::None; let mut substitution_name = String::new(); for c in input.chars() { - //the regex _should_ already trim whitespace off the end - //expecting_end is meant to permit: k=v #comment - //without affecting: k=v#comment - //and throwing on: k=v w + // A whitespace-separated comment ends the value; an attached # stays literal. if expecting_end { if c == ' ' || c == '\t' { continue; @@ -162,10 +152,6 @@ fn parse_value( return Err(INVALID); } } else if escaped { - //TODO I tried handling literal \r but various issues - //imo not worth worrying about until there's a use case - //(actually handling backslash 0x10 would be a whole other matter) - //then there's \v \f bell hex... etc match c { '\\' | '\'' | '"' | '$' | ' ' => push_char(&mut output, c)?, 'n' => push_char(&mut output, '\n')?, // handle \n case @@ -243,7 +229,6 @@ fn parse_value( } } - //XXX also fail if escaped? or... if substitution_mode == SubstitutionMode::EscapedBlock || strong_quote || weak_quote { Err(INVALID) } else { diff --git a/src/keys/load.rs b/src/keys/load.rs index 87ebe83..ef99b0b 100644 --- a/src/keys/load.rs +++ b/src/keys/load.rs @@ -52,6 +52,8 @@ pub(super) fn load(path: &Path, namings: &[KeyNaming]) -> Result Result<(), String> { + fn restore(&mut self, discard_input: bool) -> Result<(), String> { + let discarded = if discard_input && (self.terminal.is_some() || self.flags.is_some()) { + rustix::termios::tcflush(std::io::stdin(), rustix::termios::QueueSelector::IFlush) + .map_err(|e| format!("cannot discard terminal input: {e}")) + } else { + Ok(()) + }; let terminal = if let Some(original) = &self.terminal { tcsetattr(std::io::stdin(), OptionalActions::Now, original) .map_err(|e| format!("cannot restore terminal settings: {e}")) @@ -30,13 +36,13 @@ impl EchoGuard { if flags.is_ok() { self.flags = None; } - terminal.and(flags) + discarded.and(terminal).and(flags) } } impl Drop for EchoGuard { fn drop(&mut self) { - if let Err(e) = self.restore() { + if let Err(e) = self.restore(true) { crate::server::log(&e); } } @@ -44,12 +50,12 @@ impl Drop for EchoGuard { /// Read one line or a multiline EOF-terminated value without terminal echo. /// Redirected input uses stdin's existing buffer. Errors never include input values. -#[allow(clippy::print_stderr)] pub(super) fn read_secret(prompt: &str, single_line: bool) -> Result, String> { let stdin = std::io::stdin(); let mut value = Zeroizing::new(String::new()); if !stdin.is_terminal() { - eprintln!("{prompt}"); + writeln!(std::io::stderr().lock(), "{prompt}") + .map_err(|e| format!("cannot write secret input prompt: {e}"))?; let mut input = stdin.lock(); if single_line { input.read_line(&mut value) @@ -71,6 +77,10 @@ pub(super) fn read_secret(prompt: &str, single_line: bool) -> Result Result Result return Err(format!("cannot wait for secret input: {e}")), } } - echo.restore()?; + if signals.input_pending()? { + return Err("secret input interrupted".into()); + } + echo.restore(false)?; Ok(value) } @@ -122,9 +136,19 @@ mod tests { let Ok(style) = std::env::var("POSTMASTER_TEST_INPUT") else { return; }; - let result = read_secret("secret-ready", style == "line"); + let result = read_secret("secret-ready", style != "multiline"); + if style == "prompt-error" { + assert!(result.unwrap_err().contains("prompt")); + return; + } assert!(result.is_ok(), "input failed"); assert_eq!(result.unwrap().trim(), "PRIVATE_SENTINEL"); + if style == "two-lines" { + assert_eq!( + read_secret("second-secret-ready", true).unwrap().trim(), + "NEXT_SENTINEL" + ); + } } #[test] @@ -199,4 +223,82 @@ mod tests { assert_eq!(tcgetattr(&pty.slave).unwrap().local_modes, mode.local_modes); assert!(!String::from_utf8_lossy(&pty.output).contains("PRIVATE_SENTINEL")); } + + #[test] + fn idle_noncanonical_terminal_waits_for_input_and_restores_minimum() { + let mut pty = crate::test_util::pty::TestPty::new(); + let mut original = tcgetattr(&pty.slave).unwrap(); + original.local_modes.remove(LocalModes::ICANON); + original.special_codes[rustix::termios::SpecialCodeIndex::VMIN] = 0; + original.special_codes[rustix::termios::SpecialCodeIndex::VTIME] = 0; + tcsetattr(&pty.slave, OptionalActions::Now, &original).unwrap(); + pty.spawn( + std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "keys::provisioning::input::tests::input_child", + "--nocapture", + ]) + .env("POSTMASTER_TEST_INPUT", "line"), + ); + pty.expect("secret-ready"); + std::thread::sleep(std::time::Duration::from_millis(100)); + pty.send(b"PRIVATE_SENTINEL\n"); + assert!(pty.wait().success()); + let restored = tcgetattr(&pty.slave).unwrap(); + assert_eq!(restored.local_modes, original.local_modes); + assert_eq!( + restored.special_codes[rustix::termios::SpecialCodeIndex::VMIN], + 0 + ); + assert_eq!( + restored.special_codes[rustix::termios::SpecialCodeIndex::VTIME], + 0 + ); + } + + #[test] + fn prompt_error_returns_without_leaving_terminal_modified() { + let mut pty = crate::test_util::pty::TestPty::new(); + let original = tcgetattr(&pty.slave).unwrap().local_modes; + let flags = rustix::fs::fcntl_getfl(&pty.slave).unwrap(); + let (reader, writer) = std::io::pipe().unwrap(); + drop(reader); + pty.spawn_with_stderr( + std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "keys::provisioning::input::tests::input_child", + "--nocapture", + ]) + .env("POSTMASTER_TEST_INPUT", "prompt-error"), + std::process::Stdio::from(writer), + ); + assert!(pty.wait().success()); + assert_eq!(tcgetattr(&pty.slave).unwrap().local_modes, original); + assert_eq!( + rustix::fs::fcntl_getfl(&pty.slave) + .unwrap() + .contains(rustix::fs::OFlags::NONBLOCK), + flags.contains(rustix::fs::OFlags::NONBLOCK) + ); + } + + #[test] + fn successful_line_reads_preserve_the_next_queued_value() { + let mut pty = crate::test_util::pty::TestPty::new(); + pty.spawn( + std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "keys::provisioning::input::tests::input_child", + "--nocapture", + ]) + .env("POSTMASTER_TEST_INPUT", "two-lines"), + ); + pty.expect("secret-ready"); + pty.send(b"PRIVATE_SENTINEL\nNEXT_SENTINEL\n"); + assert!(pty.wait().success()); + assert!(!String::from_utf8_lossy(&pty.output).contains("SENTINEL")); + } } diff --git a/src/keys/provisioning/mod.rs b/src/keys/provisioning/mod.rs index ef43402..7f9a728 100644 --- a/src/keys/provisioning/mod.rs +++ b/src/keys/provisioning/mod.rs @@ -441,6 +441,8 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> stat.st_uid )); } + crate::secret_files::validate_private_file_acl(&fd) + .map_err(|e| format!("{}: {e}", path.display()))?; } KeySourceSpec::Keychain(service) => { #[cfg(target_os = "macos")] diff --git a/src/keys/verify.rs b/src/keys/verify.rs index 2f9ddd5..e85163c 100644 --- a/src/keys/verify.rs +++ b/src/keys/verify.rs @@ -13,7 +13,7 @@ use std::path::Path; /// bypass or a misconfigured environment. /// /// On Linux: verify the file is a regular file, owned by root (uid 0), -/// and not world-writable. There is no universal code-signing mechanism +/// and not group/other writable. There is no universal code-signing mechanism /// on Linux, so ownership and permission checks are the practical /// defense-in-depth boundary. /// @@ -62,9 +62,9 @@ pub fn verify_external_binary(path: &Path) -> Result<(), String> { md.uid() )); } - if md.mode() & 0o002 != 0 { + if md.mode() & 0o022 != 0 { return Err(format!( - "{}: external binary is world-writable; refusing to trust", + "{}: external binary is group/other writable; refusing to trust", path.display() )); } @@ -77,6 +77,29 @@ pub fn verify_external_binary(path: &Path) -> Result<(), String> { mod tests { use super::*; + #[test] + #[cfg(target_os = "linux")] + fn root_owned_helpers_reject_group_and_other_write_permissions() { + use std::os::unix::fs::PermissionsExt as _; + if !rustix::process::geteuid().is_root() { + return; + } + let dir = crate::test_util::temp_dir::TestDir::new("helper-modes"); + let path = dir.join("helper"); + std::fs::write(&path, b"root-controlled helper").unwrap(); + for mode in [0o775, 0o757, 0o777] { + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); + assert!( + verify_external_binary(&path).is_err(), + "mode {mode:o} must fail" + ); + } + for mode in [0o555, 0o755] { + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); + verify_external_binary(&path).unwrap(); + } + } + #[test] #[cfg(target_os = "macos")] fn verify_external_binary_accepts_codesigned_binary() { diff --git a/src/launcher.rs b/src/launcher.rs index 78ae244..149bc99 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -157,8 +157,8 @@ impl TerminationGuard { for sig in signals { set.insert(*sig); } - // SAFETY: the set holds only the four standard termination - // signals — none reserved by any libc in the process (glibc + // SAFETY: the set holds standard termination signals and, for + // terminal input, TSTP — none reserved by any libc (glibc // reserves 32/33, untouched). The launcher is single-threaded at // this point (the exec path spawns no threads; worker threads // exist only in serve mode). diff --git a/src/secret_files.rs b/src/secret_files.rs index 0382f9b..4f4eb2c 100644 --- a/src/secret_files.rs +++ b/src/secret_files.rs @@ -4,8 +4,8 @@ //! All file operations use `O_NOFOLLOW` and fd-based permissions to //! eliminate TOCTOU race conditions against symlink attacks. The secrets //! directory is pinned once by an open fd (`O_DIRECTORY|O_NOFOLLOW`) and -//! every create, stat, and unlink is relative to that pinned inode — -//! paths are never re-resolved. +//! output creation, entry checks, and cleanup are relative to that pinned inode. +//! Exported-path validation separately checks lexical and resolved ancestry. use std::ffi::OsString; use std::fs; @@ -28,6 +28,15 @@ pub(crate) fn clear_file_acl(fd: impl AsFd) -> Result<(), String> { Ok(()) } +/// Check private-file ACL grants on the opened inode without changing it. +pub(crate) fn validate_private_file_acl(fd: impl AsFd) -> Result<(), String> { + #[cfg(target_os = "macos")] + acl::validate_private_file(fd)?; + #[cfg(not(target_os = "macos"))] + let _ = fd; + Ok(()) +} + /// Resolved values keyed by name, each zeroized on drop. pub type Resolved = Vec<(String, Zeroizing>)>; diff --git a/src/secret_files/acl.rs b/src/secret_files/acl.rs index 7bbab0c..8dd6ef0 100644 --- a/src/secret_files/acl.rs +++ b/src/secret_files/acl.rs @@ -55,6 +55,15 @@ pub(super) fn clear(fd: impl AsFd) -> Result<(), String> { /// Reject extended grants that let another principal replace directory entries. pub(super) fn validate(fd: impl AsFd) -> Result<(), String> { + validate_grants(fd, MUTATE, true) +} + +/// Reject untrusted access to private file contents without changing its ACL. +pub(super) fn validate_private_file(fd: impl AsFd) -> Result<(), String> { + validate_grants(fd, MUTATE | (1 << 1), false) +} + +fn validate_grants(fd: impl AsFd, forbidden: u64, check_inheritance: bool) -> Result<(), String> { // SAFETY: every out pointer is initialized storage, entry pointers borrow the live ACL, // and qualifiers are owned UUID allocations with the platform's fixed 16-byte layout. unsafe { @@ -65,7 +74,7 @@ pub(super) fn validate(fd: impl AsFd) -> Result<(), String> { return if matches!(e.raw_os_error(), Some(libc::ENOTSUP | libc::ENOENT)) { Ok(()) } else { - Err(format!("cannot read directory ACL: {e}")) + Err(format!("cannot read ACL: {e}")) }; } let mut root = [0; 16]; @@ -86,28 +95,32 @@ pub(super) fn validate(fd: impl AsFd) -> Result<(), String> { }; } if index == 1024 { - return Err("directory ACL has too many entries".into()); + return Err("ACL has too many entries".into()); } let mut tag = 0; let mut permissions = 0; if acl_get_tag_type(entry, &mut tag) != 0 || acl_get_permset_mask_np(entry, &mut permissions) != 0 { - return Err("cannot inspect directory ACL permissions".into()); + return Err("cannot inspect ACL permissions".into()); } if tag != ALLOW { continue; } let mut flags = std::ptr::null_mut(); - if acl_get_flagset_np(entry, &mut flags) != 0 { - return Err("cannot inspect directory ACL inheritance".into()); + if check_inheritance && acl_get_flagset_np(entry, &mut flags) != 0 { + return Err("cannot inspect ACL inheritance".into()); } - let inherited = acl_get_flag_np(flags, FILE_INHERIT); + let inherited = if check_inheritance { + acl_get_flag_np(flags, FILE_INHERIT) + } else { + 0 + }; if inherited < 0 { - return Err("cannot inspect directory ACL inheritance".into()); + return Err("cannot inspect ACL inheritance".into()); } // An inherited grant can expose a fresh inode before its ACL is cleared. - if permissions & MUTATE == 0 && !(inherited == 1 && permissions & (1 << 1) != 0) { + if permissions & forbidden == 0 && !(inherited == 1 && permissions & (1 << 1) != 0) { continue; } let qualifier = Allocation(acl_get_qualifier(entry)); @@ -116,7 +129,12 @@ pub(super) fn validate(fd: impl AsFd) -> Result<(), String> { } let uuid = std::slice::from_raw_parts(qualifier.0.cast::(), 16); if uuid != root && uuid != user { - return Err("directory ACL permits untrusted replacement".into()); + return Err(if check_inheritance { + "directory ACL permits untrusted replacement" + } else { + "private file ACL permits untrusted access" + } + .into()); } } } diff --git a/src/server.rs b/src/server.rs index 2e0dfd7..0560836 100644 --- a/src/server.rs +++ b/src/server.rs @@ -270,16 +270,16 @@ pub fn uid_of(name: &str) -> Result { // O_NOFOLLOW|CLOEXEC fd) is invoked, and if none verifies the lookup // fails closed. #[cfg(target_os = "macos")] - let id: &str = { + let id = { crate::keys::verify_external_binary(Path::new("/usr/bin/id"))?; - "/usr/bin/id" + PathBuf::from("/usr/bin/id") }; #[cfg(not(target_os = "macos"))] - let id: &str = verified_id_binary()?; - let out = std::process::Command::new(id) + let id = verified_id_binary()?; + let out = std::process::Command::new(&id) .args(["-u", name]) .output() - .map_err(|e| format!("{id}: {e}"))?; + .map_err(|e| format!("{}: {e}", id.display()))?; if !out.status.success() { return Err(format!("peer_user {name:?}: no such user")); } @@ -294,12 +294,12 @@ pub fn uid_of(name: &str) -> Result { /// Candidates are well-known absolute paths in preference order; the /// NixOS path covers systems without /usr/bin or /bin. #[cfg(not(target_os = "macos"))] -fn verified_id_binary() -> Result<&'static str, String> { +fn verified_id_binary() -> Result { const CANDIDATES: [&str; 3] = ["/usr/bin/id", "/bin/id", "/run/current-system/sw/bin/id"]; let mut failures: Vec = Vec::new(); for path in CANDIDATES { match verify_id_candidate(path) { - Ok(()) => return Ok(path), + Ok(target) => return Ok(target), Err(e) => failures.push(e), } } @@ -310,15 +310,18 @@ fn verified_id_binary() -> Result<&'static str, String> { )) } -/// Verify one `id(1)` candidate by fstat on the opened fd -/// (O_NOFOLLOW|CLOEXEC, so a symlink at the path is rejected at open): -/// must be a regular file, owned by root, with no group/other write -/// bits. Same fd-based discipline as the keys-file checks — nothing is -/// ever re-resolved by path. +/// Resolve a system alias, verify its protected target by opened fd, and return +/// that target for invocation. The final open uses O_NOFOLLOW|CLOEXEC. +/// The target must be a regular file owned by root with no group/other write +/// bits. Type, owner and mode are checked on the same opened inode. #[cfg(not(target_os = "macos"))] -fn verify_id_candidate(path: &str) -> Result<(), String> { +fn verify_id_candidate(path: &str) -> Result { + let target = fs::canonicalize(path).map_err(|e| format!("{path}: resolve: {e}"))?; + crate::secret_files::validate_directory_path( + target.parent().ok_or("id requires a parent directory")?, + )?; let fd = rustix::fs::open( - path, + &target, rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC, rustix::fs::Mode::empty(), ) @@ -338,7 +341,7 @@ fn verify_id_candidate(path: &str) -> Result<(), String> { { return Err(format!("{path}: group/other writable; refusing to trust")); } - Ok(()) + Ok(target) } /// Resolve the keys file path from a `KeysSource` configuration. @@ -766,7 +769,40 @@ mod tests { // systems have /usr/bin/id or /bin/id, NixOS has // /run/current-system/sw/bin/id. let id = verified_id_binary().unwrap(); - assert!(id.starts_with('/')); + assert!(id.is_absolute()); + } + + #[test] + #[cfg(target_os = "linux")] + fn id_lookup_accepts_trusted_nix_style_aliases() { + use std::os::unix::fs::PermissionsExt as _; + if !rustix::process::geteuid().is_root() { + return; + } + let dir = crate::test_util::temp_dir::TestDir::new("id-alias"); + let target = dir.join("store/bin"); + fs::create_dir_all(&target).unwrap(); + fs::copy("/usr/bin/id", target.join("id")).unwrap(); + fs::set_permissions(target.join("id"), fs::Permissions::from_mode(0o755)).unwrap(); + fs::create_dir(dir.join("current-system")).unwrap(); + std::os::unix::fs::symlink(dir.join("store"), dir.join("current-system/sw")).unwrap(); + std::os::unix::fs::symlink("id", target.join("id-link")).unwrap(); + let alias = dir.join("current-system/sw/bin/id-link"); + let verified = verify_id_candidate(alias.to_str().unwrap()).unwrap(); + assert_eq!(verified, target.join("id")); + fs::remove_file(target.join("id-link")).unwrap(); + let out = std::process::Command::new(&verified) + .arg("-u") + .output() + .unwrap(); + assert!(out.status.success()); + assert_eq!(out.stdout, b"0\n"); + fs::set_permissions(&verified, fs::Permissions::from_mode(0o775)).unwrap(); + assert!( + verify_id_candidate(verified.to_str().unwrap()) + .unwrap_err() + .contains("writable") + ); } #[test] diff --git a/src/test_util/pty.rs b/src/test_util/pty.rs index 6762948..6cfbd2e 100644 --- a/src/test_util/pty.rs +++ b/src/test_util/pty.rs @@ -42,11 +42,15 @@ impl TestPty { } pub fn spawn(&mut self, command: &mut Command) { + self.spawn_with_stderr(command, Stdio::from(self.slave.try_clone().unwrap())); + } + + pub fn spawn_with_stderr(&mut self, command: &mut Command, stderr: Stdio) { self.child = Some( command .stdin(Stdio::from(self.slave.try_clone().unwrap())) .stdout(Stdio::from(self.slave.try_clone().unwrap())) - .stderr(Stdio::from(self.slave.try_clone().unwrap())) + .stderr(stderr) .spawn() .unwrap(), ); diff --git a/tests/exec_conformance/setup.rs b/tests/exec_conformance/setup.rs index 99ebf95..530fe0e 100644 --- a/tests/exec_conformance/setup.rs +++ b/tests/exec_conformance/setup.rs @@ -121,6 +121,31 @@ fn partial_noncanonical_input_does_not_delay_terminal_restoration() { assert!(!dir.join(".env.keys").exists()); } +#[test] +fn interrupted_canonical_input_is_discarded_before_the_next_reader() { + let dir = common::tmpdir("canonical-interrupt"); + let mut pty = pty::TestPty::new(); + let original = rustix::termios::tcgetattr(&pty.slave).unwrap().local_modes; + assert!(original.contains(rustix::termios::LocalModes::ICANON)); + pty.spawn(&mut setup_command(&dir, false)); + pty.expect("[y/N]"); + pty.send(b"y\n"); + pty.expect("Paste the keys file contents"); + pty.send(b"PRIVATE_SENTINEL"); + pty.signal(rustix::process::Signal::TERM); + assert!(!pty.wait().success()); + assert_eq!( + rustix::termios::tcgetattr(&pty.slave).unwrap().local_modes, + original + ); + // Complete the next canonical line; it must contain none of the interrupted secret. + pty.send(b"\n"); + let mut next = [0; 128]; + let count = pty.slave.read(&mut next).unwrap(); + assert_eq!(&next[..count], b"\n"); + assert!(!dir.join(".env.keys").exists()); +} + #[test] fn redirected_rotation_preserves_old_handles_and_read_only_files() { for mode in [0o400, 0o600] { From 949a0f4634ab723e0385bff9b3e95009a3ce234b Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Mon, 9 Nov 2026 08:04:12 -0600 Subject: [PATCH 40/47] fix: deduplicate setup keys and enable Nix features --- .github/actions/setup-nix/action.yml | 4 +- .github/actions/setup-nix/test.py | 47 +++++++++++++++++++++ CHANGELOG.md | 3 +- src/keys/provisioning/setup.rs | 61 ++++++++++++++++++++++++---- src/server.rs | 2 +- tests/exec_conformance/daemon.rs | 2 +- 6 files changed, 105 insertions(+), 14 deletions(-) create mode 100644 .github/actions/setup-nix/test.py diff --git a/.github/actions/setup-nix/action.yml b/.github/actions/setup-nix/action.yml index d8aefa3..291d4af 100644 --- a/.github/actions/setup-nix/action.yml +++ b/.github/actions/setup-nix/action.yml @@ -50,6 +50,6 @@ runs: run: | set -euo pipefail mkdir -p "$HOME/.config/nix" - if ! grep -q 'experimental-features' "$HOME/.config/nix/nix.conf" 2>/dev/null; then - echo 'experimental-features = nix-command flakes' >> "$HOME/.config/nix/nix.conf" + if ! grep -qxF 'extra-experimental-features = nix-command flakes' "$HOME/.config/nix/nix.conf" 2>/dev/null; then + printf '\nextra-experimental-features = nix-command flakes\n' >> "$HOME/.config/nix/nix.conf" fi diff --git a/.github/actions/setup-nix/test.py b/.github/actions/setup-nix/test.py new file mode 100644 index 0000000..39b24ef --- /dev/null +++ b/.github/actions/setup-nix/test.py @@ -0,0 +1,47 @@ +"""Check Nix feature configuration without installing Nix. + +Run: python3 .github/actions/setup-nix/test.py [path-to-bash] +""" + +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import textwrap + + +action = (Path(__file__).resolve().parent / "action.yml").read_text() +section = action.split(" - name: Enable nix-command and flakes\n", 1)[1] +body = textwrap.dedent(section.split(" run: |\n", 1)[1]) +bash = sys.argv[1] if len(sys.argv) > 1 else "/bin/bash" +cases = { + "missing": None, + "empty": "", + "nix-command-only": "experimental-features = nix-command\n", + "flakes-only": "experimental-features = flakes\n", + "commented": "# experimental-features = nix-command flakes\n", + "other-features": "experimental-features = ca-derivations\n", + "enabled": "experimental-features = nix-command flakes\n", + "no-newline": "experimental-features = nix-command", +} +for name, original in cases.items(): + with tempfile.TemporaryDirectory(prefix="postmaster-nix features-") as home: + config = Path(home) / ".config/nix/nix.conf" + if original is not None: + config.parent.mkdir(parents=True) + config.write_text(original) + env = {**os.environ, "HOME": home} + subprocess.run([bash, "-c", body], env=env, check=True) + first = config.read_text() + assert first.startswith(original or ""), f"{name}: existing config changed" + features = set() + for line in first.splitlines(): + key, separator, value = line.split("#", 1)[0].partition("=") + if separator and key.strip() in ("experimental-features", "extra-experimental-features"): + features.update(value.split()) + assert {"nix-command", "flakes"} <= features, f"{name}: missing features" + subprocess.run([bash, "-c", body], env=env, check=True) + assert config.read_text() == first, f"{name}: repeated setup changes config" + +print(f"Nix feature setup: {len(cases)} cases pass") diff --git a/CHANGELOG.md b/CHANGELOG.md index 67782f0..b72b0fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -113,7 +113,7 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). launching with keys that may be stale after rotation. - Provides interactive and unattended `postmaster setup` workflows. Setup creates a `0700` keys directory, verifies owner-only key files, - and optionally seeds macOS Keychain items. + and optionally seeds each required macOS Keychain account once. - Provides `setup --recheck` for key-source accessibility checks and `--keys-dir` for an explicit key directory. `--force` re-prompts for key files or re-seeds Keychain items; force with unattended mode fails @@ -138,6 +138,7 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). the pinned installer digest before execution. Official GitHub actions and helper tools use pinned versions. Nix installer temporary files work with GNU and macOS `mktemp`. + Nix setup extends existing feature settings with `nix-command` and `flakes`. Cargo tool installation honors `CARGO_INSTALL_ROOT` and `CARGO_HOME` and verifies the selected executables before adding their directory to `PATH`. - Runs formatting, Clippy, and Markdown lint from pre-commit hooks. diff --git a/src/keys/provisioning/setup.rs b/src/keys/provisioning/setup.rs index 957a6f1..33242bf 100644 --- a/src/keys/provisioning/setup.rs +++ b/src/keys/provisioning/setup.rs @@ -1,14 +1,29 @@ //! `postmaster setup` command path. +use std::collections::HashSet; use std::path::{Path, PathBuf}; #[cfg(target_os = "macos")] use super::ensure_keychain_items; use super::{default_keys_dir, ensure_keys_dir, ensure_keys_file, verify_key_sources}; use crate::adapter::KeyNaming; -use crate::exec_config::KeySourceSpec; +use crate::exec_config::{ExecConfig, KeySourceSpec}; use crate::server::log; +/// Resolve distinct setup key variables in first-seen input order. +fn wanted_keys(cfg: &ExecConfig) -> Result, String> { + let mut wanted = Vec::new(); + for f in &cfg.env_files { + wanted.push(KeyNaming::Env.key_var_for(f)?); + } + for f in &cfg.bundle_files { + wanted.push(KeyNaming::Bundle.key_var_for(f)?); + } + let mut seen = HashSet::new(); + wanted.retain(|key| seen.insert(key.clone())); + Ok(wanted) +} + /// `postmaster setup`: verify platform prerequisites, create keys /// directory with correct permissions, optionally seed keychain items, /// and validate the environment. Idempotent — skips steps that are @@ -35,14 +50,7 @@ pub fn setup( let cfg = crate::launcher::parse_exec_config(config_path)?; cfg.validate_shape()?; - // Build the wanted key variable list from both env and bundle files - let mut wanted: Vec = Vec::new(); - for f in &cfg.env_files { - wanted.push(KeyNaming::Env.key_var_for(f)?); - } - for f in &cfg.bundle_files { - wanted.push(KeyNaming::Bundle.key_var_for(f)?); - } + let wanted = wanted_keys(&cfg)?; if recheck { // --recheck: verification only, no creation or modification @@ -78,3 +86,38 @@ pub fn setup( )); Ok(()) } + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn setup_keys_are_unique_and_keep_first_seen_order() { + let mut cfg: ExecConfig = serde_json::from_value(serde_json::json!({ + "mode": "env", "keys": [{"keychain": "postmaster"}], + "bundle_files": ["/x/first.json", "/x/second.json"] + })) + .unwrap(); + assert_eq!(wanted_keys(&cfg).unwrap(), ["POSTMASTER_KEY"]); + cfg.env_files = [ + "/x/.env.production", + "/x/.env", + "/y/.env.production", + "/x/.env.development", + ] + .map(PathBuf::from) + .into(); + assert_eq!( + wanted_keys(&cfg).unwrap(), + [ + "DOTENV_PRIVATE_KEY_PRODUCTION", + "DOTENV_PRIVATE_KEY", + "DOTENV_PRIVATE_KEY_DEVELOPMENT", + "POSTMASTER_KEY" + ] + ); + cfg.env_files.push("/x/.env.bad-name".into()); + assert!(wanted_keys(&cfg).is_err()); + } +} diff --git a/src/server.rs b/src/server.rs index 0560836..8e57ef0 100644 --- a/src/server.rs +++ b/src/server.rs @@ -782,7 +782,7 @@ mod tests { let dir = crate::test_util::temp_dir::TestDir::new("id-alias"); let target = dir.join("store/bin"); fs::create_dir_all(&target).unwrap(); - fs::copy("/usr/bin/id", target.join("id")).unwrap(); + fs::copy(verified_id_binary().unwrap(), target.join("id")).unwrap(); fs::set_permissions(target.join("id"), fs::Permissions::from_mode(0o755)).unwrap(); fs::create_dir(dir.join("current-system")).unwrap(); std::os::unix::fs::symlink(dir.join("store"), dir.join("current-system/sw")).unwrap(); diff --git a/tests/exec_conformance/daemon.rs b/tests/exec_conformance/daemon.rs index 1935f1e..e7e46e8 100644 --- a/tests/exec_conformance/daemon.rs +++ b/tests/exec_conformance/daemon.rs @@ -62,7 +62,7 @@ fn daemon_serves_a_real_fetch_roundtrip() { #[test] fn daemon_serves_configured_peer_under_any_umask() { - let out = Command::new("/usr/bin/id").arg("-un").output().unwrap(); + let out = Command::new("id").arg("-un").output().unwrap(); assert!(out.status.success()); let user = String::from_utf8(out.stdout).unwrap(); for mask in ["000", "022", "077"] { From f55ad3506af00b3740d298faf832b04117f22c4b Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Mon, 9 Nov 2026 21:04:42 -0600 Subject: [PATCH 41/47] docs: align runtime guidance and documentation voice --- .github/CONTRIBUTING.md | 51 ++++--- .github/SECURITY.md | 19 +-- .github/workflows/ci.yml | 3 +- .markdownlint-cli2.jsonc | 4 +- Cargo.toml | 6 +- Justfile | 8 +- README.md | 43 +++--- docs/schema/exec.schema.json | 2 +- docs/src/architecture/materialization-abi.md | 66 ++++---- docs/src/architecture/postmaster.md | 49 +++--- docs/src/architecture/threat-model.md | 151 ++++++++----------- docs/src/getting-started/injection-modes.md | 38 ++--- docs/src/getting-started/key-provisioning.md | 22 ++- docs/src/getting-started/quick-start.md | 18 +-- docs/src/introduction.md | 84 +++++------ docs/src/reference/cli.md | 27 ++-- docs/src/reference/launcher-contract.md | 39 +++-- docs/src/unsafe-code/index.md | 4 +- docs/src/unsafe-code/macos-libc-boundary.md | 8 +- docs/src/unsafe-code/monitor.md | 25 ++- docs/src/unsafe-code/signal-deferral.md | 25 ++- docs/src/unsafe-code/systemd-fd-ownership.md | 15 +- docs/src/unsafe-code/test-env-mutation.md | 30 ++-- flake.nix | 11 +- package.nix | 13 +- src/aad.rs | 2 +- src/adapter/bundle.rs | 30 ++-- src/adapter/mod.rs | 33 ++-- src/cli/help.rs | 36 ++--- src/cli/mod.rs | 30 ++-- src/exec_config.rs | 24 ++- src/keys/env.rs | 13 +- src/keys/keychain.rs | 10 +- src/keys/load.rs | 18 +-- src/keys/mod.rs | 102 ++++++------- src/keys/provisioning/cleanup.rs | 31 ++-- src/keys/provisioning/mod.rs | 126 +++++++--------- src/keys/source.rs | 45 +++--- src/keys/verify.rs | 20 +-- src/launcher.rs | 88 +++++------ src/lib.rs | 27 ++-- src/main.rs | 5 +- src/monitor.rs | 8 +- src/monitor/tests.rs | 4 +- src/ramdisk.rs | 11 +- src/secret_files.rs | 33 ++-- src/server.rs | 85 +++++------ src/test_util.rs | 6 +- tests/common/mod.rs | 3 +- tests/exec_check.rs | 2 +- tests/exec_conformance/bundle.rs | 22 +-- tests/exec_conformance/daemon.rs | 13 +- tests/exec_conformance/files_mode.rs | 22 ++- tests/exec_conformance/keys_verify.rs | 18 +-- tests/exec_conformance/main.rs | 12 +- 55 files changed, 724 insertions(+), 916 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 9071cb4..e13e85c 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,9 +1,7 @@ # Contributing to postmaster -postmaster is a standalone, format-neutral local secret materialization -engine. It decrypts encrypted secret inputs at process launch time and -injects them into a child process via environment variables, files, or -systemd credentials — then `execvp`s the target binary directly. +Postmaster decrypts local secret inputs, projects values into the application, +and replaces the launcher with the target binary through `execvp`. External contributions are welcome. @@ -12,24 +10,24 @@ project's [MIT license](../LICENSE) (inbound = outbound). ## Ground rules -- **The Justfile is the single source of truth.** The local git hooks - (lefthook) and CI both call the same `just` recipes, so what passes - locally passes in CI. Don't add a check to CI that isn't a `just` recipe. -- **The bar is enforced, not aspirational.** Clippy runs with `-D - warnings`, formatting is checked, and the dependency license/source - policy is gated. CI will not go green on a warning. -- **Real tests, not coverage theater.** New behavior needs a test that - would fail without the change. Match the existing unit/integration - style in the crate. +- **Keep checks in the Justfile.** Git hooks and workflow definitions call + the same recipes. Runner setup still needs separate verification, and a + local pass doesn't establish that hosted CI ran. Don't add a CI check + without a matching recipe. +- **Treat warnings as failures.** Clippy runs with `-D warnings`. + Formatting and dependency license, source, and advisory checks must pass. +- **Test the behavior.** Add a regression that fails without the change. + Match the crate's existing unit and integration tests. - **This is a security tool.** Secret material, private keys, and decrypted values are core to its purpose. Changes to the decrypt path, key handling, or injection modes get extra scrutiny. ## Getting set up -You need a recent stable Rust toolchain (`rustup` + the -`rust-toolchain.toml` will help), [`just`](https://just.systems), and +You need Rust 1.99.1 or newer, [`just`](https://just.systems), and [`lefthook`](https://lefthook.dev) for the git hooks. +`rust-toolchain.toml` selects the toolchain and required components through +`rustup`. ```sh git clone git@github.com:beardedeagle/postmaster.git @@ -40,31 +38,36 @@ just --list # see every available recipe ## The development loop -Run the full native gate before you push — it is exactly what CI runs: +Run the Rust gate before pushing. It includes native and release checks, +Linux-target Clippy, a locked build, and tests: ```sh -just ci-rust # fmt-check, clippy, build, test +just ci-rust # fmt-check, native/release/Linux clippy, build, test just ci # ci-rust + nix flake check just docs # mdBook build ``` +The GitHub workflow jobs currently use `if: false`, so hosted checks are +skipped. Run the recipes locally and report that distinction in the PR. + For dependency policy checks: ```sh -just deny # cargo deny check (advisories, bans, sources) +just deny # advisories, bans, licenses, sources +just audit # advisory database check, warnings fail ``` ## Submitting a change 1. Branch off `main` (`git switch -c fix/short-description`). -2. Make your change + add tests where appropriate. +2. Make the change and add tests where needed. 3. Run the full `just ci`. 4. Open a PR. Use the PR template. -5. Be patient — reviews will focus on correctness, security posture, and - consistency with the existing style. +5. Include verification evidence and unresolved limits. Reviews focus on + correctness, security, and consistency with the existing code. ## Reporting bugs and requesting features -Please use the GitHub issue templates. For security issues, see -`SECURITY.md` and report privately (GitHub Security Advisories or the -contact in that file). +Use the GitHub issue templates. For security issues, see +[Security policy](SECURITY.md) and report privately through advisories or the +contact in that file. diff --git a/.github/SECURITY.md b/.github/SECURITY.md index eb64a45..ed586fd 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -1,23 +1,20 @@ -# Security Policy +# Security policy ## Supported versions -postmaster is pre-1.0 and ships from a single line of development. -Security fixes land on the latest release and on `main`; there are no -separately maintained release branches. Always run the latest release. +Postmaster is unreleased. `main` is the supported development line; +there are no released versions or separately maintained release branches. | Version | Supported | | ---------------- | --------- | -| latest release | ✅ | -| `main` | ✅ | -| older tags | ❌ | +| `main` | Yes | ## Reporting a vulnerability **This project handles secrets.** Private keys, decrypted environment values, and systemd/nix-darwin credentials are core to its purpose. -Please report security issues **privately** — do **not** open a public +Report security issues **privately**. Do **not** open a public issue, pull request, or discussion for anything security-sensitive. Preferred channels (either is fine): @@ -29,12 +26,12 @@ Preferred channels (either is fine): 2. **Email.** Write to . -Please include as much of the following as you can: +Include the following where available: - A description of the vulnerability and its potential impact. - Steps to reproduce (or a minimal proof-of-concept if safe to share). - Affected versions / commits. - Any suggested mitigation or fix. -We will acknowledge receipt quickly and work with you on a fix and -disclosure timeline. +We'll acknowledge the report and work with you on a fix and disclosure +timeline. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index edba7b5..2295ed5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,5 +42,4 @@ jobs: - name: Quality gate (fmt, clippy, build, test) run: just ci-rust -# The dependency-policy (cargo deny) job lives in security.yml — do not -# duplicate it here (sweep 2026-08-07 R9). +# The dependency-policy (cargo deny) job lives in security.yml. diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc index 4c3ffad..2867622 100644 --- a/.markdownlint-cli2.jsonc +++ b/.markdownlint-cli2.jsonc @@ -1,7 +1,5 @@ { - // markdownlint-cli2 configuration (sweep 2026-08-07 R6): one file, one - // source of truth — the old .markdownlint.jsonc (rules) and - // .markdownlintignore (never read by cli2) were consolidated here. + // Keep Markdown rules and ignored paths together in the CLI configuration. "config": { // Prose is wrapped at 80; tables and code blocks legitimately exceed any fixed // width (a multi-column row or a CLI line can't be 80 chars) and render fine. diff --git a/Cargo.toml b/Cargo.toml index 31e796d..e23904c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,7 +42,7 @@ impl_trait_redundant_captures = "warn" # join at teardown) that may legitimately fail, and the adjacent comments # explain why that's acceptable. Security-relevant hardening calls # (mlockall-style, non-dumpable, core limits, ptrace-deny) LOG their -# failures instead (audit 2026-08-02 A10). Converting either to +# failures instead. Converting either to # unwrap/expect/error handling would CHANGE behavior in a fail-closed # daemon, so the lint stays off. let_underscore_drop = "allow" @@ -112,8 +112,8 @@ zeroize = "1" sha2 = "0.11" getrandom = "0.4" # Syscall layer: rustix's default linux_raw backend issues raw syscalls from -# Rust — no libc FFI in these paths, and the unsafe surface collapses to the -# single fd-ownership assertion at the systemd socket-activation boundary. +# Rust. Signal-mask operations and systemd fd adoption require narrow unsafe +# blocks; fork(2) uses libc at the launcher boundary. rustix = { version = "1", features = ["net", "process", "mm", "fs", "termios", "event"] } [target.'cfg(target_os = "linux")'.dependencies] diff --git a/Justfile b/Justfile index c85c85b..54d98ae 100644 --- a/Justfile +++ b/Justfile @@ -18,12 +18,11 @@ fmt-check: clippy: cargo +{{stable_toolchain}} clippy --all-targets -- -D warnings -# Release-profile clippy (house battery gate; sweep 2026-08-07 R2) +# Check release-only code paths with Clippy. clippy-release: cargo +{{stable_toolchain}} clippy --all-targets --release -- -D warnings -# Linux-target clippy (house battery gate; sweep 2026-08-07 R2). The -# target is pinned in rust-toolchain.toml, so rustup installs it. +# Check Linux-only code paths; rust-toolchain.toml declares the target. clippy-linux: cargo +{{stable_toolchain}} clippy --all-targets --target x86_64-unknown-linux-gnu -- -D warnings @@ -63,8 +62,7 @@ docs-serve: trap 'rm -f docs/src/changelog.md' EXIT (cd docs && mdbook serve --open) -# Markdown prose lint (sweep 2026-08-07 R6; rules + ignores in -# .markdownlint-cli2.jsonc). markdownlint-cli2 version pinned. +# Markdown rules and ignores live in .markdownlint-cli2.jsonc; pin the linter version. lint-md: npx --yes markdownlint-cli2@0.23.2 "**/*.md" diff --git a/README.md b/README.md index 2895bb9..157f7dd 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,20 @@ # postmaster -**postmaster** is a standalone, format-neutral local secret -materialization engine. It decrypts encrypted secret inputs at process -launch time and injects them into a child process via environment -variables, files, or systemd credentials — then `execvp`s your binary -directly. No Node, no shell, no separate CLI process in the runtime path. +Postmaster decrypts local secret inputs at process launch and delivers values +through environment variables, files, or systemd credentials. It then replaces +the launcher with your binary through `execvp`. The first input adapter is wire-compatible with [dotenvx](https://github.com/dotenvx/dotenvx)-encrypted `.env` files (same ECIES/secp256k1 + HKDF-SHA256 + AES-256-GCM crypto path), so existing -`.env` files encrypted with the dotenvx CLI decrypt byte-exact through -postmaster's native Rust implementation. dotenvx is one adapter, not the -ceiling — the architecture supports file-based (`.env`), HashiCorp Vault, -AWS SSM, and other secret providers (1Password, etc.) as source/custody -backends. +`.env` files encrypted with the dotenvx CLI decrypt through Postmaster's +native Rust implementation. Postmaster also reads encrypted +`postmaster_bundle` JSON files. External systems such as Vault, AWS SSM, +and 1Password can deliver private keys to its local key sources before launch. -Postmaster works with Nix, AWS CDK, Ansible, SaltStack, Puppet, -Terraform, and OpenTofu as deployment automation targets, all sharing -the same `exec.json` contract. +Deployment tools such as Nix, AWS CDK, Ansible, SaltStack, Puppet, Terraform, +and OpenTofu can generate the same `exec.json` contract. Postmaster doesn't +fetch secrets from those tools or remote stores. Encrypted values can be public: each value is ECIES/secp256k1-encrypted, and the embedded public key permits encryption but not decryption. @@ -73,9 +70,8 @@ $ postmaster --help ## Injection modes -**`mode = "env"`.** Decrypted values are exported into the -process environment and the wrapper `exec`s your binary. Correct for -12-factor apps. +**`mode = "env"`.** Postmaster exports resolved values into the application +environment and replaces the launcher with your binary. **`mode = "files"`.** Values are written one-file-per-key onto a namespace-private tmpfs (`TemporaryFileSystem=/run/postmaster`; on macOS, @@ -85,16 +81,16 @@ variables are exported by default, following the Docker-secrets convention. absent from environ, `ps e`, crash-dump environment sections, and ambient child inheritance. -**`mode = "credentials"`.** Real systemd credentials, served on demand by -the postmaster daemon. The consumer's unit gets +**`mode = "credentials"`.** The launcher exports pointers to credentials +that systemd has already supplied, or fetches them from configured local +Postmaster sockets. With daemon-backed systemd delivery, the consumer gets `LoadCredential=:/run/postmaster-credd//.sock` per key and the app reads `$CREDENTIALS_DIRECTORY/` from unit-private, unswappable -ramfs. Strongest hygiene of the three. +ramfs. The deployment controls credential storage and access. ## Key sources -Postmaster reads private keys from local terminal sources only — it never -fetches from remote systems: +Postmaster reads private keys from four local sources: - **systemd credentials** (`LoadCredential=`) — PID 1 places key material in `$CREDENTIALS_DIRECTORY` before postmaster starts. Includes @@ -112,8 +108,9 @@ fetches from remote systems: Postmaster is the local secret materialization stage in a 5-stage pipeline: custody (Vault/SSM/1Password/TPM2) → rendering (Nix/Terraform/ CDK/Ansible/Salt/Puppet) → delivery (credentials/files/keychain/env) → -materialization (postmaster) → launch (execvp). Each stage is owned by a -different system; postmaster owns exactly materialization. The +materialization (postmaster) → launch (execvp). Each stage has a separate +responsibility. Postmaster handles local materialization and the handoff to +the target process. The stage-by-stage breakdown lives in [The secret pipeline](docs/src/architecture/postmaster.md#the-secret-pipeline). diff --git a/docs/schema/exec.schema.json b/docs/schema/exec.schema.json index ebb116d..573d32b 100644 --- a/docs/schema/exec.schema.json +++ b/docs/schema/exec.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/beardedeagle/postmaster/docs/schema/exec.schema.json", "title": "postmaster exec.json", - "description": "Public launcher configuration for the current dotenvx-shaped postmaster materialization ABI instance.", + "description": "Public Postmaster launch configuration: local inputs, key sources, and projection settings.", "type": "object", "additionalProperties": false, "required": ["mode"], diff --git a/docs/src/architecture/materialization-abi.md b/docs/src/architecture/materialization-abi.md index ef8256f..3042174 100644 --- a/docs/src/architecture/materialization-abi.md +++ b/docs/src/architecture/materialization-abi.md @@ -4,20 +4,18 @@ contract between public deployment artifacts, local private key material, and the process that receives plaintext at runtime. -## Audience Quickstart +## Audience quickstart -**What this is:** the contract that every integration (Nix, Terraform, -CDK, Ansible, etc.) must follow when wiring postmaster. If you're writing -a binding or evaluating whether a generated config is correct, this is -your page. +Deployment integrations generate local inputs for Postmaster. This contract +defines those inputs, key sources, resolution rules, and output projections. ### Who this is for | Reader | What to take | | -------- | ------------ | | Integration author | The entire page — this is your contract | -| Security engineer | "Non-goals" and "Resolution" — what postmaster will never do | -| New user | "Current ABI instance" and the exec.json example — the 60-second tour | +| Security engineer | "Non-goals" and "Resolution" | +| New user | "Current ABI instance" and the exec.json example | | Platform / SRE | "Key sources" and "Validation" — what the host needs | ### Quick glossary @@ -25,7 +23,7 @@ your page. | Term | Plain meaning | | ------ | --------------- | | **ABI** | Application Binary Interface — the contract between config files, key material, and the launcher | -| **exec.json** | A JSON file that tells postmaster what to decrypt, how to inject, and what to launch | +| **exec.json** | A JSON file that selects inputs, key sources, and projection mode. The launch command is supplied separately after `--`. | | **Projection** | Where decrypted secrets go — env vars, files, or systemd credentials | | **Adapter** | An input format (.env, postmaster_bundle) — postmaster supports multiple, not just one | @@ -38,8 +36,8 @@ The ABI is deliberately local: - required validation and decryption checks finish before `exec` This page describes the ABI and how `exec.json` fits inside it. It is a -contract for bindings and documentation recipes, not an invitation to put -provider clients into `postmaster`. +contract for bindings and documentation recipes. Remote provider clients +belong in the delivery tooling, outside `postmaster`. ## Non-goals @@ -123,13 +121,14 @@ filename selects the private key variable: - environment names must be non-empty `[A-Za-z0-9_]` (letters fold to upper case); anything else is rejected -The `.env` adapter is the first adapter, not the ceiling of the system. +The bundle adapter below provides another input format under the same +projection contract. ## Neutral bundle adapter -The `postmaster_bundle` adapter is a second input format, not a replacement -for `.env`. Its job is to let non-`.env` ecosystems produce a public -encrypted artifact without pretending their native model is an `.env` file. +The `postmaster_bundle` adapter reads structured JSON artifacts alongside +dotenv inputs. Producers can represent binary and UTF-8 entries without +encoding their native data model as a dotenv file. The on-disk format is a JSON container. JSON keeps generated artifacts easy for Terraform, OpenTofu, CDK, Ansible, Salt, Puppet, and Nix to render and @@ -173,10 +172,9 @@ uses the uncompressed ephemeral and shared points, matching `ecies` defaults. The entry name's exact UTF-8 bytes are the AAD; plaintext is returned only after AES-256-GCM authentication succeeds. -The remaining metadata (profile, recipient ids, encodings) is not yet -cryptographically bound. Binding it requires specifying canonical serialized -bytes for the authenticated metadata first — generated artifacts need -deterministic bytes for reproducible builds and stable test vectors. +The remaining metadata, including profile, recipient IDs, and encodings, is +not cryptographically bound. A format that authenticates those fields would +need canonical serialized bytes for reproducible builds and stable vectors. The design constraints are: @@ -286,8 +284,8 @@ The deployment must supply RAM-backed storage. The launcher does not establish RAM backing when `verify_ramdisk` is absent. The launcher refuses to follow symlinks when writing secret files. On macOS, -when `verify_ramdisk` is set, it verifies the configured mount before writing -plaintext. +when `verify_ramdisk` is set, it verifies the configured mount and the opened +directory's device and ownership before writing plaintext. `passthrough` may additionally export selected keys as real environment variables. Passthrough values containing NUL bytes are rejected. @@ -297,9 +295,10 @@ variables. Passthrough values containing NUL bytes are rejected. On systemd, PID 1 has already materialized credentials and the launcher only exports `_FILE` pointers into `$CREDENTIALS_DIRECTORY`. -On launchd, the launcher can fetch configured keys from local postmaster -sockets, write them into the verified RAM disk directory, and export -credential-style pointers. +When `sockets` is configured, the launcher fetches values from local +Postmaster sockets, writes them beneath `secrets_dir`, and exports +credential-style pointers. This path is normally used with launchd. RAM +backing is verified only when `verify_ramdisk` is set on macOS. Every `credential_keys` entry must be a valid identifier before any fetch or write occurs. @@ -330,19 +329,20 @@ the key file is missing, the keychain item is absent, or the credential source is not provisioned. The launcher's fail-closed behavior is the runtime guarantee; `--check` cannot substitute for it. -`postmaster setup --config --recheck` provides runtime -environment verification — it probes the filesystem and keychain to -confirm that key material is actually accessible at the configured paths, -without decrypting any secrets. It complements `--check`: run `--check` -in CI for config correctness, run `setup --recheck` on the host for -environment readiness. +`postmaster setup --config --recheck` checks local provisioning +without decrypting secrets. File sources receive descriptor-based ownership, +permission, and macOS ACL checks. Credential sources receive path-presence and +regular-file checks. Keychain checks look for the required items; environment +checks look for required variables. These checks do not prove that the keys +can decrypt the configured inputs. Run `--check` in CI for config shape and +`setup --recheck` on the host for provisioning checks. The full `postmaster setup` command goes beyond verification: it creates the keys directory with 0700 permissions, verifies or creates -keys files with 0600, optionally seeds keychain items (macOS, interactive), -and validates platform prerequisites. It is idempotent — each step checks -whether the target state is already present and correct, and skips if it -is. Flags: `--recheck` (verification only), `--unattended` (non-interactive, +key files with owner-only permissions, and optionally seeds macOS Keychain +items interactively. It derives a unique required-account list in first-seen +input order. Steps already satisfied are skipped. +Flags: `--recheck` (verification only), `--unattended` (non-interactive, fail closed), `--force` (re-create/re-seed), `--keys-dir ` (override default path). diff --git a/docs/src/architecture/postmaster.md b/docs/src/architecture/postmaster.md index 2c9357d..05bb481 100644 --- a/docs/src/architecture/postmaster.md +++ b/docs/src/architecture/postmaster.md @@ -4,14 +4,13 @@ Postmaster is a standalone Rust binary that decrypts secret inputs at process launch, injects them into the child process, and replaces its own process image with the target binary via `execvp`. -It is not a library. It is not a plugin host. It is not a daemon -framework. It is a single binary with a fixed, local, offline -contract. +It ships as a standalone binary with a local, offline contract. Decryption +and projection are implemented in the repository's Rust library crate. -## Audience Quickstart +## Audience quickstart -**What this is:** the architecture of postmaster — what it does, -what it owns, and where it fits in the secret delivery pipeline. +This page describes Postmaster's runtime responsibilities and the deployment +stages around it. ### Who this is for @@ -21,7 +20,7 @@ what it owns, and where it fits in the secret delivery pipeline. | Platform / SRE | "Implementation" and "Dependency policy" — what you're deploying | | Security engineer | The entire page — this defines the security boundary | | Integration author | "What postmaster does NOT own" and the [Launcher contract](../reference/launcher-contract.md) | -| Product / project manager | "What postmaster owns" and the pipeline diagram — the 30-second summary | +| Product / project manager | "What postmaster owns" and the pipeline diagram | ### Quick glossary @@ -66,7 +65,7 @@ plaintext in its environment or files": seeds keychain items (macOS), and validates the environment — idempotently. -## What postmaster does NOT own +## What Postmaster does not own Deployment tooling owns authoring, custody, and service-manager policy: @@ -92,8 +91,8 @@ Deployment tooling owns authoring, custody, and service-manager policy: Postmaster runs a sibling monitor alongside the exec'd service: it forwards stop signals, escalates to SIGKILL after a bounded grace, and removes plaintext secret files on every - death path (see "The secret pipeline" below) — supervision of - plaintext, not of the service's health. + death path while the monitor survives. Integration cleanup and storage + teardown provide backstops if it doesn't. - **Child behavior.** What the child process does with its secrets — reading from environment variables, files, or credentials — is the @@ -103,8 +102,9 @@ Deployment tooling owns authoring, custody, and service-manager policy: ## The secret pipeline -The full secret lifecycle is a pipeline of distinct stages, each -owned by a different system. Postmaster owns exactly one stage. +The secret lifecycle has separate custody, rendering, delivery, +materialization, and launch responsibilities. Postmaster handles +materialization and the process handoff. ```mermaid flowchart LR @@ -191,8 +191,8 @@ remote systems. ### Stage 4: Materialization (postmaster) -Postmaster decrypts encrypted inputs and injects them into the child -context. This is the only stage postmaster owns. +Postmaster decrypts local inputs and projects the resulting values into the +application's environment or files. - Decrypts `.env` files via the `ecies` crate (native Rust, offline) - Decrypts `postmaster_bundle` entries with name-bound AES-GCM AAD @@ -204,16 +204,16 @@ context. This is the only stage postmaster owns. ### Stage 5: Launch (execvp) Postmaster forks a **sibling monitor** and then calls `execvp` in the -parent. The parent's process image is replaced. The child binary IS -`MainPID`. Postmaster is gone from the service's process. +parent. The service binary remains `MainPID`; the launcher's process image +is gone. The fork-child becomes the monitor. It scrubs its projected environment pairs, keeps the termination signals blocked for life, and supervises its parent — forwards stop signals with a 250 ms grace before SIGKILL escalation, and removes the plaintext secret files on every service-death path (natural exit, `kill -9`, crash), then exits. -One tiny extra process per service for the service's lifetime; liveness -is pidfd+`poll` on Linux and kqueue `NOTE_EXIT` on macOS. +One monitor process runs for the service's lifetime. It watches liveness +with pidfd and `poll` on Linux, or kqueue `NOTE_EXIT` on macOS. The monitor retains the original process environment, which can contain private keys supplied through environment variables. Use a non-environment @@ -250,7 +250,7 @@ is `cfg`-gated (`SO_PEERCRED`→`getpeereid`, `prctl`/`mlockall`→core-limit + `PT_DENY_ATTACH`). The binary has five entry points: the default daemon (`--bind`/ -socket-activated `serve`), `fetch` (the darwin fetch client), `exec` +socket-activated `serve`), `fetch` (the local socket client), `exec` (decrypt + inject + `execvp`), `setup` (idempotent environment verification and key provisioning), and `cleanup` (plaintext file removal for `ExecStopPost`). Its config schema, key-source precedence, @@ -276,18 +276,17 @@ Postmaster has 11 direct dependencies (9 portable, 2 platform-gated): the only libc FFI on Linux is `fork(2)` — see the unsafe registry) - `libc` — macOS (getpeereid, `PT_DENY_ATTACH`, the monitor's kqueue/signal ops) plus Linux `fork(2)` only (rustix has no fork - wrapper — review-gated doctrine exception) + wrapper) - `security-framework` — macOS only (Security.framework keychain reads) - `zeroize` — secret memory wiping Bundle envelopes use Postmaster's AAD decoder with the released `ecies` curve/HKDF helpers and RustCrypto AES-GCM. This preserves existing ciphertext -compatibility without a git patch or an upstream AAD API dependency. +compatibility without an upstream AAD API dependency. -No CLI parsing library (clap, etc.). No async runtime. No OpenSSL. -No network client. No plugin system. The dependency set is -intentionally minimal: smaller binary, smaller attack surface, -faster startup, fewer supply-chain risks. +The CLI parser uses the standard library. There is no async runtime, OpenSSL +dependency, remote secret-store client, or plugin system. Each dependency +must justify its role in the runtime path. New dependencies are rejected unless they are strictly necessary for the core decrypt-inject-execvp path and cannot be implemented in diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index fac1a8b..392d426 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -1,9 +1,9 @@ # Threat model -## Audience Quickstart +## Audience quickstart -**What this is:** what postmaster protects, what it cannot prevent, -and why it's built this way. This is the security reference. +This reference defines Postmaster's trust boundary, deployment requirements, +and remaining exposure. ### Who this is for @@ -12,14 +12,14 @@ and why it's built this way. This is the security reference. | Security engineer | The entire page — every claim is about the security boundary | | Platform / SRE | "Swap and core dumps" and "Hardening inheritance" — what to configure | | Integration author | "Why a native launcher" — understand the design constraints | -| New user | "Secrets at rest" and "Fail-closed" — the 30-second security summary | -| Product / project manager | The residuals table — what postmaster does NOT protect against | +| New user | "Secrets at rest" and "Fail-closed" | +| Product / project manager | The residuals table | ### Quick glossary | Term | Plain meaning | | ------ | --------------- | -| **execvp** | Replaces the current process — no parent holds secrets after launch | +| **execvp** | Replaces the launcher with the target binary while keeping its PID. The sibling monitor is a separate process. | | **Fail-closed** | A failed required check prevents launch; dotenv decryption is strict by default | | **Zeroize** | Overwrite secret memory with zeros before it's freed | | **mlockall** | Pin memory in RAM so the kernel can't swap it to disk | @@ -35,18 +35,18 @@ and why it's built this way. This is the security reference. | Plaintext on persistent disk | Avoided when the deployment supplies RAM-backed secret storage | | Plaintext in swap | Mitigated — mlockall + MemorySwapMax=0 | | Core dumps | Mitigated — PR_SET_DUMPABLE=0, RLIMIT_CORE=0 | -| Shell injection | Prevented — no shell anywhere in the path | +| Shell injection through secret values | Values are passed without shell evaluation | | Symlink attacks on key files | Prevented — O_NOFOLLOW + fstat | | Same-UID env var exposure (env mode) | Residual — use files or credentials mode | -| Root on the host | Residual — root is always game over | +| Root on the host | Outside the trust boundary; privileged processes can inspect memory | | VM/hypervisor inspection | Residual — outside the trust boundary | -| CPU cache/register residue | Non-goal — no mitigation available | +| CPU cache/register residue | Outside Postmaster's memory-wiping guarantees | ## Why a native launcher, not a shell wrapper -Postmaster is a native Rust binary, not a shell wrapper around an -external CLI. This decision is driven by three security properties that -a shell-based approach cannot provide. +Postmaster decrypts in Rust and replaces the launcher with the service. +The relevant properties are process identity, value handling, and local +decryption. ### Process identity: execvp, not spawn @@ -55,12 +55,12 @@ call that replaces the current process image with the target binary. The process ID (PID) does not change. The service binary is `MainPID` from its first instruction. -A shell wrapper or Node.js parent process would `spawn` a child -instead. The parent stays alive as `MainPID`, which breaks: +A wrapper that spawns the service and remains alive keeps another process +in the service unit. That affects: - **systemd readiness notifications** (`Type=notify`, `sd_notify`): - systemd expects `MainPID` to send `READY=1`. A parent process that - spawns the real service means the wrong process is notifying. + notifications must come from the process the unit is configured to accept. + Keeping the wrapper as `MainPID` can leave the service outside that rule. - **Cgroup memory accounting**: the parent's memory (including private key material) is counted against the service unit's cgroup. - **Secret lifetime**: the parent process holds private keys and @@ -70,16 +70,13 @@ instead. The parent stays alive as `MainPID`, which breaks: ### No shell interpolation -A shell-based launcher would use `eval` or source-based injection to -set environment variables. That leaves `$(…)` and backticks live -inside double quotes. Combined with a public key embedded in the -repository (which lets any repo writer add or replace encrypted -values), this would be remote code execution at service start for -anyone who can commit to the repo. +A launcher that evaluates secret values through a shell can execute `$(…)` +or backticks inside those values. Anyone with the public key can encrypt a +replacement value, so artifact write access combined with shell evaluation +can become command execution at service start. -Postmaster never evaluates secret values as shell code. Decrypted values move directly -into the child's environment array or a file write. No shell sits -between decryption and injection to reinterpret the values. +Postmaster doesn't evaluate secret values as shell code. Decrypted values +move directly into the application's environment array or a file write. ### Private-key environment variables @@ -230,8 +227,8 @@ no external binary is invoked for it. The external binaries postmaster does invoke in secret-adjacent paths (`/usr/bin/id`, `/sbin/mount`, `/usr/bin/hdiutil`) are verified before use: -- **macOS:** `codesign -v` verifies a valid Apple code signature - (defense-in-depth; the binaries are also SIP-protected). +- **macOS:** `codesign -v` checks the designated system binary's code + signature. The fixed system paths are also SIP-protected. - **Linux:** verified as regular files owned by root (uid 0) with no group or other write permissions. `id` lookup resolves system aliases, including the NixOS system profile, verifies the target and its directory ancestry, @@ -295,10 +292,10 @@ node's lifetime. ### Root on the host -A process running as root can read any other process's memory via -`/proc/PID/mem` or `ptrace`. This is the Unix trust boundary — root is -always game over. Postmaster's `PR_SET_DUMPABLE=0` and `PT_DENY_ATTACH` -prevent non-privileged peers from attaching, but cannot stop root. +A privileged process can inspect other processes through mechanisms such as +`/proc/PID/mem` or `ptrace`. Root access is outside Postmaster's trust boundary. +The launcher's `PR_SET_DUMPABLE=0` and `PT_DENY_ATTACH` checks restrict +unprivileged attachment, but don't protect against a privileged inspector. ### Rotation timing oracle @@ -402,8 +399,8 @@ rest or zram to keep swap pages in RAM. **Core dumps:** Disabled at the process level (`PR_SET_DUMPABLE=0` on Linux, `RLIMIT_CORE=0` on macOS) and at the unit level when configured by the integration (`LimitCORE=0`, `CoredumpFilter=0`). Host-wide -`systemd.coredump.extraConfig = "Storage=none"` is a belt for all -units. +`systemd.coredump.extraConfig = "Storage=none"` disables storage for all +units handled by systemd-coredump. **Pre-execvp zeroization:** Private keys (the `KeyRing`) are zeroized when `decrypt()` returns and the `ring` local goes out of scope — @@ -430,18 +427,15 @@ pages before reusing them, so the plaintext exists only in freed pages until the kernel reclaims them — a transient window, not a persistent risk. -No further mitigation is possible: the kernel needs the env array -to be intact at the moment of `execvp`, and `execvp` replaces the -process image without running destructors. Fork+wait would keep -secrets in a long-lived parent heap (strictly worse) and was rejected. +The environment array must remain intact for `execvp`. Process replacement +releases the old address space without running its remaining destructors. ### Monitor inherited heap — Mitigated The sibling monitor is forked after zeroization, so the key ring and the `Zeroizing` resolved values are already wiped in the copy it -inherits. The projected -`extra` env array (plaintext values in env mode and in files-mode -passthrough). The monitor scrubs its copy **first**, before the +inherits. The projected `extra` array still contains plaintext in env mode +and files-mode passthrough. The monitor scrubs its copy before the supervision loop starts: each `OsString` is consumed into its existing buffer (no copy) and wiped in place with `zeroize` — free() alone would leave the bytes in the monitor's mapped pages for its whole life, @@ -470,40 +464,34 @@ requirements. Swap and crash-dump protections remain separate requirements. `MemorySwapMax=0` can be wired by the service manager (systemd) or the deployment integration. This enforces the cgroup's swap limit — the kernel will not swap the unit's pages even under host memory -pressure. The residual is only if the host kernel itself is -compromised, which falls under "root on the host is always game over." -Host-wide encrypted swap is recommended as defense-in-depth for the -entire host, not just postmaster's cgroup. +pressure. This depends on the deployment applying the setting and on a +trusted host kernel. Host-wide encrypted swap also protects pages outside +Postmaster's cgroup. -### VM and hypervisor inspection — Residual (no mitigation available) +### VM and hypervisor inspection A hypervisor can inspect guest memory, take snapshots, or live-migrate VMs to other hosts. Postmaster's `mlockall` and `MemorySwapMax=0` operate inside the guest kernel; the hypervisor is -outside the trust boundary. The only defense is confidential computing -hardware (AMD SEV-SNP, Intel TDX, AWS Nitro Enclaves), which is -outside postmaster's scope and dependency set. +outside the trust boundary. Confidential-computing platforms can provide +additional isolation, but their setup and guarantees are outside +Postmaster's scope. -### CPU registers and cache — Non-goal (no mitigation available) +### CPU registers and cache Plaintext secrets pass through CPU registers and L1/L2/L3 cache -during decryption and injection. Postmaster does not attempt to flush -cache lines or zero registers after use. This is a non-goal: -mitigating cache-line side channels and register residue requires -constant-time crypto implementations and hardware support (e.g., TSX -memory scrubbing, `wbinvd` instruction) that are outside postmaster's -scope. The crypto library (`ecies`) uses `secp256k1` and `AES-256-GCM` -primitives that are not guaranteed constant-time on all targets; this -is a property of the crypto library, not postmaster. +during decryption and injection. Postmaster does not flush cache lines or +zero registers after use. Zeroizing its buffers does not establish that +registers, caches, or temporary copies are clear. Constant-time behavior +also depends on the crypto implementations and target hardware; Postmaster +does not guarantee it on every target. -### Privileged ptrace — Residual (no mitigation available) +### Privileged ptrace `PR_SET_DUMPABLE=0` (Linux) and `PT_DENY_ATTACH` (macOS release builds) -prevent non-privileged peers from attaching. A privileged process -(root, or a process with `CAP_SYS_PTRACE`) can still read process -memory — this is unavoidable and the same trust boundary as "root on -the host is always game over." No software mitigation exists for -privileged memory inspection within the same kernel. +restrict unprivileged attachment when those calls succeed. A process with +sufficient OS privileges can still inspect memory. Postmaster does not +provide isolation from a privileged inspector in the same kernel. ### Plaintext file persistence window (files mode) — Mitigated @@ -515,32 +503,27 @@ function also removes stale files from prior launches before writing new ones. A `TerminationGuard` blocks SIGTERM/SIGINT/SIGHUP/SIGQUIT across the -write window on both platforms, so a signal landing mid-write cannot -strand partial plaintext. At the end of the window — after zeroization, +write window on both platforms when masking succeeds. Masking failures +are logged and leave that window unguarded; SIGKILL cannot be blocked. +At the end of the window, after zeroization and before `execvp` — the launcher forks. The parent restores its pre-guard mask and execs the service (MainPID unchanged); the fork-child is the **sibling monitor**: it keeps the four termination signals blocked for life and owns stop semantics. -*Monitor model:* the monitor consumes stop signals synchronously (no -handlers anywhere — the sigaction flag-handler and second pre-exec gate -were retired with this design), forwards them to -the service, and escalates to SIGKILL after a **250 ms grace** — a -single global constant, deliberately not configurable (per-service -erosion of a security policy is unacceptable; the per-unit knob is the -manager's own stop timeout). Cleanup runs on **every** death path: -forwarded stops, natural exit, `kill -9`, crashes. Liveness uses a -pidfd + `poll` on Linux and kqueue `NOTE_EXIT` on macOS — both fire at -exit (zombie- and PID-reuse-proof); `kill(pid, 0)` polling is fallback -only. On systemd the monitor receives its own copy of cgroup-wide stop -signals, so it never depends on a signal the launcher already consumed. -On launchd, signals go to the job's main process only, so the monitor -is primarily a cleanup-watcher there — the macOS stop-path exposure -(plus the bounded PID-reuse window of its `kill(2)` forwarding, Darwin -having no pidfd) remains bounded by the ramdisk teardown at job stop, -the strongest backstop in the system. A monitor that dies before the -service leaves the pre-existing backstops (`ExecStopPost`, teardown, -`prune_stale`) — the same floor as before the monitor existed. +The monitor consumes stop signals synchronously, forwards them to the +service, and escalates to SIGKILL after a fixed 250 ms grace. The service +manager's stop timeout is separate. The monitor attempts cleanup after +forwarded stops, natural exit, `kill -9`, and crashes. Liveness uses a +pidfd with `poll` on Linux and kqueue `NOTE_EXIT` on macOS. Both report exit +without waiting for reaping; `kill(pid, 0)` polling is a fallback. + +On systemd the monitor receives its own copy of cgroup-wide stop signals. +On launchd, signals go to the job's main process, so the monitor primarily +watches for exit and cleans up. macOS forwarding uses `kill(2)` and retains +a PID-reuse risk because Darwin has no pidfd. Ramdisk teardown at job stop +provides a separate cleanup path. If the monitor dies first, cleanup depends +on `ExecStopPost`, ramdisk teardown, or the next launch's `prune_stale`. ### Shared `secrets_dir` (multi-tenant misuse) — Documented contract diff --git a/docs/src/getting-started/injection-modes.md b/docs/src/getting-started/injection-modes.md index a97213d..d35196f 100644 --- a/docs/src/getting-started/injection-modes.md +++ b/docs/src/getting-started/injection-modes.md @@ -4,16 +4,16 @@ Postmaster supports three ways to deliver decrypted secrets to the child process. Each mode makes a different tradeoff between convenience and security. -## Audience Quickstart +## Audience quickstart -**What this is:** choosing how secrets reach your application — as -environment variables, as files, or as systemd credentials. +Choose how secrets reach your application. Storage and process isolation +depend on the deployment as well as the selected mode. -| Mode | Best for | Secrets in environ? | Hygiene | +| Mode | Use | Secrets in environ? | Storage and access | | --- | --- | --- | --- | -| `env` | 12-factor apps, simple services | Yes | Lowest — same-UID processes can read `/proc/PID/environ` | +| `env` | Apps that read environment variables | Yes | Environment copies can reach process listings, diagnostics, and child processes | | `files` | Apps that read `KEY_FILE` pointers (Docker secrets convention) | Only when `passthrough` requests it | No environment copy by default; the app still reads plaintext files | -| `credentials` | systemd services wanting strongest isolation | No — reads `$CREDENTIALS_DIRECTORY` | Highest — unit-private unswappable ramfs | +| `credentials` | Apps that read credential files | No additional value copy | Systemd supplies the credentials directory, or Postmaster fetches values from local sockets | ## Mode comparison @@ -35,8 +35,8 @@ flowchart TB ## `mode = "env"` -Decrypted values are exported into the process environment and the -wrapper `exec`s your binary. Correct for 12-factor apps. +Postmaster exports resolved values into the application environment and +replaces the launcher with your binary. **Exposure:** environment variables are readable via `/proc//environ` by root and the same UID, inherited by every child, @@ -76,7 +76,8 @@ Old read handles keep the old contents. Foreign, linked, and special entries fail closed, and exported paths require protected ancestry. Trusted symlink aliases and sticky shared parents remain supported. -For a mostly-file-capable app with a straggler that needs an env var: +If the application reads most values from files but needs one in its +environment, list that key in `passthrough`: ```json { @@ -93,20 +94,21 @@ rejection, since they become environment variables). ## `mode = "credentials"` -Real systemd credentials, served on demand by the postmaster daemon. -The consumer's unit gets +The launcher exports `_FILE` pointers into credentials that systemd has +already supplied. Systemd can obtain those credentials from Postmaster's +daemon. In that deployment, the consumer's unit gets `LoadCredential=:/run/postmaster-credd//.sock` per key and the app reads `$CREDENTIALS_DIRECTORY/` from unit-private, **unswappable** ramfs. -No Node, no jq, no shell anywhere in the consumer's start path. The -optional wrapper only exports non-secret `_FILE` pointers. -Strongest hygiene of the three. +The launcher exports file pointers without reading the credential values. +Systemd owns their storage and access controls. -On macOS, postmaster runs `--bind` (owns its sockets), the wrapper -`postmaster fetch`es each key onto the RAM disk, and exports -`$CREDENTIALS_DIRECTORY` set to `secrets_dir` — same path convention as -systemd credentials, so app code is unchanged. +For local socket delivery, normally used with launchd on macOS, the daemon +runs with `--bind`. The launcher fetches each configured key, writes it beneath +`secrets_dir`, and exports `CREDENTIALS_DIRECTORY` along with `_FILE` +pointers. The file naming convention matches systemd credentials. The fetch +branch is selected by `sockets`, not by the operating system. ## Fail-closed rules diff --git a/docs/src/getting-started/key-provisioning.md b/docs/src/getting-started/key-provisioning.md index 3aa1c9a..3ed3e70 100644 --- a/docs/src/getting-started/key-provisioning.md +++ b/docs/src/getting-started/key-provisioning.md @@ -3,14 +3,13 @@ This page covers how to get private keys onto hosts and how to rotate them without downtime. -## Audience Quickstart +## Audience quickstart -**What this is:** the operational side of postmaster — how the -decryption key gets to the host, and how to rotate it safely. +Provision a local private-key source and rotate it alongside encrypted inputs. | Reader | What to take | | -------- | ------------ | -| Operator / SRE | All sections — this is your playbook | +| Operator / SRE | Provisioning strategies and rotation | | Security engineer | The rotation window and fail-closed behavior | | New user | Skim strategies A and B, come back when you deploy | @@ -50,13 +49,12 @@ keys file fails closed for a service running as a normal user. On macOS, runtime loading and file-source `setup --recheck` also reject ACL grants that let anyone other than root or the effective user read or modify the -key file. -These checks leave the file and its ACL intact, including read-only files. +key file. These checks leave the file and its ACL intact, including read-only +files. ## Strategy B: TPM2 / host-sealed blob -Fully declarative — the key is sealed to the host's TPM2 and can only -be decrypted on that specific machine: +Seal the key to the host's TPM2 so decryption requires that host: ```console # on the target host, once (--name MUST match postmaster-) @@ -103,8 +101,8 @@ effective uid, so `root` here only works for services that run as root. ## Strategy D: macOS Keychain -The recommended path is `postmaster setup`, which seeds the wanted -keychain items interactively. By hand, use `security +Use `postmaster setup` to seed each required Keychain account once, +in first-seen input order. By hand, use `security add-generic-password` *without* `-w` so it prompts for the value: ```console @@ -115,8 +113,8 @@ $ security add-generic-password -a DOTENV_PRIVATE_KEY_PRODUCTION \ Avoid `-w ""`: it puts the private key in the process argv, visible to every process on the host via `ps`. -No file on disk — keys live as generic-password items in the default -keychain search list. Postmaster reads them natively via the +This source stores keys as generic-password items in the default Keychain +search list. Postmaster reads them through the Security.framework API (`security-framework` crate). `postmaster setup` hides terminal input for both key files and Keychain values. diff --git a/docs/src/getting-started/quick-start.md b/docs/src/getting-started/quick-start.md index b150acb..3156402 100644 --- a/docs/src/getting-started/quick-start.md +++ b/docs/src/getting-started/quick-start.md @@ -2,11 +2,10 @@ This page launches a command with values from an encrypted `.env` file. -## Audience Quickstart +## Audience quickstart -**What this is:** a hands-on walkthrough of the simplest path — -encrypting secrets, provisioning keys, and launching a service with -postmaster. +Encrypt a dotenv file, provision its private key, and launch a command with +Postmaster. ## Prerequisites @@ -83,8 +82,8 @@ visible to every process on the host via `ps`. ## Step 3: Create exec.json -Postmaster reads an `exec.json` config that specifies what to decrypt, -how to inject, and what binary to launch: +The `exec.json` config selects inputs, key sources, and projection mode. +You supply the command to launch separately after `--`: ```json { @@ -122,10 +121,9 @@ DATABASE_URL=postgres://user:pass@localhost:5432/myapp API_TOKEN=secret-token-here ``` -Postmaster decrypted the values, injected them as environment variables, -and `execvp`'d `/usr/bin/env` — which printed them. In a real deployment, -the service manager (systemd or launchd) runs postmaster, which -replaces itself with your binary. +Postmaster decrypts the values, exports them as environment variables, and +replaces the launcher with `/usr/bin/env`, which prints them. In a deployment, +systemd or launchd runs Postmaster with your service command instead. ```mermaid flowchart TB diff --git a/docs/src/introduction.md b/docs/src/introduction.md index 59f4fe4..1ae4977 100644 --- a/docs/src/introduction.md +++ b/docs/src/introduction.md @@ -1,18 +1,15 @@ # Introduction -postmaster is a **standalone, format-neutral local secret materialization -engine**. It decrypts encrypted secret inputs at process launch time and -injects them into a child process via environment variables, files, or -systemd credentials — then `execvp`s the target binary directly. No Node, -no shell, no separate CLI process in the runtime path. +Postmaster decrypts local secret inputs at process launch and delivers values +through environment variables, files, or systemd credentials. It then replaces +the launcher with the target binary through `execvp`. -## Audience Quickstart +## Audience quickstart -**What this is:** a tool that takes encrypted secrets (like database -passwords and API tokens) and safely puts them into your service's -environment at startup — without writing plaintext to disk, without -running a shell, and without keeping a long-lived parent process that -holds secrets in memory. +Decryption runs in Rust. Postmaster doesn't evaluate secret values as shell +code. Deployments provide RAM-backed storage for file projections and +configure swap and dump protection. The service manager owns the service; +a sibling monitor handles stop-signal forwarding and file cleanup. ### Who this is for @@ -31,33 +28,31 @@ holds secrets in memory. | **Materialization** | Decrypting secrets and putting them where your app can read them (env vars, files, or credentials) | | **execvp** | A Unix system call that replaces the current process with a new binary — postmaster becomes your app | | **ECIES** | Elliptic Curve Integrated Encryption Scheme — the crypto used to encrypt individual secret values | -| **exec.json** | A JSON config file that tells postmaster what to decrypt, how to inject, and what binary to launch | +| **exec.json** | A JSON config file that selects inputs, key sources, and projection mode. The command to launch is supplied separately after `--`. | | **Key source** | Where the decryption key comes from (a file, systemd credentials, macOS keychain, or environment) | | **Injection mode** | How decrypted secrets reach the child: `env` (environment variables), `files` (one file per secret), or `credentials` (systemd credentials) | | **Ciphertext** | Encrypted data — safe to store in git, the Nix store, or any world-readable location | -## The Core Problem +## The core problem -Deploying secrets to production services is hard. The secrets need to -be present at runtime, but they must not be stored in plaintext on disk, -in the container image, or in the deployment manifest. Common approaches -each have tradeoffs: +Services need secrets at runtime. Storing them in plaintext in a container +image, deployment manifest, or persistent file creates additional copies to +protect. Delivery methods have different exposure: -- **Shell wrappers** run a script that `eval`s secrets — vulnerable to - command injection if a secret contains `$(...)` or backticks. -- **External CLIs** (Node, Python) stay alive as a parent process — - secrets persist in the parent's heap for the service's entire lifetime. -- **Sidecar containers** inject secrets over the network — adds a - network dependency to the startup path. -- **Manual env vars** put plaintext secrets in the systemd unit file or - the container spec — visible in `ps`, `systemctl cat`, and crash dumps. +- **Shell wrappers** that evaluate secret values as code can execute + `$(...)` or backticks embedded in those values. +- **Parent processes** that stay alive can retain keys and decrypted values + for the service's lifetime. +- **Network delivery** adds a dependency to the startup path. +- **Plaintext environment configuration** can expose values through unit + files, container specifications, process listings, and dumps. Postmaster decrypts locally, injects directly, and replaces the launcher with your binary. It wipes its key ring and resolved buffers before launch. Deployments provide RAM-backed secret storage and configure swap and dump protection. The application keeps access to the secrets it uses. -## What postmaster Does +## What Postmaster does 1. **Decrypts** encrypted `.env` files (or `postmaster_bundle` JSON containers) using native Rust cryptography. Bundle entries use Postmaster's @@ -67,16 +62,17 @@ protection. The application keeps access to the secrets it uses. - `env` — environment variables (12-factor apps) - `files` — one file per secret on a RAM-backed filesystem (Docker secrets convention, `KEY_FILE` pointers) - - `credentials` — systemd credentials (strongest hygiene) + - `credentials` — pointers to systemd credentials or values fetched + from configured local sockets 3. **Launches** the target binary via `execvp` — postmaster is replaced - by your binary. The child process IS `MainPID` from its first + by your binary. The service process remains `MainPID` from its first instruction. A sibling monitor handles stop signals and file cleanup. 4. **Cleans up** — `postmaster cleanup` removes plaintext secret files after the child exits, wired to `ExecStopPost` in systemd. -## How postmaster Works +## How Postmaster works ```mermaid flowchart LR @@ -98,21 +94,20 @@ ones. This allows encrypted values in the Nix store, git, or an artifact registry. Private keys still need separate protection. Anyone with the public key can encrypt replacement values, so artifact write access remains trusted. -## The Secret Pipeline +## The secret pipeline -Postmaster owns exactly one stage in a 5-stage pipeline: custody +Postmaster handles local materialization and process launch in this pipeline: +custody (Vault/SSM/1Password/TPM2) → rendering (Nix/Terraform/CDK/Ansible) → delivery (systemd credentials/files/keychain/env) → **materialization (postmaster)** → launch (execvp). The stage diagram, table, and per-stage detail live in [postmaster — the secret pipeline](./architecture/postmaster.md#the-secret-pipeline). -Postmaster does not participate in stages 1-3. It does not fetch from -remote systems, does not deploy infrastructure, and owns no service -lifecycle policy — no restarts, no health checks (a sibling -monitor forwards stop signals and cleans up plaintext; the service -manager supervises the service itself). It decrypts, injects, and gets -out of the way. +External tools own custody, rendering, and delivery. Postmaster doesn't fetch +from remote stores or deploy infrastructure. Its monitor forwards stop signals +and cleans up plaintext files; the service manager owns restarts and health +checks. The monitor scrubs the projected environment pairs, but retains the original process environment. Environment-supplied private keys can remain there. @@ -120,15 +115,14 @@ The optional credential daemon also retains its key ring while serving requests. See the [Threat model](./architecture/threat-model.md) for these limits and the deployment requirements. -## Capability Horizon +## Capabilities and scope - `.env` adapter (wire-compatible with dotenvx), `postmaster_bundle` JSON container, three injection modes, four key sources (systemd credentials, files, keychain, environment), `--verify-keys` freshness check, `setup` command, `cleanup` command. -- **Non-goals:** postmaster will never become a network client for Vault, - SSM, or any remote secret store. It will not add a plugin system, an - async runtime, or a CLI parsing library. +- **Scope:** remote secret-store clients, plugin systems, an async runtime, + and a CLI parsing library are outside Postmaster's runtime contract. ## First input adapter @@ -138,8 +132,6 @@ The first input adapter is wire-compatible with existing `.env` files encrypted with the dotenvx CLI decrypt byte-exact through postmaster's native Rust implementation. -dotenvx is one adapter, not the ceiling — the architecture supports -file-based (`.env`), HashiCorp Vault, AWS SSM, and other secret providers -as source/custody backends. But those systems deliver key material to -local terminal sources; postmaster reads from those local sources and -never reaches across the network. +The bundle adapter provides a second input format. Vault, AWS SSM, and other +custody systems can deliver key material to local sources before launch. +Postmaster reads those local sources; it doesn't contact the remote store. diff --git a/docs/src/reference/cli.md b/docs/src/reference/cli.md index 7f5976a..ebbca46 100644 --- a/docs/src/reference/cli.md +++ b/docs/src/reference/cli.md @@ -1,8 +1,6 @@ # CLI reference -All postmaster commands, flags, and exit codes. The CLI is hand-rolled -with no external parsing library — every flag below is the complete -set, directly from the argument parser in `cli/mod.rs`. +Commands, flags, and exit codes accepted by `src/cli/mod.rs`. ## Synopsis @@ -105,9 +103,9 @@ Exit codes: ## setup -Create keys directory, verify permissions, optionally seed keychain -(macOS), validate environment. Idempotent — skips steps that are -already correct. +Create the keys directory, check key sources, and optionally seed macOS +Keychain accounts. Setup skips steps that are already satisfied. It derives +one required-account list in first-seen input order, without duplicate prompts. ```console $ postmaster setup --config [--recheck] [--unattended] [--force] [--keys-dir ] @@ -153,11 +151,12 @@ $ postmaster cleanup --config | --- | --- | | `--config ` | Path to `exec.json` (reads `secrets_dir` from config) | -Safety guard: cleanup refuses to bulk-delete a **non-empty** directory -that lacks the `.postmaster-managed` sentinel file (dropped by postmaster -when it writes there) — a misconfigured `secrets_dir` can never wipe a -directory postmaster doesn't manage. Empty or missing directories are -fine. +Cleanup refuses to bulk-delete a non-empty directory without the +`.postmaster-managed` sentinel. The marker identifies a managed directory, +not individual files, so keep one `secrets_dir` per service. Empty or missing +directories need no cleanup. If a secret-file stat or removal fails, the command +retains the sentinel and returns an error so cleanup can be retried. Removing +the sentinel after successful cleanup is best effort. Integrations can wire this to `ExecStopPost` in systemd. On macOS, the ramdisk destruction handles cleanup automatically when the launchd job @@ -165,9 +164,9 @@ stops. ## fetch -macOS credential fetch client — connects to a postmaster socket and -reads the decrypted value to EOF. Reads are hard-capped at 16 MiB; -an oversize stream fails rather than truncates. +Connect to a local Postmaster socket and write its decrypted value to stdout. +Reads stop at EOF and are capped at 16 MiB; an oversized stream fails without +truncating the value. This command is available on Linux and macOS. ```console $ postmaster fetch /run/postmaster-credd/myapp/DATABASE_URL.sock diff --git a/docs/src/reference/launcher-contract.md b/docs/src/reference/launcher-contract.md index 595fe21..5558b44 100644 --- a/docs/src/reference/launcher-contract.md +++ b/docs/src/reference/launcher-contract.md @@ -1,10 +1,9 @@ # Launcher contract (exec.json) -## Audience Quickstart +## Audience quickstart -**What this is:** the complete specification of `exec.json` — every -field, every mode, every validation rule. This is the contract a -binding (Nix, Terraform, CDK, Ansible) must produce. +This reference defines the fields, modes, and validation rules for `exec.json`. +Deployment integrations must generate this format. ### Who this is for @@ -19,10 +18,10 @@ binding (Nix, Terraform, CDK, Ansible) must produce. | Term | Plain meaning | | ------ | --------------- | -| **exec.json** | JSON config that tells postmaster what to decrypt and how to launch | +| **exec.json** | JSON config that selects inputs, key sources, and projection mode. The launch command follows `--` separately. | | **Projection mode** | How secrets reach the child: env, files, or credentials | | **Key source** | Where the decryption key comes from (file, credential, keychain, env) | -| **Strict** | If true (default), any decryption failure aborts the launch | +| **Strict** | If true, dotenv decryption failures abort launch. Bundle authentication failures abort under either setting. | | **Passthrough** | In files mode, specific keys also exported as env vars | `postmaster exec` is the concrete instance of the @@ -141,10 +140,10 @@ Every field except `mode` has a default, so a minimal config is just | `bundle_files` | array of paths | `[]` | Encrypted `postmaster_bundle` JSON containers, resolved after `env_files`. The first definition wins unless `overload` selects the last; bundle keys use the same identifier rule and injection modes. | | `strict` | bool | **`true`** | Undecryptable dotenv values abort launch when true and are omitted when false. Bundle authentication failures always abort. | | `overload` | bool | `false` | File-derived values override the process environment; later files override earlier ones. | -| `secrets_dir` | path or `null` | `null` | `files` mode, and `credentials` mode on the launchd/fetch path: directory plaintext files are written into. | +| `secrets_dir` | path or `null` | `null` | `files` mode, and `credentials` mode on the socket-fetch path: directory plaintext files are written into. | | `passthrough` | array of strings | `[]` | `files` mode only: these keys are *also* exported as real env vars, in addition to their `_FILE` pointer. | | `credential_keys` | array of strings | `[]` | `credentials` mode: keys to expose as `$CREDENTIALS_DIRECTORY/`. Required (non-empty) for that mode. | -| `sockets` | map of key → socket path | `{}` | `credentials` mode: postmaster socket to fetch `` from. Non-empty selects the darwin/launchd fetch path; empty means systemd already materialized the credentials via `LoadCredential=`. | +| `sockets` | map of key → socket path | `{}` | `credentials` mode: postmaster socket to fetch `` from. Non-empty selects local socket fetching on either OS; empty means systemd already materialized the credentials via `LoadCredential=`. | | `verify_ramdisk` | path or `null` | `null` | darwin only: require a RAM-backed HFS mount and a service-owned `secrets_dir` on that device. The verified directory handle is retained for plaintext I/O. | Note the field name is `verify_ramdisk`, not `ramdisk` or `ramdisk_mount` — @@ -354,23 +353,23 @@ this mode — it dispatches on whether `sockets` is empty: against running this mode outside systemd). For each key, exports `_FILE=$CREDENTIALS_DIRECTORY/` — no reading, no permission changes; systemd already owns that file. -- **`sockets` non-empty (darwin/launchd fetch path):** requires +- **`sockets` non-empty (local fetch path):** requires `secrets_dir`; runs the ramdisk guard if `verify_ramdisk` is set. For each key, looks up its socket in `sockets` (missing entry is an error), connects and reads to EOF via the same client path `postmaster fetch` uses, writes the bytes to `/` at `0600`, and exports `_FILE`. After all keys, also exports `CREDENTIALS_DIRECTORY` set to `secrets_dir` - — unlike the systemd branch, there is no real `LoadCredential` - mechanism on darwin, so the launcher has to tell the consumer that - `secrets_dir` *is* its credentials directory. + so the application can use the same credential-directory convention. + This path is normally used with launchd, but `sockets` selects it on + either supported operating system. ## Fail-closed rules - **`strict` (default `true`).** In `env`/`files` modes, if a selected dotenv value fails to decrypt (bad key, wrong key, malformed ciphertext), the whole exec aborts before the child runs — nothing partial is injected. With - `strict: false`, an undecryptable value is logged and simply omitted + `strict: false`, an undecryptable value is logged and omitted from the resolved set (never served as an error string or empty value). Bundle entries must authenticate regardless of `strict`. `--verify-keys` also rejects skipped dotenv values when `strict` is false. @@ -384,8 +383,9 @@ this mode — it dispatches on whether `sockets` is empty: to serve); failing closed"` rather than writing an empty credential file. - **16 MiB read cap.** Config JSON, bundle JSON, and credential fetch payloads - are capped at 16 MiB by `read_capped`; oversized payloads fail. Dotenv and - private-key files are streamed through `dotenvy` without this cap. + are capped at 16 MiB by `read_capped`; oversized payloads fail. Dotenv + sources have the separate byte, assignment, and expansion limits described + above. Private-key files use the `dotenvy` streaming parser without that cap. - **Missing `$CREDENTIALS_DIRECTORY`** in `credentials` mode's systemd branch fails closed rather than silently exporting nothing. - **Private keys never come from the Nix store.** A `{"file": …}` key @@ -466,11 +466,10 @@ with external secret-management tooling that materializes a `{"credential": "postmaster-myapp"}`. AWS tooling owns IAM, network I/O, and retrieval; postmaster inherits systemd's local credential access control. -- **macOS Keychain → `{"keychain": ""}`.** No external tooling - needed beyond what's already documented for `key.keychainService` - (Operational notes) — this is the existing source, not a new - composition, but the one to reach for on darwin when a file or - `LoadCredential` isn't a fit. +- **macOS Keychain → `{"keychain": ""}`.** Use + `postmaster setup` to seed the required accounts under that service name. + Postmaster reads those items through Security.framework. See + [Key provisioning](../getting-started/key-provisioning.md#strategy-d-macos-keychain). ## Conformance diff --git a/docs/src/unsafe-code/index.md b/docs/src/unsafe-code/index.md index aaa0cc4..869a630 100644 --- a/docs/src/unsafe-code/index.md +++ b/docs/src/unsafe-code/index.md @@ -1,4 +1,4 @@ -# Unsafe Code +# Unsafe code Postmaster deliberately allows `unsafe` at the lint level (documented in `[lints.rust]` in `Cargo.toml`) because it is a syscall-boundary daemon: @@ -36,7 +36,7 @@ Every `unsafe` block requires: Note what is NOT in the inventory: `mlockall`, `setrlimit(Core, 0)`, and `set_dumpable(NotDumpable)` hardening all use **safe** rustix wrappers. -## Adding Unsafe Code +## Adding Unsafe code 1. **Exhaust safe alternatives** — rustix first; is there a safe way at all? 2. **Justify in the platform note** — why this platform has no safe route diff --git a/docs/src/unsafe-code/macos-libc-boundary.md b/docs/src/unsafe-code/macos-libc-boundary.md index 017fa5f..a7a4ee6 100644 --- a/docs/src/unsafe-code/macos-libc-boundary.md +++ b/docs/src/unsafe-code/macos-libc-boundary.md @@ -1,4 +1,4 @@ -# macOS libc Boundary +# macOS libc boundary On Darwin the stable kernel ABI *is* libc, so these calls have no raw-syscall route (contrast with Linux, where rustix's `linux_raw` @@ -23,14 +23,14 @@ The credential socket must only answer the service user. On Linux the daemon reads peer credentials with `SO_PEERCRED` (safe rustix); Darwin has no `SO_PEERCRED`, so the equivalent is `getpeereid(2)` via libc. -### UB Vectors and Mitigations +### UB vectors and mitigations | Vector | Description | Mitigation | |--------|-------------|------------| | Out-param types | `getpeereid` writes a `uid_t` and a `gid_t` | Out-params are exactly `libc::uid_t`/`libc::gid_t` | | fd validity | The socket fd must stay valid for the call | Borrowed from `stream` for the call's duration only | -### Remaining Risks +### Remaining risks `getpeereid` establishes *same-euid*, not *same-process*: any process running as the service user passes. That is an accepted residual of the @@ -53,7 +53,7 @@ attachment to the daemon. Compiled only under `not(debug_assertions)`; assertions, including through a profile environment override, disables this call. A failed attach-denial request is logged. -### UB Vectors and Mitigations +### UB vectors and mitigations | Vector | Description | Mitigation | |--------|-------------|------------| diff --git a/docs/src/unsafe-code/monitor.md b/docs/src/unsafe-code/monitor.md index a24a7e4..0bde0c2 100644 --- a/docs/src/unsafe-code/monitor.md +++ b/docs/src/unsafe-code/monitor.md @@ -1,9 +1,9 @@ -# Sibling Launch Monitor +# Sibling launch monitor -> **At a glance:** a sibling process watches the service until it exits. -> It forwards stop signals, escalates to SIGKILL after a 250 ms grace, and -> removes secret files after exit, a crash, or `kill -9`. It scrubs projected -> environment pairs but retains the launcher's original environment. +A sibling process watches the service until it exits. +It forwards stop signals, escalates to SIGKILL after a 250 ms grace, and +removes secret files after exit, a crash, or `kill -9`. It scrubs projected +environment pairs but retains the launcher's original environment. ## Lifecycle @@ -48,8 +48,8 @@ Unsafe blocks: fork(2) (libc, both platforms); rustix `runtime` ## Purpose -The sibling monitor closes the launch-handoff stop-semantics gap and -adds plaintext cleanup on **every** service-death path. After +The sibling monitor forwards stop signals and attempts plaintext cleanup +after service exit. After validation, plaintext writes, and zeroization of the key ring and resolved buffers, and before `execvp`, the launcher `fork()`s. The parent restores its @@ -61,16 +61,15 @@ after a 250 ms grace (a single global security policy, deliberately not configurable), watches liveness (pidfd+poll on Linux, kqueue `EVFILT_PROC`/`NOTE_EXIT` on macOS, `kill(pid, 0)` only as fallback), and runs `cleanup_written` before exiting — on stop, on natural exit, on -`kill -9`, on crash. The sigaction flag-handler and second pre-exec gate -were retired with this design: the monitor is the single owner of stop -semantics, so no async-signal context exists anywhere. +`kill -9`, and crashes. The monitor consumes signals synchronously; it +does not install signal handlers. The scrub does not erase the monitor's original process environment. Private keys supplied through environment variables can remain there for the monitor's lifetime. Use a non-environment key source to avoid that exposure. See [Private-key environment variables](../architecture/threat-model.md#private-key-environment-variables). -## Why Unsafe +## Why unsafe - **`fork(2)` has no rustix wrapper** (a deliberate rustix omission), so it is a direct libc call on both platforms. On Linux this is the @@ -110,7 +109,7 @@ are reaped, so NOTE_EXIT registration on an already-exited service fails rustix 1.1.6 exports the experimental API as `runtime_448b8ad740e2a26f`. The launcher and monitor import it as `runtime`. -## UB Vectors and Mitigations +## UB vectors and mitigations | Vector | Description | Mitigation | |--------|-------------|------------| @@ -124,7 +123,7 @@ The launcher and monitor import it as `runtime`. | Zombie blindness | `kill(pid, 0)` succeeds on zombies | pidfd/kqueue are the primary mechanisms precisely because they fire at exit, not at reap; polling is fallback-only and documented | | Handler unsoundness | Non-reentrant work in signal context | Eliminated by design — there are no signal handlers; consumption is synchronous in the loop | -## Remaining Risks +## Remaining risks | Risk | Likelihood | Impact | |------|------------|--------| diff --git a/docs/src/unsafe-code/signal-deferral.md b/docs/src/unsafe-code/signal-deferral.md index a22b8e9..5661170 100644 --- a/docs/src/unsafe-code/signal-deferral.md +++ b/docs/src/unsafe-code/signal-deferral.md @@ -1,9 +1,9 @@ -# Signal Deferral (TerminationGuard) +# Signal deferral (TerminationGuard) -> **At a glance:** while postmaster decrypts and injects, termination -> signals are blocked to protect the plaintext-write window. The launcher -> restores the captured mask before exec. Masking failures are logged and -> leave the write window unguarded. +While Postmaster decrypts and injects, termination +signals are blocked to protect the plaintext-write window. The launcher +restores the captured mask before exec. Masking failures are logged and +leave the write window unguarded. ## Location @@ -19,11 +19,11 @@ explicitly removed, so a SIGTERM landing *during* the plaintext-write window would leave material on disk with no cleanup. `TerminationGuard` blocks SIGTERM/SIGINT/SIGHUP/SIGQUIT (`monitor::STOP_SIGNALS`) from just after config validation until the fork/exec at the end of the -window — a deterministic write window: no termination signal can kill -the launcher mid-write. +window when masking succeeds. A masking failure is logged and leaves +the window unguarded. SIGKILL cannot be blocked. At the end of the window the launcher forks the sibling monitor (see -[Sibling Launch Monitor](./monitor.md)), which **inherits the blocked +[Sibling launch monitor](./monitor.md)), which **inherits the blocked mask and keeps it for life** — the fork-child's guard is never dropped (the monitor entry point diverges and exits via `_exit`/`exit_group`, running no destructors). The parent calls `restore_mask()` before @@ -41,7 +41,7 @@ when stderr fails. Setup refuses terminal input if masking fails. Redirected input keeps stdin's existing buffer and normal signal behavior. Linux uses rustix's raw signal APIs; Darwin uses libc. -## Why Unsafe +## Why unsafe Raw signal-mask operations — `pthread_sigmask` on Darwin (whose stable kernel ABI is libc), `rt_sigprocmask` via rustix's `runtime` module on @@ -51,7 +51,7 @@ pre-fork guard shares its platform notes with the monitor page: the rustix `runtime` API is experimental (lockfile-pinned), and the mask set holds only standard signals no libc reserves. -## UB Vectors and Mitigations +## UB vectors and mitigations | Vector | Description | Mitigation | |--------|-------------|------------| @@ -62,7 +62,7 @@ holds only standard signals no libc reserves. | Mask clobber | Restoring a mask never captured | Both legs are Option-shaped and store `None` on block failure (logged); restore then no-ops | | Mask leak to the service | Service inheriting blocked termination signals | Mask restored before `execvp` on every path (explicit + `Drop` on early-Err) — the monitor *wants* the mask and is the only inheritor | -## Remaining Risks +## Remaining risks | Risk | Likelihood | Impact | |------|------------|--------| @@ -81,8 +81,7 @@ The guard's contract is exercised end-to-end by the monitor tests (`monitor::tests` — every one of them blocks via `TerminationGuard::block()` before forking the real monitor loop, exactly mirroring production) and by the exec integration suites -(`tests/exec_check.rs`, `tests/exec_conformance/`). The retired -flag-handler test was removed with the handler. +(`tests/exec_check.rs`, `tests/exec_conformance/`). Input tests use pseudo-terminals to check hidden single-line and multiline input, idle noncanonical reads, prompt failures, queued values, and terminal diff --git a/docs/src/unsafe-code/systemd-fd-ownership.md b/docs/src/unsafe-code/systemd-fd-ownership.md index 2ac8db1..9350c6d 100644 --- a/docs/src/unsafe-code/systemd-fd-ownership.md +++ b/docs/src/unsafe-code/systemd-fd-ownership.md @@ -1,9 +1,8 @@ -# systemd fd Ownership (Linux) +# systemd fd ownership (Linux) -> **At a glance:** on Linux, systemd hands postmaster ready-made -> sockets as inherited file descriptors. Adopting them is the one -> `unsafe` act on the serving path — valid exactly because systemd's -> `sd_listen_fds(3)` contract says which descriptors they are. +On Linux, systemd hands Postmaster sockets as inherited file descriptors. +Postmaster validates the `sd_listen_fds(3)` protocol before adopting them +as owned listeners. ## Location @@ -18,13 +17,13 @@ unit owns the per-(service, key) sockets and the daemon inherits them as fds `[3, 3+n)`. Serving requires a `UnixListener`, so each inherited fd is adopted with `UnixListener::from_raw_fd`. -## Why Unsafe +## Why unsafe `from_raw_fd` asserts *ownership*: if the fd were invalid, duplicated elsewhere, or owned by someone else, the result is double-close / use-after-close — undefined behavior the compiler cannot check. -## UB Vectors and Mitigations +## UB vectors and mitigations | Vector | Description | Mitigation | |--------|-------------|------------| @@ -33,7 +32,7 @@ use-after-close — undefined behavior the compiler cannot check. | fd leak to child | Inherited socket leaking across execvp | `FD_CLOEXEC` is set on the listener immediately after adoption | | Not-a-socket | Wrong unit passed non-socket fds | `getsockname(2)` mapping to the filesystem path fails closed immediately | -## Remaining Risks +## Remaining risks | Risk | Likelihood | Impact | |------|------------|--------| diff --git a/docs/src/unsafe-code/test-env-mutation.md b/docs/src/unsafe-code/test-env-mutation.md index 73d9cd5..77e31d0 100644 --- a/docs/src/unsafe-code/test-env-mutation.md +++ b/docs/src/unsafe-code/test-env-mutation.md @@ -1,17 +1,17 @@ -# Test-Only env Mutation +# Test-only environment mutation -> **At a glance:** some tests must change the process environment, -> which Rust 2024 marks `unsafe` because it can race other threads. -> Every such test holds one shared process-wide lock, so env-mutating -> tests can never run — or race — concurrently. +Some tests must change the process environment, +which Rust 2024 marks `unsafe` because it can race other threads. +Every such test holds one shared process-wide lock, so env-mutating +tests can never run — or race — concurrently. ## Location ```text src/test_util.rs — the shared ENV_LOCK itself -src/keys/source.rs (test module) — 8 tests, 17 set/remove calls -src/keys/env.rs (test module) — 2 tests, 8 set/remove calls -src/keys/provisioning/mod.rs (test module) — 3 tests, 14 set/remove calls + ambient vars() scans +src/keys/source.rs (test module) — credential and source-selection tests +src/keys/env.rs (test module) — environment key-loading tests +src/keys/provisioning/mod.rs (test module) — environment provisioning checks ``` ## Purpose @@ -23,7 +23,7 @@ Several key-source tests must set or clear `DOTENV_PRIVATE_KEY*` / `POSTMASTER_KEY*` / `CREDENTIALS_DIRECTORY` to exercise source selection. -## UB Vectors and Mitigations +## UB vectors and mitigations | Vector | Description | Mitigation | |--------|-------------|------------| @@ -34,14 +34,10 @@ Each site carries a SAFETY comment naming the serialization discipline. ## Why one process-wide lock -The discipline was previously **per-module**: `keys/source.rs` and -`keys/provisioning/mod.rs` each had their own `ENV_LOCK` static, and -`keys/env.rs`'s `from_env_loads_and_fails_closed` mutated env holding no -lock at all. Module-local locks do not exclude each other, so two such -tests still raced — the loser's panic poisoned a mutex and failed -unrelated tests (~1 in 5 baseline runs). Every env-mutating test in -every module now acquires the single `crate::test_util::ENV_LOCK`; any -new env-touching test must do the same. +Module-local locks do not exclude tests in other modules. Every test that +mutates the environment, or reads variables another test mutates, must hold +`crate::test_util::ENV_LOCK` for that scope. The lock serializes cooperating +tests; it does not control environment access inside unrelated libraries. ## Tests diff --git a/flake.nix b/flake.nix index 0c442e2..c483a16 100644 --- a/flake.nix +++ b/flake.nix @@ -1,12 +1,9 @@ { description = '' - postmaster — a standalone, format-neutral local secret - materialization engine. Decrypts encrypted secret inputs at process - launch time and injects them into a child process via environment - variables, files, or systemd credentials, then execvp's the target - binary directly. Supports file-based (.env), HashiCorp Vault, AWS SSM, - and other secret providers as source/custody backends, with Nix, CDK, - Ansible, SaltStack, Puppet, Terraform, and OpenTofu as automation targets. + Postmaster decrypts local secret inputs and delivers values through + environment variables, files, or credentials before execvp replaces the + launcher with the application. Deployment tools generate exec.json and + provide local keys, storage, permissions, and service-manager policy. ''; inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.05"; diff --git a/package.nix b/package.nix index 8e5a36f..5378756 100644 --- a/package.nix +++ b/package.nix @@ -30,13 +30,12 @@ rustPlatform.buildRustPackage { meta = { description = cargoToml.package.description; longDescription = '' - postmaster is a dependency-lean Rust daemon (edition 2024; pure-Rust - crypto with no openssl, no async runtime) that serves decrypted - values as systemd LoadCredential AF_UNIX sources (with equivalent - support under nix-darwin). It enables encrypted .env files to be - treated as ordinary, world-readable Nix store artifacts while - guaranteeing that plaintext secrets only ever appear inside - unit-private unswappable credential ramfs. + Postmaster decrypts local dotenv and bundle inputs and delivers values + through environment variables, files, or systemd credentials before + replacing the launcher with the application. It also serves credentials + over local Unix sockets. Deployments provide storage, access controls, + and service-manager hardening. Encrypted artifacts can be public; + private keys and plaintext entries need separate protection. ''; homepage = "https://github.com/beardedeagle/postmaster"; license = lib.licenses.mit; diff --git a/src/aad.rs b/src/aad.rs index 4ec3f96..29a10c5 100644 --- a/src/aad.rs +++ b/src/aad.rs @@ -46,7 +46,7 @@ mod tests { } fn vectors() -> Vec { - // Fixed outputs of the previously deployed AAD fork at 81e1b84. + // Fixed ECIES envelopes pin the wire format and entry-name authentication. serde_json::from_str(include_str!("aad/vectors.json")).unwrap() } diff --git a/src/adapter/bundle.rs b/src/adapter/bundle.rs index 29818ab..b1d6bf7 100644 --- a/src/adapter/bundle.rs +++ b/src/adapter/bundle.rs @@ -1,5 +1,4 @@ -//! `postmaster_bundle` adapter: a neutral JSON container for encrypted -//! secrets that doesn't pretend to be an `.env` file. +//! `postmaster_bundle` adapter for structured, encrypted JSON inputs. //! //! The bundle format is a JSON file with: //! - `format`: must be `"postmaster.bundle"` (fail closed on unknown) @@ -45,10 +44,8 @@ pub struct Bundle { pub entries: std::collections::BTreeMap, } -/// A recipient in the bundle: public routing metadata reserved for -/// future recipient selection. Parsed and shape-validated only today — -/// resolution selects ring candidates by the fixed `POSTMASTER_KEY` -/// variable, never by recipient. +/// Public recipient metadata, parsed but not used for key selection. +/// Resolution uses the fixed `POSTMASTER_KEY` variable. #[derive(Deserialize, Debug)] #[serde(deny_unknown_fields)] pub struct Recipient { @@ -82,8 +79,8 @@ pub enum Encoding { /// The only supported crypto suite: ECIES (secp256k1, HKDF-SHA256, /// AES-256-GCM) with the entry name bound as AES-GCM additional -/// authenticated data. Pre-AAD v1 ciphertexts are rejected at decryption -/// (authentication failure), not just here. +/// authenticated data. Ciphertexts that do not authenticate with that entry +/// name are rejected during decryption. const SUITE: &str = "ecies-secp256k1-hkdf-sha256-aes-256-gcm-entry-aad"; /// Parse a bundle JSON file, rejecting invalid metadata and reserved key names. @@ -153,8 +150,8 @@ pub fn resolve_bundle( .decode(&entry.ciphertext) .map_err(|_| format!("{}: {name} is not valid base64", bundle_path.display()))?, ); - // AAD = the entry name: a ciphertext pasted under a different - // entry fails authentication here (audit 2026-08-02 A7). + // AAD = the entry name: a ciphertext pasted under a different entry fails + // authentication here. let mut decrypted: Option>> = None; for sk in candidates { if let Some(pt) = crate::aad::decrypt(&sk[..], &ciphertext, name.as_bytes()) { @@ -178,7 +175,7 @@ pub fn resolve_bundle( } None => { let _ = ciphertext; // zeroize on drop - // No candidate count in the error text (audit 2026-08-02 A15). + // No candidate count in the error text. return Err(format!( "{}: no key under {var} decrypts {name}", bundle_path.display() @@ -336,8 +333,7 @@ mod tests { #[test] fn resolve_bundle_rejects_relocated_ciphertext() { - // audit 2026-08-02 A7: a ciphertext encrypted under one entry - // name must not decrypt under another. + // A ciphertext encrypted under one entry name must not decrypt under another. let ct = enc("REAL", "top-secret"); let bundle = make_bundle(vec![("FAKE", &ct, Encoding::Utf8)]); let ring = crate::keys::tests::make_test_ring(); @@ -416,9 +412,7 @@ mod tests { #[test] fn resolve_bundle_requires_a_postmaster_key_entry() { - // sweep 2026-08-07 T14: a ring built for a different naming (the - // bundle-ring gap's unit-test shape) must fail closed with the - // missing-entry error, never a silent skip or decrypt failure. + // A ring containing only dotenv keys must report the missing bundle key. let ct = enc("SECRET", "unreachable"); let bundle = make_bundle(vec![("SECRET", &ct, Encoding::Utf8)]); let env_only_ring = KeyRing::from_pairs( @@ -438,8 +432,8 @@ mod tests { #[test] fn resolve_bundle_rejects_invalid_base64() { - // sweep 2026-08-07 T14: malformed base64 in a ciphertext field is - // a hard parse error naming the entry, not a decrypt failure. + // Malformed base64 in a ciphertext field is a hard parse error naming the + // entry, not a decrypt failure. let bundle = make_bundle(vec![("SECRET", "!!!not-base64!!!", Encoding::Utf8)]); let ring = crate::keys::tests::make_test_ring(); let err = resolve_bundle(&bundle, &ring, Path::new("/test")).unwrap_err(); diff --git a/src/adapter/mod.rs b/src/adapter/mod.rs index 35558f0..e97342f 100644 --- a/src/adapter/mod.rs +++ b/src/adapter/mod.rs @@ -1,15 +1,11 @@ //! Adapter enum for key-naming conventions. //! -//! Different input adapters (`.env` files, `postmaster_bundle`, etc.) have -//! different conventions for how private keys are named, how metadata keys -//! are filtered, and how artifact filenames map to key variable names. This -//! enum encapsulates those conventions so the core key-loading and -//! resolution logic is adapter-neutral. +//! Dotenv and bundle inputs have different key names, metadata filters, and +//! filename mappings. `KeyNaming` keeps those rules together for loading and +//! resolution. //! -//! An enum (not a trait) is used deliberately: the set of adapters is small -//! and security-critical. Exhaustive match ensures every call site handles -//! every adapter at compile time — adding a variant is a deliberate act -//! that forces all code paths to acknowledge it. +//! Exhaustive matches make new adapter variants a compile-time obligation +//! for each dispatch site. pub mod bundle; @@ -17,9 +13,7 @@ use std::path::Path; /// The key-naming convention for a secret input adapter. /// -/// Adding a variant is a deliberate act: every match on this enum must -/// handle the new variant or the code will not compile. This is the -/// security boundary — no adapter can silently slip through unhandled. +/// Each dispatch match must handle every adapter variant. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum KeyNaming { /// The `.env` file adapter. Uses `DOTENV_PRIVATE_KEY[_]` as its @@ -72,11 +66,10 @@ impl KeyNaming { let env = rest.strip_prefix('.').ok_or_else(|| { format!("{base}: env files must follow the `.env[.]` convention") })?; - // Reject anything outside [A-Za-z0-9_]: such characters - // would sanitize to '_', making distinct filenames collide - // on the same key variable (`.env..x` ≡ `.env._x`) - // (audit 2026-08-02 A20). Letters fold to upper case, the - // dotenvx convention. + // Reject anything outside [A-Za-z0-9_]: such characters would sanitize + // to '_', making distinct filenames collide on the same key variable + // (`.env..x` ≡ `.env._x`). Letters fold to upper case, the dotenvx + // convention. if env.is_empty() || !env.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { return Err(format!( "{base}: environment name must be non-empty [A-Za-z0-9_] only" @@ -125,15 +118,13 @@ mod tests { #[test] fn key_var_for_requires_the_dot_env_convention() { - // Consolidated from the keys/exec_config test copies (sweep - // 2026-08-07 T13): the mapping lives here, so its legs do too. + // Dotenv inputs must follow the .env[.] naming convention. assert!(KeyNaming::Env.key_var_for(Path::new("no-dot-env")).is_err()); } #[test] fn key_var_for_rejects_aliasing_names() { - // audit 2026-08-02 A20: `.env..x` used to alias `.env._x` onto the - // same key variable (DOTENV_PRIVATE_KEY__X); lossy names now fail. + // Reject lossy names that could alias another file's key variable. assert!(KeyNaming::Env.key_var_for(Path::new("/x/.env..x")).is_err()); assert!(KeyNaming::Env.key_var_for(Path::new("/x/.env.-x")).is_err()); assert!(KeyNaming::Env.key_var_for(Path::new("/x/.env.")).is_err()); diff --git a/src/cli/help.rs b/src/cli/help.rs index 13a4acf..597812a 100644 --- a/src/cli/help.rs +++ b/src/cli/help.rs @@ -19,7 +19,7 @@ help Show help for a subcommand or this message\n\n\ OPTIONS:\n \ --config Configuration file (required for serve, exec, setup, cleanup)\n \ --bind (serve) Bind listener sockets even if not socket-activated\n \ ---allow-nonroot (serve) Allow non-root connections (dangerous)\n \ +--allow-nonroot (serve) Allow any UID when peer_user is unset\n \ --check (exec) Validate config shape only, no decryption or exec\n \ --verify-keys (exec) Preflight key freshness check before exec\n \ --recheck (setup) Verification only, no creation or modification\n \ @@ -33,9 +33,8 @@ OPTIONS:\n \ pub const HELP_EXEC: &str = "postmaster exec — decrypt secrets and exec a child process\n\n\ USAGE:\n \ postmaster exec --config [--check] [--verify-keys] -- [args…]\n\n\ -Decrypts the configured env files and/or bundle files using the loaded key\n\ -ring, injects the resolved values into the child environment (or writes them\n\ -as files / credential pointers depending on mode), and execs the command.\n\n\ +Resolves configured inputs, projects values through environment variables,\n\ +files, or credential pointers, and replaces the launcher with the command.\n\n\ OPTIONS:\n \ --config Exec config JSON (required)\n \ --check Validate config shape only, no decryption, no exec\n \ @@ -43,29 +42,31 @@ OPTIONS:\n \ under `strict:false` any skipped/undecryptable value also aborts\n \ the launch (fail-closed)\n \ -- Everything after `--` is the child argv (required unless --check)\n\n\ -The config must specify mode (env/files/credentials), key sources, and\n\ -artifact paths. See docs/src/reference/launcher-contract.md for the full contract.\n"; +The config selects mode (env/files/credentials) and its required fields.\n\ +Env and files modes need key sources and artifact paths. Credentials mode\n\ +uses existing credential files or configured local sockets. See\n\ +docs/src/reference/launcher-contract.md for the full contract.\n"; /// Help text for the `fetch` subcommand. pub const HELP_FETCH: &str = "postmaster fetch — fetch a secret from a daemon socket\n\n\ USAGE:\n \ postmaster fetch \n\n\ -Connects to a running postmaster daemon's AF_UNIX socket, requests the\n\ -default secret, and writes the decrypted bytes to stdout. Used internally\n\ -by the credentials-mode launcher on macOS (launchd) to pull secrets from\n\ -the daemon into the RAM disk.\n\n\ +Connects to a local postmaster AF_UNIX socket, reads its configured secret\n\ +to EOF, and writes the bytes to stdout. The credentials-mode launcher uses\n\ +the same client path when sockets are configured. Available on Linux and macOS.\n\n\ The socket path must be a single relative or absolute path to the AF_UNIX\n\ socket created by `postmaster --config `.\n"; /// Help text for the `setup` subcommand. -pub const HELP_SETUP: &str = "postmaster setup — verify environment and create key material\n\n\ +pub const HELP_SETUP: &str = "postmaster setup — provision and verify local key sources\n\n\ USAGE:\n \ postmaster setup --config [--recheck] [--unattended] [--force] [--keys-dir ]\n\n\ Verifies platform prerequisites, creates the keys directory with 0700\n\ permissions, verifies or creates keys files with 0600, optionally seeds\n\ keychain items (macOS, interactive), and validates the environment.\n\n\ -Idempotent — each step checks whether the target state is already present\n\ -and correct, and skips if it is. Safe to run on every converge cycle.\n\n\ +Steps already satisfied are skipped. Use --unattended for automated runs;\n\ +it fails if operator input is required. Required Keychain accounts are\n\ +deduplicated before prompting, preserving first-seen input order.\n\n\ OPTIONS:\n \ --config Exec config JSON (required)\n \ --recheck Verification only — no creation or modification\n \ @@ -83,9 +84,10 @@ postmaster cleanup --config \n\n\ Reads the exec config, extracts secrets_dir, and removes all regular files\n\ in that directory. Intended for ExecStopPost in systemd or equivalent\n\ lifecycle hooks in other service managers.\n\n\ -Does not decrypt — only removes files that postmaster would have written.\n\ -Safety guard: a NON-EMPTY directory without a .postmaster-managed sentinel\n\ -file is left untouched (postmaster only bulk-deletes directories it manages).\n\ -Safe to run even if the directory is already empty or does not exist.\n\n\ +Does not decrypt. A non-empty directory without a .postmaster-managed\n\ +sentinel is left untouched. The marker identifies the managed directory,\n\ +not individual files. Keep one secrets_dir per service. Empty or missing\n\ +directories need no cleanup. Secret-file removal failures retain the marker\n\ +and return an error so cleanup can be retried.\n\n\ OPTIONS:\n \ --config Exec config JSON (required)\n"; diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 462728d..7c2ecb4 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -1,8 +1,8 @@ //! CLI parsing (`Invocation`, `parse_args`, help text) and the //! configuration data structures for postmaster's daemon and exec modes. //! -//! The config is generated by the Nix module as JSON. It contains only -//! public information (store paths for ciphertext + key *names*). +//! Deployment tools provide JSON configuration containing public paths, +//! key-source names, and projection settings. use std::collections::HashMap; use std::path::PathBuf; @@ -11,12 +11,10 @@ use serde::Deserialize; mod help; -/// Help text constants, re-exported so `crate::config::HELP_*` keeps -/// resolving via the `cli as config` re-export in `lib.rs`. +/// CLI help text, also available through the `crate::config` alias. pub use help::{HELP_CLEANUP, HELP_EXEC, HELP_FETCH, HELP_SETUP, HELP_TOP}; -/// Full configuration loaded from the JSON file produced by the Nix module. -/// Unknown fields are rejected — same strictness as the exec config. +/// Daemon configuration loaded from JSON. Unknown fields are rejected. #[derive(Deserialize, Debug)] #[serde(deny_unknown_fields)] pub struct Config { @@ -41,7 +39,7 @@ pub enum KeysSource { /// A single credential mapping served by postmaster. Unknown fields are /// rejected — same strictness as `Config`. pub struct Entry { - /// encrypted env file (a Nix store path; ciphertext is public). + /// Dotenv input containing encrypted values, plaintext entries, or both. pub env_file: PathBuf, /// Which key inside it to serve. pub key: String, @@ -49,9 +47,8 @@ pub struct Entry { /// A hash must match before parsing, interpolation or decryption. #[serde(deserialize_with = "deserialize_env_file_hashes")] pub env_file_sha256: Vec<[u8; 32]>, - /// Additionally allow this (non-root) user to fetch the credential. - /// Used by the darwin module, where consumers are launchd daemons - /// connecting as their own service user rather than uid 0 (root). + /// Allow this user as well as root to fetch the credential. + /// Enforced even when `--allow-nonroot` is set. #[serde(default)] pub peer_user: Option, } @@ -209,7 +206,7 @@ pub fn parse_args_from(args: impl IntoIterator) -> Result { it.next(); match it.next() { - // Every subcommand takes --help/-h (sweep 2026-08-07 D5). + // Every subcommand takes --help/-h. Some(a) if a == "--help" || a == "-h" => Ok(Invocation::Help(Some("fetch".into()))), Some(path) => { if it.next().is_some() { @@ -472,9 +469,8 @@ mod tests { #[test] fn config_rejects_unknown_fields_in_nested_entry() { - // audit 2026-08-02 A21: the nested credential Entry is as strict - // as the top-level Config — an unknown field is a binding bug, - // not something to silently ignore. + // The nested credential Entry is as strict as the top-level Config — an unknown + // field is a binding bug, not something to silently ignore. let raw = serde_json::json!({ "keys": {"file": "/run/postmaster/.env.keys"}, "credentials": { @@ -560,8 +556,7 @@ mod tests { #[test] fn parse_help_in_fetch_subcommand() { - // sweep 2026-08-07 D5: fetch takes --help/-h like every other - // subcommand (previously "--help" was treated as the socket path). + // Fetch accepts --help/-h without treating either flag as a socket path. assert!(matches!( parse(&["fetch", "--help"]), Ok(Invocation::Help(Some(s))) if s == "fetch" @@ -579,8 +574,7 @@ mod tests { #[test] fn parse_rejects_flag_as_option_value() { - // sweep 2026-08-07 D6: a value-taking option must not swallow the - // following flag as its value. + // A value-taking option must not swallow the following flag as its value. let err = parse(&["exec", "--config", "--check"]).unwrap_err(); assert!(err.contains("--config"), "{err}"); assert!(err.contains("--check"), "{err}"); diff --git a/src/exec_config.rs b/src/exec_config.rs index b31d3cf..49e2c93 100644 --- a/src/exec_config.rs +++ b/src/exec_config.rs @@ -12,9 +12,8 @@ use serde::Deserialize; use crate::adapter::KeyNaming; -/// Launcher configuration for `postmaster exec` — THE cross-binding -/// contract. Generated by the Nix module (later: other bindings); contains -/// only public data: store paths of ciphertext, key *names*, socket paths. +/// Public launcher configuration shared by deployment integrations. +/// Contains input paths, key-source names, and projection settings, not secret values. #[derive(Deserialize, Debug)] #[serde(deny_unknown_fields)] pub struct ExecConfig { @@ -39,22 +38,22 @@ pub struct ExecConfig { /// File values override process env; later files override earlier. #[serde(default)] pub overload: bool, - /// files/credentials(darwin) mode: where plaintext files land. + /// Output directory for files mode and the credentials socket-fetch path. #[serde(default)] pub secrets_dir: Option, - /// files mode: keys ALSO exported as real env vars. + /// Files-mode keys also exported as environment values alongside file pointers. #[serde(default)] pub passthrough: Vec, /// credentials mode: keys exposed as `$CREDENTIALS_DIRECTORY/`. #[serde(default)] pub credential_keys: Vec, - /// credentials mode, darwin: key → postmaster socket to fetch from. + /// Credentials-mode key names mapped to local Postmaster sockets. /// Non-empty selects the fetch path; empty means systemd already /// materialized the credentials. #[serde(default)] pub sockets: HashMap, - /// darwin: refuse to write plaintext unless this mount point is the - /// HFS ramdisk and secrets_dir is a directory we own. + /// On macOS, require a RAM-backed HFS mount and an owned `secrets_dir` + /// on that device before writing plaintext. #[serde(default)] pub verify_ramdisk: Option, } @@ -102,12 +101,9 @@ impl ExecConfig { Ok(()) } - /// The key-naming conventions this config's artifacts require: - /// `Env` when `env_files` are present, `Bundle` when `bundle_files` - /// are present (both when both are). `load_ring` admits exactly these - /// namings into the key ring — no more (least privilege on key - /// material), no less (a bundle config must actually see - /// `POSTMASTER_KEY`). + /// Return the key-naming conventions required by the configured inputs. + /// `load_ring` admits only these namespaces: `Env` for dotenv files, + /// `Bundle` for bundles, or both for mixed inputs. pub fn required_namings(&self) -> Vec { let mut namings = Vec::with_capacity(2); if !self.env_files.is_empty() { diff --git a/src/keys/env.rs b/src/keys/env.rs index d6b39a1..b0fecae 100644 --- a/src/keys/env.rs +++ b/src/keys/env.rs @@ -25,11 +25,10 @@ pub(crate) fn is_private_key_var_name(name: &str) -> bool { /// Implementation of [`KeyRing::from_env`]; the contract is documented on /// the method. pub(super) fn from_env(namings: &[KeyNaming]) -> Result { - // vars_os + skip non-UTF-8 names/values: std::env::vars() PANICS during - // iteration if any inherited entry is not valid Unicode, which under - // panic=abort aborts the whole launcher on an arbitrary inherited - // variable (sweep 2026-08-07 K3). Key-var names match [A-Za-z0-9_] and - // key values are hex, so nothing admissible is lost. + // vars_os + skip non-UTF-8 names/values: std::env::vars() PANICS during iteration + // if any inherited entry is not valid Unicode, which under panic=abort aborts the + // whole launcher on an arbitrary inherited variable. Key-var names match + // [A-Za-z0-9_] and key values are hex, so nothing admissible is lost. KeyRing::from_pairs( std::env::vars_os() .filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?))) @@ -48,8 +47,8 @@ mod tests { #[test] fn is_key_var_name_rules() { - // audit 2026-08-02 A16: only `PREFIX` or `PREFIX_` match; - // prefix-substring collisions are rejected. + // Only `PREFIX` or `PREFIX_` match; prefix-substring collisions are + // rejected. let p = "DOTENV_PRIVATE_KEY"; assert!(is_key_var_name(p, "DOTENV_PRIVATE_KEY")); assert!(is_key_var_name(p, "DOTENV_PRIVATE_KEY_PRODUCTION")); diff --git a/src/keys/keychain.rs b/src/keys/keychain.rs index 64892c2..b7685a7 100644 --- a/src/keys/keychain.rs +++ b/src/keys/keychain.rs @@ -1,4 +1,4 @@ -//! macOS System keychain key source. +//! macOS Keychain source using the default keychain search list. use zeroize::Zeroizing; @@ -13,11 +13,9 @@ pub(super) fn from_keychain( vars: &[String], namings: &[KeyNaming], ) -> Result { - // Reads go through the Security.framework API, not the - // /usr/bin/security CLI (F1 direction): no subprocess, no argv, - // and no stdout buffer holding key material — the UTF-8-failure - // path validates from a borrow so the error never carries the - // bytes (audit 2026-08-02 A17). + // Reads go through the Security.framework API, not the /usr/bin/security CLI: no + // subprocess, no argv, and no stdout buffer holding key material — the + // UTF-8-failure path validates from a borrow so the error never carries the bytes. let mut pairs = Vec::new(); for var in vars { let bytes = Zeroizing::new( diff --git a/src/keys/load.rs b/src/keys/load.rs index ef99b0b..e691523 100644 --- a/src/keys/load.rs +++ b/src/keys/load.rs @@ -1,4 +1,4 @@ -//! `.env.keys` file loading with on-fd stat hardening (no TOCTOU window). +//! `.env.keys` loading with type, ownership, and access checks on the opened inode. use std::path::Path; @@ -10,10 +10,9 @@ use crate::adapter::KeyNaming; /// Implementation of [`KeyRing::load`]; the contract is documented on the /// method. pub(super) fn load(path: &Path, namings: &[KeyNaming]) -> Result { - // NONBLOCK is inert on regular files; on a FIFO it turns the otherwise - // blocking open into an immediate success that the file-type check - // below rejects — a FIFO here must never hang the launcher at open - // (sweep 2026-08-07 K5). + // NONBLOCK is inert on regular files; on a FIFO it turns the otherwise blocking + // open into an immediate success that the file-type check below rejects — a FIFO + // here must never hang the launcher at open. let oflags = rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC @@ -26,9 +25,8 @@ pub(super) fn load(path: &Path, namings: &[KeyNaming]) -> Result {} diff --git a/src/keys/mod.rs b/src/keys/mod.rs index 67096b7..015239c 100644 --- a/src/keys/mod.rs +++ b/src/keys/mod.rs @@ -1,11 +1,11 @@ //! Key loading, variable name resolution, and ciphertext decryption. //! -//! All secret material is Zeroized. Decryption is tried with rotation candidates. +//! The key ring and resolved values use zeroizing buffers. Decryption tries +//! rotation candidates in order; the source environment is not zeroized. //! Plaintext values (from `dotenvx set --plain`) are passed through. //! -//! Key-naming conventions are abstracted via the `KeyNaming` trait -//! (see `adapter/mod.rs`), so the core logic is adapter-neutral. The `.env` -//! adapter's `KeyNaming::Env` is the first implementation. +//! The `KeyNaming` enum in `adapter/mod.rs` defines the dotenv and bundle +//! namespaces used by loading and resolution. use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -26,7 +26,7 @@ pub mod provisioning; pub mod source; mod verify; -/// Re-exported so `crate::keys::verify_external_binary` keeps resolving. +/// Shared external-helper verification. pub use verify::verify_external_binary; /// Key-variable predicates shared by loading, setup and launch validation. @@ -37,11 +37,7 @@ pub(crate) use env::{is_key_var_name, is_private_key_var_name}; /// comma-separated rotation convention; decryption tries each in order. pub struct KeyRing(HashMap>>); -// Redacted Debug: variable names only, never key material. A derived impl -// would print every 32-byte key verbatim — zeroize's `Zeroizing` derives -// its own Debug pass-through to the inner value — a latent leak channel on -// a public type (sweep 2026-08-07 K1). Tests need *a* Debug impl for -// `Result::expect_err`; this keeps that working without the leak. +// Zeroizing forwards Debug to its inner value; derive would expose every private key. impl std::fmt::Debug for KeyRing { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("KeyRing") @@ -59,8 +55,8 @@ impl KeyRing { /// Load a `.env.keys` file from `path` and build a key ring. /// - /// Security invariants enforced on the opened file (all checked on the - /// file descriptor, never the path, to eliminate TOCTOU windows): + /// Checks apply to the opened inode, so path replacement cannot change + /// which file is validated and read: /// - `O_NOFOLLOW`: reject a symlink at `path` (defense-in-depth; also /// closes the credential-source symlink attack leg). /// - `mode & 0o077 == 0`: no group or world read/write/exec. A keys @@ -76,17 +72,18 @@ impl KeyRing { load::load(path, namings) } - /// Core parser shared by every key source: keep keys exactly matching - /// the required adapters' key prefixes (`PREFIX` or `PREFIX_` — - /// the key-variable predicate; a bare starts_with admitted unreachable - /// prefix-collision material like `DOTENV_PRIVATE_KEYFOO` from keys - /// files), split comma-separated rotation - /// candidates, hex-decode to 32-byte zeroized keys. Empty result is an - /// error (fail closed). Takes `Zeroizing` values so callers - /// never hand key material as a plain heap String that drops without - /// zeroization. `namings` is the set the config's artifacts require - /// (see `ExecConfig::required_namings`) — the ring admits exactly - /// those prefixes, no more (least privilege on key material). + /// Parse key values shared by all local key sources. + /// + /// Keep names matching the required adapters' exact prefix or a prefix + /// followed by `_`. Split comma-separated rotation + /// candidates and decode each into a zeroizing 32-byte key. + /// `namings` comes from `ExecConfig::required_namings`; other namespaces + /// are discarded. Input values use `Zeroizing` so discarded + /// material is wiped on drop. + /// + /// # Errors + /// + /// Return an error for invalid key material or an empty required ring. pub fn from_pairs( pairs: impl IntoIterator)>, namings: &[KeyNaming], @@ -129,14 +126,14 @@ impl KeyRing { Ok(KeyRing(map)) } - /// Private key variables from the process environment (external - /// provisioning; `key.file = null` in the module). Reads all - /// variables matching any required adapter's key prefix. + /// Read private-key variables matching the required adapter namespaces + /// from the process environment. pub fn from_env(namings: &[KeyNaming]) -> Result { env::from_env(namings) } - /// macOS System keychain: one generic-password item per variable, + /// Read macOS Keychain through the default search list. Each variable uses + /// one generic-password item: /// service = `service`, account = the adapter's key variable name. /// Only the vars actually needed (derived from artifact names) are /// fetched. @@ -166,7 +163,7 @@ fn empty_error(namings: &[KeyNaming]) -> String { } } -/// Shell-identifier check shared with the Nix module's eval-time isIdent. +/// Check an ASCII identifier used for environment names and secret filenames. pub fn is_ident(k: &str) -> bool { let mut cs = k.chars(); matches!(cs.next(), Some(c) if c.is_ascii_alphabetic() || c == '_') @@ -220,8 +217,8 @@ pub fn decrypt_value( return Ok(Zeroizing::new(pt)); } } - // No candidate count in the error text — the rotation-set size is - // not something errors should leak (audit 2026-08-02 A15). + // No candidate count in the error text — the rotation-set size is not something + // errors should leak. Err(format!( "{}: no key under {var} decrypts {key}", env_file.display() @@ -266,8 +263,7 @@ pub struct Resolution { pub failed: Vec<(String, String)>, } -// Redacted Debug, same channel as K1 (sweep 2026-08-07 K2): names only — -// a derived impl would print the decrypted plaintext values themselves. +// A derived Debug implementation would expose decrypted values; print names only. impl std::fmt::Debug for Resolution { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Resolution") @@ -284,8 +280,8 @@ impl std::fmt::Debug for Resolution { } /// Resolve every key across `files` per the precedence contract -/// (see docs/src/launcher-contract.md): within one file the LAST assignment -/// wins (dotenv semantics); across files the FIRST file defining a key wins +/// (see `docs/src/reference/launcher-contract.md`): within one file the last +/// assignment wins; across files the first file defining a key wins /// unless `overload`; keys already present in the process environment are /// skipped unless `overload`. Adapter metadata keys are dropped; /// non-identifier keys are a hard error (they become env names/filenames). @@ -326,9 +322,8 @@ pub fn resolve_all( file_vals.insert(k, v); // last assignment within a file wins } for k in file_order { - // Unreachable invariant (file_order mirrors file_vals), but a - // clear error beats an abort under panic=abort (audit - // 2026-08-02 A22). + // Unreachable invariant (file_order mirrors file_vals), but a clear error + // beats an abort under panic=abort. let Some(v) = file_vals.remove(&k) else { return Err(format!("internal: {k} in file_order but not file_vals")); }; @@ -348,8 +343,8 @@ pub fn resolve_all( if !overload && env_has(&k) { continue; // process environment wins } - // Unreachable invariant (order mirrors merged), but a clear error - // beats an abort under panic=abort (audit 2026-08-02 A22). + // Unreachable invariant (order mirrors merged), but a clear error beats an + // abort under panic=abort. let Some((file, raw)) = merged.remove(&k) else { return Err(format!("internal: {k} in order but not merged")); }; @@ -400,8 +395,7 @@ pub mod tests { let mut f = std::fs::File::create(&path).unwrap(); writeln!(f, "{}", content).unwrap(); } - // KeyRing::load now enforces 0600-or-stricter permissions (audit - // finding #1). The temp file must pass that check. + // Match the owner-only permissions required by KeyRing::load. std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); f(&path); let _ = std::fs::remove_file(&path); @@ -696,9 +690,8 @@ pub mod tests { ) .is_err() ); - // non-strict: skipped, not served wrong — and the skip is - // recorded so --verify-keys can fail closed on it (audit - // 2026-08-02 A3). + // Non-strict: skipped, not served wrong — and the skip is recorded so + // --verify-keys can fail closed on it. let out = resolve_all( &[d.join(".env")], &ring, @@ -715,9 +708,8 @@ pub mod tests { #[test] fn keyring_debug_redacts_key_material() { - // sweep 2026-08-07 K1: a derived Debug would print every 32-byte - // key verbatim (Zeroizing's Debug passes through to the inner - // value). Names only. + // A derived Debug would print every 32-byte key verbatim (Zeroizing's Debug + // passes through to the inner value). Names only. let ring = KeyRing::from_pairs( [( "DOTENV_PRIVATE_KEY".to_string(), @@ -736,8 +728,7 @@ pub mod tests { #[test] fn resolution_debug_redacts_plaintext() { - // sweep 2026-08-07 K2: same channel — a derived Debug would print - // the decrypted plaintext values themselves. + // Debug output must expose names without decrypted values. let r = Resolution { resolved: vec![( "MY_SECRET".to_string(), @@ -756,9 +747,7 @@ pub mod tests { #[test] fn from_pairs_uses_the_exact_key_var_predicate() { - // sweep 2026-08-07 K6: bare starts_with admitted - // DOTENV_PRIVATE_KEYFOO from keys files as unreachable dead - // material; the A16 predicate drops it exactly as from_env does. + // Reject prefix lookalikes consistently across file and environment sources. let ring = KeyRing::from_pairs( [ ( @@ -779,9 +768,7 @@ pub mod tests { #[test] fn resolve_all_refuses_symlinked_env_file() { - // sweep 2026-08-07 T5: the O_NOFOLLOW ciphertext open (audit - // 2026-08-02 A13) — a planted symlink at a configured .env path - // is a hard error, never a read-through. + // A symlink at a configured .env path must fail before reading its target. let d = tdir("symlink"); std::fs::write(d.join(".env.real"), "A=plain\n").unwrap(); std::os::unix::fs::symlink(d.join(".env.real"), d.join(".env")).unwrap(); @@ -800,9 +787,8 @@ pub mod tests { #[test] fn decrypt_value_fails_closed_on_bad_base64_and_missing_ring_entry() { - // sweep 2026-08-07 T14: decrypt_value's two fail-closed legs, - // exercised directly (the resolve paths reach them only - // indirectly). + // decrypt_value's two fail-closed legs, exercised directly (the resolve paths + // reach them only indirectly). let env_file = Path::new(".env"); let ring = KeyRing(HashMap::new()); diff --git a/src/keys/provisioning/cleanup.rs b/src/keys/provisioning/cleanup.rs index c91a46c..a16ad1f 100644 --- a/src/keys/provisioning/cleanup.rs +++ b/src/keys/provisioning/cleanup.rs @@ -8,13 +8,13 @@ use crate::server::log; /// `postmaster cleanup`: remove all secret files from the secrets_dir /// configured in the exec config. Intended for `ExecStopPost` in systemd -/// or equivalent lifecycle hooks. Does not decrypt — only removes files -/// that postmaster would have written. Bulk removal is guarded by the +/// or equivalent lifecycle hooks. Removes regular files without decrypting. +/// Bulk removal is guarded by the /// `.postmaster-managed` sentinel: a non-empty directory lacking it is /// refused (postmaster only bulk-deletes directories it manages). The -/// sentinel is removed last, and ONLY when every managed regular file +/// sentinel is removed last, and only when every managed regular file /// was removed successfully — on any stat/unlink failure the sentinel -/// is RETAINED and the command fails, so a retry is not refused as +/// is retained and the command fails, so a retry is not refused as /// unmanaged while plaintext files survive. Safe to run even if the /// directory is empty or does not exist. pub fn cleanup(config_path: &Path) -> Result<(), String> { @@ -23,11 +23,10 @@ pub fn cleanup(config_path: &Path) -> Result<(), String> { .secrets_dir .as_deref() .ok_or("cleanup: config has no secrets_dir — nothing to clean up")?; - // Pin the directory by fd: O_DIRECTORY|O_NOFOLLOW rejects a symlinked - // or non-directory secrets dir at open, and the sentinel check, the - // per-entry stat, and every unlink below are all relative to the - // pinned inode — no path is ever re-resolved (audit 2026-08-02 - // A12/A19). + // Pin the directory by fd: O_DIRECTORY|O_NOFOLLOW rejects a symlinked or + // non-directory secrets dir at open, and the sentinel check, the per-entry stat, + // and every unlink below are all relative to the pinned inode — no path is ever + // re-resolved. let dir_fd = match open_secrets_dir(dir) { Ok(fd) => fd, Err(rustix::io::Errno::NOENT) => { @@ -53,9 +52,8 @@ pub fn cleanup(config_path: &Path) -> Result<(), String> { )); return Ok(()); } - // Managed-dir guard (audit 2026-08-02 A19): non-empty and no - // sentinel means postmaster never wrote here — bulk deletes could - // hit foreign files. Refuse. + // Managed-dir guard: non-empty and no sentinel means postmaster never wrote here — + // bulk deletes could hit foreign files. Refuse. match rustix::fs::statat( &dir_fd, MANAGED_SENTINEL, @@ -148,8 +146,8 @@ mod tests { #[test] fn cleanup_removes_all_files_from_secrets_dir() { let dir = crate::test_util::temp_dir::TestDir::new("cleanup"); - // cleanup requires a postmaster-managed (owner-only) dir - // (audit 2026-08-02 A19); match real deployments. + // Cleanup requires a postmaster-managed (owner-only) dir; match real + // deployments. use std::os::unix::fs::PermissionsExt; fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); fs::write(dir.join("KEY_A"), b"secret-a").unwrap(); @@ -180,9 +178,8 @@ mod tests { #[test] fn cleanup_refuses_unmanaged_dir() { - // audit 2026-08-02 A19: a non-empty dir without the sentinel was - // never written by postmaster; cleanup must refuse to bulk-delete - // there (foreign files could be present). + // A non-empty dir without the sentinel was never written by postmaster; cleanup + // must refuse to bulk-delete there (foreign files could be present). let dir = crate::test_util::temp_dir::TestDir::new("cleanup"); fs::write(dir.join("FOREIGN"), b"not-ours").unwrap(); let cfg_path = dir.join("exec.json"); diff --git a/src/keys/provisioning/mod.rs b/src/keys/provisioning/mod.rs index 7f9a728..ff6a9bc 100644 --- a/src/keys/provisioning/mod.rs +++ b/src/keys/provisioning/mod.rs @@ -36,18 +36,16 @@ fn default_keys_dir() -> PathBuf { PathBuf::from("/var/lib/postmaster") } -/// Create the keys directory with 0700 permissions if it doesn't exist. -/// If it exists, verify permissions and ownership are correct, correcting -/// the mode whenever wrong. `force` has no directory effect — there is -/// nothing to re-seed in a directory; force governs the keys file and the -/// keychain items. +/// Create a 0700 keys directory, or check the existing directory's ownership +/// and remove group or other access. `force` affects key files and Keychain +/// items, not the directory. #[allow(clippy::print_stderr)] fn ensure_keys_dir(keys_dir: &Path, _force: bool) -> Result<(), String> { if keys_dir.exists() { // Open the directory itself and work on the fd throughout: - // O_DIRECTORY|O_NOFOLLOW rejects symlinks and non-directories at - // open, and fchmod on the fd eliminates the TOCTOU between a - // path-based check and a path-based chmod (audit 2026-08-02 A5). + // O_DIRECTORY|O_NOFOLLOW rejects symlinks and non-directories at open, and + // fchmod on the fd eliminates the TOCTOU between a path-based check and a + // path-based chmod. let dir_fd = rustix::fs::open( keys_dir, rustix::fs::OFlags::RDONLY @@ -84,12 +82,11 @@ fn ensure_keys_dir(keys_dir: &Path, _force: bool) -> Result<(), String> { return Ok(()); } - // Create the directory with 0700. create_dir_all follows intermediate - // symlinks, so first reject any existing symlink component in the - // prefix (audit 2026-08-02 O5). Residual TOCTOU: a component could be - // swapped between this check and the create, but an attacker with - // that write access could plant the symlink outright — and the open - // below is still NOFOLLOW on the final component. + // Create the directory with 0700. create_dir_all follows intermediate symlinks, so + // first reject any existing symlink component in the prefix. Residual TOCTOU: a + // component could be swapped between this check and the create, but an attacker + // with that write access could plant the symlink outright — and the open below is + // still NOFOLLOW on the final component. let mut prefix = PathBuf::new(); for comp in keys_dir.components() { prefix.push(comp); @@ -130,10 +127,9 @@ fn ensure_keys_dir(keys_dir: &Path, _force: bool) -> Result<(), String> { Ok(()) } -/// Verify a keys file exists with correct permissions (0600, owned by -/// euid). If the file doesn't exist, in interactive mode, prompt the -/// operator to create it. In unattended mode, fail closed. If the file -/// exists but has wrong permissions, fix them. +/// Check an owned, regular key file and remove group or other access. +/// Prompt for missing contents in interactive mode; fail closed if unattended. +/// New files and forced replacements use fresh 0600 inodes. /// /// `--force` re-prompts for the contents even when the file is already /// correct (manual key rotation). Force requires @@ -275,7 +271,7 @@ fn ensure_keys_file(path: &Path, force: bool, unattended: bool) -> Result<(), St /// Verify keychain items exist for the wanted key variables. If they /// don't exist and we're in interactive mode, offer to seed them. -/// `--force` re-seeds EVERY wanted item, present or not. On macOS only. +/// `--force` re-seeds every wanted item, including existing ones. macOS only. #[cfg(target_os = "macos")] #[allow(clippy::print_stderr)] fn ensure_keychain_items( @@ -286,8 +282,8 @@ fn ensure_keychain_items( ) -> Result<(), String> { let mut missing: Vec<&str> = Vec::new(); for var in wanted { - // Existence check via the Security.framework API (F1) — no - // subprocess; retrieved bytes zeroized on drop (A17). + // Existence check via the Security.framework API — no subprocess; retrieved + // bytes zeroized on drop. match security_framework::passwords::get_generic_password(service, var) { Ok(bytes) => { let _ = zeroize::Zeroizing::new(bytes); // zeroize on drop @@ -296,8 +292,8 @@ fn ensure_keychain_items( } } - // --force re-seeds every wanted item, present or not; without it - // only the missing ones are offered (sweep 2026-08-07 K7). + // --force re-seeds every wanted item, present or not; without it only the missing + // ones are offered. let to_seed: Vec<&str> = if force { wanted.iter().map(String::as_str).collect() } else { @@ -339,9 +335,8 @@ fn ensure_keychain_items( return Err(format!("{var}: empty value, refusing to seed")); } // Seed via the Security.framework API, not the security CLI: - // `add-generic-password -w ` exposes key material in - // the subprocess argv, readable by any local process via ps / - // proc_pidinfo (audit 2026-08-02 O3; F1 crate direction). + // `add-generic-password -w ` exposes key material in the subprocess + // argv, readable by any local process via ps / proc_pidinfo. security_framework::passwords::set_generic_password(service, var, value.as_bytes()) .map_err(|e| format!("keychain {service}: failed to seed {var}: {e}"))?; log(&format!("keychain {service}: seeded {var}")); @@ -350,8 +345,9 @@ fn ensure_keychain_items( Ok(()) } -/// Verify that all configured key sources are accessible. This is the -/// `--recheck` path — same as the old `setup_recheck` function. +/// Check configured key-source prerequisites without decrypting values. +/// File sources get descriptor-based access checks; credentials get presence +/// and type checks. Keychain and environment sources check required names. fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> { // `wanted` is only consulted by the macOS keychain check below. #[cfg(not(target_os = "macos"))] @@ -365,10 +361,9 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> let dir = std::env::var_os("CREDENTIALS_DIRECTORY") .ok_or("$CREDENTIALS_DIRECTORY is not set")?; let p = Path::new(&dir).join(name); - // Mirror load_ring's discipline (sweep 2026-08-07 K4): - // verification must not pass what resolution rejects — - // exists() follows symlinks, but the loader refuses a - // symlinked credential outright. + // Mirror load_ring's discipline: verification must not pass what + // resolution rejects — exists() follows symlinks, but the loader + // refuses a symlinked credential outright. match fs::symlink_metadata(&p) { Ok(md) if md.file_type().is_symlink() => { return Err(format!( @@ -405,10 +400,9 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> path.display() )); } - // NONBLOCK is inert on regular files and prevents a FIFO - // from hanging verification at open; the file-type check - // then rejects anything that isn't a regular file (sweep - // 2026-08-07 K5). + // NONBLOCK is inert on regular files and prevents a FIFO from hanging + // verification at open; the file-type check then rejects anything that + // isn't a regular file. let oflags = rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC @@ -449,8 +443,8 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> { checked += 1; for var in wanted { - // Security.framework API (F1) — no subprocess; - // retrieved bytes zeroized on drop (A17). + // Security.framework API — no subprocess; retrieved bytes + // zeroized on drop. match security_framework::passwords::get_generic_password(service, var) { Ok(bytes) => { let _ = zeroize::Zeroizing::new(bytes); // zeroize on drop @@ -471,21 +465,13 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> } KeySourceSpec::Environment => { checked += 1; - // Every naming the config's artifacts require must be - // present: accepting ANY single prefix let `POSTMASTER_KEY` - // satisfy verification for an env-files-only config (setup - // said OK, exec then failed) — and vice versa. - // - // The SAME predicate KeyRing::from_env applies (audit - // 2026-08-02 A16): a bare starts_with would count a - // prefix-substring collision like DOTENV_PRIVATE_KEYFOO - // as key material that from_env then refuses to load — - // verification must not pass what resolution rejects. + // Require each adapter namespace with the same exact-prefix predicate + // as KeyRing::from_env; unrelated keys must not satisfy setup checks. for naming in cfg.required_namings() { let prefix = naming.key_prefix(); - // vars_os: std::env::vars() panics during iteration on - // non-Unicode entries — an abort under panic=abort, not - // a clean verification failure (sweep 2026-08-07 K3). + // vars_os: std::env::vars() panics during iteration on non-Unicode + // entries — an abort under panic=abort, not a clean verification + // failure. if !std::env::vars_os().any(|(k, _)| { k.to_str() .is_some_and(|k| crate::keys::is_key_var_name(prefix, k)) @@ -501,9 +487,8 @@ fn verify_key_sources(cfg: &ExecConfig, wanted: &[String]) -> Result<(), String> return Err("no key sources configured (configure keys=[…])".into()); } - // Every per-source failure above early-returns, so reaching the log - // means checked == verified — report the count, not a fraction that - // is always N/N (sweep 2026-08-07 K12). + // Every per-source failure above early-returns, so reaching the log means checked + // == verified — report the count, not a fraction that is always N/N. log(&format!( "setup: {checked} key source(s) verified — environment ready" )); @@ -524,10 +509,9 @@ mod tests { #[test] fn verify_key_sources_uses_from_env_predicate() { - // audit 2026-08-02 A16: verification must admit exactly what - // KeyRing::from_env admits. A prefix-substring collision like - // DOTENV_PRIVATE_KEYFOO is NOT a key var, so with only such a - // var set, verification must fail. + // Verification must admit exactly what KeyRing::from_env admits. A + // prefix-substring collision like DOTENV_PRIVATE_KEYFOO is NOT a key var, so + // with only such a var set, verification must fail. let _guard = ENV_LOCK.lock().unwrap(); let cfg = env_only_cfg(); let bogus = "DOTENV_PRIVATE_KEYFOO_PMVERIFY"; @@ -572,8 +556,7 @@ mod tests { #[test] fn verify_key_sources_credential_rejects_symlink() { - // sweep 2026-08-07 K4: verification must not pass what resolution - // rejects — exists() followed symlinks; the loader refuses them. + // Rechecks must reject symlinks just as runtime loading does. use std::os::unix::fs::PermissionsExt; let d = crate::test_util::temp_dir::TestDir::new("mod"); let cred_dir = d.join("creds"); @@ -606,9 +589,8 @@ mod tests { #[test] fn ensure_keys_file_force_unattended_fails_closed() { - // sweep 2026-08-07 K7: --force re-prompts for contents, which - // unattended mode cannot do — fail closed rather than silently - // skipping the re-create the operator asked for. + // --force re-prompts for contents, which unattended mode cannot do — fail + // closed rather than silently skipping the re-create the operator asked for. use std::os::unix::fs::PermissionsExt; let d = crate::test_util::temp_dir::TestDir::new("mod"); let keys = d.join(".env.keys"); @@ -710,12 +692,10 @@ mod tests { #[test] fn ensure_keys_dir_creates_0700_and_corrects_wide_modes() { - // sweep 2026-08-07 T7: the provisioning primitives had no direct - // coverage — create sets exactly 0700, and a pre-existing 0755 - // dir is corrected in place. + // Creation and repair must both leave the directory at 0700. use std::os::unix::fs::PermissionsExt; // Canonicalize the temp base: on macOS it sits under /var → - // /private/var, and the O5 prefix walk would (correctly) refuse + // /private/var, and the directory-prefix walk would refuse // the symlinked /var component for reasons unrelated to this test. let d = crate::test_util::temp_dir::TestDir::new("mod"); @@ -736,11 +716,9 @@ mod tests { #[test] fn ensure_keys_dir_refuses_a_symlinked_prefix() { - // sweep 2026-08-07 T7 (audit 2026-08-02 O5): create_dir_all - // follows intermediate symlinks, so the prefix walk must refuse - // them before anything is created. - // Canonicalize the temp base (macOS /var → /private/var) so the - // walk reaches OUR planted symlink instead of refusing the + // create_dir_all follows intermediate symlinks, so the prefix walk must refuse + // them before anything is created. Canonicalize the temp base (macOS /var → + // /private/var) so the walk reaches OUR planted symlink instead of refusing the // OS-provided /var component first. let d = crate::test_util::temp_dir::TestDir::new("mod"); let real = d.join("real"); @@ -760,8 +738,8 @@ mod tests { #[test] fn ensure_keys_file_corrects_mode_and_missing_unattended_fails() { - // sweep 2026-08-07 T7: a 0644 keys file is corrected to 0600; a - // missing file in unattended mode fails closed (no prompt). + // A 0644 keys file is corrected to 0600; a missing file in unattended mode + // fails closed (no prompt). use std::os::unix::fs::PermissionsExt; let d = crate::test_util::temp_dir::TestDir::new("mod"); let keys = d.join(".env.keys"); diff --git a/src/keys/source.rs b/src/keys/source.rs index 4baf2f4..5afe618 100644 --- a/src/keys/source.rs +++ b/src/keys/source.rs @@ -18,8 +18,7 @@ use crate::keys::KeyRing; /// /// `namings` is the adapter set the config's artifacts require /// (`ExecConfig::required_namings`): the ring admits exactly those key -/// prefixes. Hardcoding a single naming here previously dropped -/// `POSTMASTER_KEY*` at parse time and broke bundle configs end-to-end. +/// prefixes, including both namespaces for mixed dotenv and bundle inputs. // `wanted_vars` is only consumed by the macOS keychain source; on other // targets the parameter is unused, so silence that leg's clippy warning // without touching the signature or source-selection semantics. @@ -34,13 +33,11 @@ pub fn load_ring( KeySourceSpec::Credential(name) => { if let Some(dir) = std::env::var_os("CREDENTIALS_DIRECTORY") { let p = Path::new(&dir).join(name); - // Use symlink_metadata instead of p.exists(): exists() - // follows symlinks, so a planted symlink at - // $CREDENTIALS_DIRECTORY/ pointing to a - // world-readable file would be silently followed. - // Reject symlinks outright (audit finding #2); the - // subsequent KeyRing::load also opens with O_NOFOLLOW - // as defense-in-depth. + // Use symlink_metadata instead of p.exists(): exists() follows + // symlinks, so a planted symlink at $CREDENTIALS_DIRECTORY/ + // pointing to a world-readable file would be silently followed. + // Reject symlinks outright; the subsequent KeyRing::load also opens + // with O_NOFOLLOW as defense-in-depth. match fs::symlink_metadata(&p) { Ok(md) if md.file_type().is_symlink() => { return Err(format!( @@ -58,10 +55,9 @@ pub fn load_ring( Err(e) if e.kind() == std::io::ErrorKind::NotFound => { // absent: fall through to next source } - // A permission-denied or malformed credential dir is - // NOT "absent" — it is misconfigured. Fail loudly - // rather than silently selecting a source the - // operator didn't expect (sweep 2026-08-07 K8). + // A permission-denied or malformed credential dir is NOT + // "absent" — it is misconfigured. Fail loudly rather than + // silently selecting a source the operator didn't expect. Err(e) => { return Err(format!( "{}: cannot stat credential source: {e}", @@ -117,11 +113,10 @@ mod tests { unsafe { std::env::remove_var("CREDENTIALS_DIRECTORY"); } - // Guard against an ambient valid key var in the test runner's own - // environment (e.g. DOTENV_PRIVATE_KEY exported in CI): with one - // present, the environment source SUCCEEDS and the terminal error - // is unobservable — skip rather than flake (sweep 2026-08-07 T16). - // Only the Env prefix counts here: these namings require Env alone. + // Guard against an ambient valid key var in the test runner's own environment + // (e.g. DOTENV_PRIVATE_KEY exported in CI): with one present, the environment + // source SUCCEEDS and the terminal error is unobservable — skip rather than + // flake. Only the Env prefix counts here: these namings require Env alone. let ambient = std::env::vars_os().any(|(k, _)| { k.to_str() .is_some_and(|k| crate::keys::is_key_var_name(KeyNaming::Env.key_prefix(), k)) @@ -144,8 +139,8 @@ mod tests { #[test] fn load_ring_credential_rejects_symlink() { - // Audit finding #2: a symlink planted at - // $CREDENTIALS_DIRECTORY/ must be rejected, not followed. + // A symlink planted at $CREDENTIALS_DIRECTORY/ must be rejected, not + // followed. use std::os::unix::fs::PermissionsExt; let d = crate::test_util::temp_dir::TestDir::new("source"); let real = d.join("real-keys"); @@ -176,9 +171,8 @@ mod tests { #[test] fn load_ring_credential_stat_error_is_terminal() { - // sweep 2026-08-07 K8: a permission-denied credential dir is - // misconfigured, not "absent" — it must hard-error rather than - // fall through to the next source. + // A permission-denied credential dir is misconfigured, not "absent" — it must + // hard-error rather than fall through to the next source. use std::os::unix::fs::PermissionsExt; if rustix::process::geteuid().is_root() { // chmod 000 does not exclude root; the EACCES leg is @@ -366,9 +360,8 @@ mod tests { #[test] fn load_ring_credential_loads_present_file() { - // sweep 2026-08-07 T9: the positive credential leg — a present, - // well-formed credential file loads through the same selection - // path the negative legs reject. + // The positive credential leg — a present, well-formed credential file loads + // through the same selection path the negative legs reject. use std::os::unix::fs::PermissionsExt; let d = crate::test_util::temp_dir::TestDir::new("source"); let cred_dir = d.join("creds"); diff --git a/src/keys/verify.rs b/src/keys/verify.rs index e85163c..91cb096 100644 --- a/src/keys/verify.rs +++ b/src/keys/verify.rs @@ -3,27 +3,19 @@ use std::path::Path; -/// Verify the integrity of an external binary before invoking it as part -/// of a secret-handling path. This is a defense-in-depth trust boundary -/// check: the binary path is a trust root, and we -/// verify it has not been tampered with before exec. +/// Check platform trust requirements before invoking an external helper. /// -/// On macOS: `codesign -v ` verifies the code signature. The binary -/// is additionally SIP-protected, so this catches a hypothetical SIP -/// bypass or a misconfigured environment. +/// On macOS, `codesign -v ` checks the code signature. Callers use +/// fixed system paths protected by SIP. /// /// On Linux: verify the file is a regular file, owned by root (uid 0), -/// and not group/other writable. There is no universal code-signing mechanism -/// on Linux, so ownership and permission checks are the practical -/// defense-in-depth boundary. +/// and not writable by group or others. These are ownership and permission +/// checks, not a content-signature check. /// /// Bootstrap limitation: on macOS the verifier /// itself invokes `/usr/bin/codesign`. Self-verifying codesign with /// codesign is circular — a compromised codesign would vouch for -/// itself — so codesign is trusted via SIP alone. Moving verification -/// onto the Security.framework StaticCode API (the `security-framework` -/// crate route already chosen for keychain access) would remove this -/// residual trust gap. +/// itself. The verifier trusts the system's SIP protection for that tool. pub fn verify_external_binary(path: &Path) -> Result<(), String> { #[cfg(target_os = "macos")] { diff --git a/src/launcher.rs b/src/launcher.rs index 149bc99..406235d 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -34,12 +34,10 @@ use crate::server::{fetch_bytes, log, read_capped}; /// the saved mask before execvp so the service starts with a clean /// signal state. /// -/// The sigaction flag-handler and second pre-exec gate this guard used -/// to implement were retired with the sibling-monitor design: the -/// monitor owns stop semantics, so no async handler is -/// needed anywhere. What remains is the deterministic write window -/// (`block`) and the pre-exec mask restore (`restore_mask`) — now real -/// on Linux too, because the fork+monitor model runs there as well. +/// The monitor consumes stop signals synchronously. This guard protects +/// the write window with `block` and restores the captured mask through +/// `restore_mask` on Linux and macOS. A block failure is logged and leaves +/// that window unguarded; terminal-input callers refuse to proceed. #[cfg(target_os = "macos")] pub(crate) struct TerminationGuard { /// `None` only if the block call failed (logged); restore then no-ops @@ -208,8 +206,8 @@ pub fn parse_exec_config(config_path: &Path) -> Result { } /// Validate the public shape of an exec config without decrypting, -/// reading key material, or touching the host filesystem. This is -/// the `--check` contract for CI and automation tools. +/// reading key material, or inspecting deployment resources. Only the +/// configuration file is read. This is the `--check` contract for CI. pub fn check_config(config_path: &Path) -> Result<(), String> { let cfg = parse_exec_config(config_path)?; cfg.validate_shape() @@ -217,11 +215,8 @@ pub fn check_config(config_path: &Path) -> Result<(), String> { /// Preflight key freshness check: fail if any encrypted env value was /// skipped during resolution because the key ring could not decrypt it. -/// Under `strict: false` a partial key rotation -/// would otherwise pass silently here — the old check only caught total -/// failure (empty resolved set) — and the child would launch with a -/// partial secret set. The failure list recorded by `resolve_all` makes -/// every skip visible to `--verify-keys`. +/// Under `strict: false`, the failure list recorded by `resolve_all` makes +/// every skipped value visible to `--verify-keys`, including partial rotation. /// /// Bundle files need no scan here: `resolve_bundle` is all-or-nothing — /// the first undecryptable entry aborts `decrypt()` regardless of @@ -274,9 +269,9 @@ fn decrypt(cfg: &ExecConfig) -> Result<(Resolved, Vec<(String, String)>), String } let ring = load_ring(&cfg.keys, &wanted, &cfg.required_namings())?; - // Resolve .env files (if any) via the env adapter. Values skipped - // under strict:false are recorded in `failed` so --verify-keys can - // fail closed on a partial key rotation (audit 2026-08-02 A3). + // Resolve .env files (if any) via the env adapter. Values skipped under strict:false + // are recorded in `failed` so --verify-keys can fail closed on a partial key + // rotation. let (mut resolved, failed): (Resolved, Vec<(String, String)>) = if cfg.env_files.is_empty() { (Vec::new(), Vec::new()) } else { @@ -298,8 +293,7 @@ fn decrypt(cfg: &ExecConfig) -> Result<(Resolved, Vec<(String, String)>), String .collect(); // Bundle files follow env files and use the same first/last-wins contract. for bundle_path in &cfg.bundle_files { - // O_NOFOLLOW on the ciphertext open (audit 2026-08-02 A13): - // refuse to read through a planted symlink. + // O_NOFOLLOW on the ciphertext open: refuse to read through a planted symlink. let bundle_fd = rustix::fs::open( bundle_path, rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC, @@ -319,9 +313,8 @@ fn decrypt(cfg: &ExecConfig) -> Result<(Resolved, Vec<(String, String)>), String if !cfg.overload && std::env::var_os(&name).is_some() { continue; } - // NUL check for utf8 entries that would become env vars. - // One rule for every env-bound value (sweep 2026-08-07 X6): - // NUL is a hard error, identical to the .env path in + // NUL check for utf8 entries that would become env vars. One rule for every + // env-bound value: NUL is a hard error, identical to the .env path in // env_pairs — no strict-gated skip. if matches!(cfg.mode, ExecMode::Env) && encoding == crate::bundle::Encoding::Utf8 @@ -353,24 +346,22 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() cfg.validate_shape()?; let program = argv.first().ok_or("exec: empty argv")?; - // Defer termination signals until the fork/exec below, so a signal - // landing mid-write can't strand plaintext on disk (audit 2026-08-02 - // A11 — see TerminationGuard docs). The fork-child monitor inherits - // the blocked mask and keeps it for life; the parent restores the - // saved mask before execvp. + // Defer termination signals until the fork/exec below, so a signal landing + // mid-write can't strand plaintext on disk (see TerminationGuard docs). The + // fork-child monitor inherits the blocked mask and keeps it for life; the parent + // restores the saved mask before execvp. let sig_guard = TerminationGuard::block(); let mut extra: Vec<(OsString, OsString)> = Vec::new(); - // Names of plaintext files written beneath the pinned secrets-dir - // fd, tracked across the match so the failure paths (and the monitor, - // post-fork) can unlink them fd-relative (audit 2026-08-02 A9). + // Names of plaintext files written beneath the pinned secrets-dir fd, tracked + // across the match so the failure paths (and the monitor, post-fork) can unlink + // them fd-relative. let mut written: Vec = Vec::new(); - // The pinned secrets-dir fd (Files / Credentials-fetch modes only). - // Opened ONCE with O_DIRECTORY|O_NOFOLLOW|O_RDONLY|CLOEXEC and kept - // until after the exec-failure cleanup, so every write and every - // cleanup unlink is relative to the same pinned inode (audit - // 2026-08-02 A12). Across the fork the monitor inherits the fd - // (CLOEXEC fires only on exec, which the monitor never performs) and - // holds it for the service's lifetime. + // The pinned secrets-dir fd (Files / Credentials-fetch modes only). Opened ONCE + // with O_DIRECTORY|O_NOFOLLOW|O_RDONLY|CLOEXEC and kept until after the + // exec-failure cleanup, so every write and every cleanup unlink is relative to the + // same pinned inode. Across the fork the monitor inherits the fd (CLOEXEC fires + // only on exec, which the monitor never performs) and holds it for the service's + // lifetime. let mut secrets_dir_fd: Option = None; match cfg.mode { @@ -426,9 +417,8 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() } } // resolved (Zeroizing> values) dropped here — - // decrypted values zeroized before execvp. Only file paths - // (extra: OsString pairs) survive to execvp, not the - // plaintext values themselves. + // decrypted values zeroized before execvp. File pointers and + // any passthrough plaintext remain in extra for the child. drop(resolved); secrets_dir_fd = Some(dir_fd); } @@ -449,7 +439,7 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() )); } } else { - // launchd path: pull each key from postmaster ourselves. + // Local socket path, normally used with launchd. let dir = cfg .secrets_dir .as_deref() @@ -501,8 +491,7 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() // the sibling monitor BEFORE exec. The fork-child keeps the guard's // blocked mask for life and supervises this process — stop-signal // forwarding, bounded grace, SIGKILL escalation, and plaintext cleanup - // on every death path (sibling-monitor design 2026-08-05; see - // monitor.rs). The parent execs the service exactly as before, so + // on every service-death path (see monitor.rs). The parent execs the service, so // MainPID is unchanged. The monitor runs for ALL exec launches, // including env mode (uniform semantics; its cleanup is a no-op // there). The pid is captured pre-fork: post-fork the parent IS the @@ -554,7 +543,7 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() } // Parent only from here (the fork-child diverged). Restore the // pre-guard signal mask so the service starts with a clean signal - // state, then exec exactly as before. + // state, then exec the service. sig_guard.restore_mask(); let mut cmd = std::process::Command::new(program); cmd.args(&argv[1..]).envs(extra); @@ -568,12 +557,11 @@ pub fn exec(config_path: &Path, argv: &[String], verify_keys: bool) -> Result<() cmd.env_remove(name); } let err = cmd.exec(); // only returns on failure - // execvp failed: the process image was NOT replaced, so any - // plaintext secret files written above would otherwise persist - // (the macOS ramdisk survives process death). Remove them before - // returning the error (audit 2026-08-02 A9). The monitor watching - // this process fires on the imminent exit and cleans again — - // unlinkat of already-removed names is a no-op. + // execvp failed: the process image was NOT replaced, so any plaintext secret files + // written above would otherwise persist (the macOS ramdisk survives process death). + // Remove them before returning the error. The monitor watching this process fires + // on the imminent exit and cleans again — unlinkat of already-removed names is a + // no-op. if let Some(dir_fd) = &secrets_dir_fd { cleanup_written(dir_fd, &written); } @@ -615,7 +603,7 @@ mod tests { format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32)), ) .unwrap(); - // KeyRing::load enforces 0600-or-stricter (audit finding #1). + // KeyRing::load enforces 0600-or-stricter. fs::set_permissions(&keys_path, fs::Permissions::from_mode(0o600)).unwrap(); let env_path = d.join(".env"); fs::write(&env_path, "A=hello\n").unwrap(); diff --git a/src/lib.rs b/src/lib.rs index 4678158..94b4b76 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,10 +1,7 @@ -//! postmaster library. +//! CLI dispatch and secret handling for Postmaster. //! -//! The bulk of the logic lives in the submodules so that unit tests can -//! exercise key loading, resolution, argument parsing, and serving logic -//! without going through main(). -//! -//! Security and fail-closed semantics are preserved exactly. +//! Submodules expose key loading, resolution, argument parsing, and serving +//! logic to tests without launching the binary entry point. // `multiple_crate_versions` is warn-level in Cargo.toml; allowed here for // exactly one uncontrollable case: syn 2 + syn 3 coexist only because @@ -28,24 +25,22 @@ pub mod server; #[cfg(test)] pub(crate) mod test_util; -/// The bundle adapter, re-exported so `crate::bundle` keeps resolving. +/// Public alias for the bundle adapter. pub use adapter::bundle; -/// The CLI module under its former name, so `crate::config` keeps resolving. +/// Public alias for CLI parsing and daemon configuration. pub use cli as config; pub use cli::{Invocation, parse_args, parse_args_from}; pub use keys::provisioning::{cleanup, setup}; -/// Key-source selection under its former name, so `crate::key_source` -/// keeps resolving. +/// Public alias for ordered key-source selection. pub use keys::source as key_source; pub use server::{fetch, harden_process, run}; -/// Re-exported for binary use. The real main is here so tests can call into it. +/// Dispatch a parsed invocation from the binary or tests. pub fn main() -> std::process::ExitCode { - // Harden only the arms that can touch secret material (sweep - // 2026-08-07 D17): --help/--version and --check must not print - // hardening noise (e.g. an mlockall failure) for invocations that - // never decrypt. Serve/Exec/Fetch/Setup/Cleanup stay hardened BEFORE - // any decryption and before execvp, exactly as before. + // Harden only the arms that can touch secret material: --help/--version and --check + // must not print hardening noise (e.g. an mlockall failure) for invocations that + // never decrypt. Serve/Exec/Fetch/Setup/Cleanup stay hardened BEFORE any decryption + // and before execvp. let result = match parse_args() { Ok(Invocation::Serve(args)) => { harden_process(); diff --git a/src/main.rs b/src/main.rs index 54a89ee..4db66eb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,7 @@ //! Thin binary entry point. //! -//! Real logic (and all security properties) live in the library crate so -//! they can be unit-tested. See `lib.rs` and the submodule docs for the -//! full security posture, fail-closed design, and invariants. +//! The library crate owns CLI dispatch and secret handling so tests can call +//! those paths directly. See `lib.rs` and the submodule contracts. // See src/lib.rs for why this allow exists (wasm-bindgen's wasm32-gated // syn 2 vs serde_derive's syn 3; uncontrollable, deny.toml keeps watch). diff --git a/src/monitor.rs b/src/monitor.rs index 40cafe4..d1d2c99 100644 --- a/src/monitor.rs +++ b/src/monitor.rs @@ -19,7 +19,7 @@ //! inherited from the launcher's `TerminationGuard` across fork and //! re-asserted at monitor start — and are consumed synchronously via the //! `sigpending`/`sigwait` family. No signal handlers exist anywhere in -//! the process (the sigaction flag-handler was retired with this design). +//! the process. //! SIGPIPE is additionally blocked so a stderr write to a closed pipe //! cannot kill the monitor mid-supervision. //! @@ -33,7 +33,7 @@ //! 2. Otherwise, if the service is dead (liveness watch: pidfd + `poll` //! on Linux, kqueue `EVFILT_PROC`/`NOTE_EXIT` on macOS, `kill(pid, 0)` //! only as fallback) → `cleanup_written` → exit. This covers natural -//! exit, `kill -9`, and crashes — the net-new cleanup coverage. +//! exit, `kill -9`, and crashes. //! 3. Otherwise, sleep one tick. Liveness/stop latency adds to cleanup //! latency, never to the grace cap. //! @@ -498,8 +498,6 @@ fn take_pending_stop(set: &libc::sigset_t) -> Option { #[cfg(not(any(target_os = "linux", target_os = "macos")))] compile_error!("postmaster's sibling monitor supports Linux and macOS only"); -// Tests live in monitor/tests.rs (sweep 2026-08-07 X8): the -// production half stays readable at ~500 lines; the test half keeps -// the same module path (monitor::tests) and crate-internal access. +// Keep monitor tests in a child module with access to the private implementation. #[cfg(test)] mod tests; diff --git a/src/monitor/tests.rs b/src/monitor/tests.rs index f27d073..6688a24 100644 --- a/src/monitor/tests.rs +++ b/src/monitor/tests.rs @@ -1,6 +1,4 @@ -//! Tests for the sibling monitor, extracted from monitor.rs. Same -//! module path (`monitor::tests`), same crate-internal visibility — -//! nothing here changed but location. +//! Sibling-monitor lifecycle, signal forwarding, cleanup, and heap-wiping tests. #![allow(clippy::unwrap_used, clippy::panic)] use super::*; diff --git a/src/ramdisk.rs b/src/ramdisk.rs index f589c6d..8c0e480 100644 --- a/src/ramdisk.rs +++ b/src/ramdisk.rs @@ -101,10 +101,9 @@ pub(crate) fn open_verified_ramdisk_dir( mount_point: &Path, secrets_dir: &Path, ) -> Result { - // Trust boundary (audit 2026-08-02 O2): a compromised /sbin/mount or - // hdiutil could report persistent disk as the RAM-backed postmaster - // ramdisk and let plaintext land on persistent storage. Verify both - // helpers before invoking. + // Trust boundary: a compromised /sbin/mount or hdiutil could report persistent disk + // as the RAM-backed postmaster ramdisk and let plaintext land on persistent + // storage. Verify both helpers before invoking. crate::keys::verify_external_binary(Path::new("/sbin/mount"))?; crate::keys::verify_external_binary(Path::new("/usr/bin/hdiutil"))?; let out = std::process::Command::new("/sbin/mount") @@ -287,8 +286,8 @@ image-type : read/write #[test] fn path_beneath_enforces_containment() { - // sweep 2026-08-07 X1: the guard must relate secrets_dir to the - // verified mount, not check each independently. + // The guard must relate secrets_dir to the verified mount, not check each + // independently. let mp = Path::new("/private/var/run/postmaster"); assert!(path_beneath( Path::new("/private/var/run/postmaster/myapp"), diff --git a/src/secret_files.rs b/src/secret_files.rs index 4f4eb2c..aff0cc1 100644 --- a/src/secret_files.rs +++ b/src/secret_files.rs @@ -1,9 +1,8 @@ //! Secret file operations — writing, cleanup, and pruning of plaintext //! secret files on RAM-backed filesystems. //! -//! All file operations use `O_NOFOLLOW` and fd-based permissions to -//! eliminate TOCTOU race conditions against symlink attacks. The secrets -//! directory is pinned once by an open fd (`O_DIRECTORY|O_NOFOLLOW`) and +//! The secrets directory is pinned by an open fd (`O_DIRECTORY|O_NOFOLLOW`), +//! and permissions are checked on opened inodes. Subsequent //! output creation, entry checks, and cleanup are relative to that pinned inode. //! Exported-path validation separately checks lexical and resolved ancestry. @@ -290,10 +289,10 @@ pub fn cleanup_written(dir_fd: impl AsFd, names: &[String]) { /// plaintext is transient — is best served by cleaning what we can rather /// than aborting the launch over an unrelated stale file. pub fn prune_stale(dir: &Path, keep_keys: &[String]) -> Result<(), String> { - // Pin the directory by fd: O_DIRECTORY|O_NOFOLLOW rejects a symlinked - // or non-directory secrets dir at open, and the sentinel check, the - // per-entry stat, and every unlink below are all relative to the - // pinned inode — no path is ever re-resolved (audit 2026-08-02 A12). + // Pin the directory by fd: O_DIRECTORY|O_NOFOLLOW rejects a symlinked or + // non-directory secrets dir at open, and the sentinel check, the per-entry stat, + // and every unlink below are all relative to the pinned inode — no path is ever + // re-resolved. let dir_fd = match open_secrets_dir(dir) { Ok(fd) => fd, // If the directory does not exist yet, there is nothing to prune. @@ -322,9 +321,8 @@ pub(crate) fn prune_stale_at( if names.is_empty() { return Ok(()); } - // Managed-dir guard (audit 2026-08-02 A19): non-empty and no - // sentinel means postmaster never wrote here — bulk deletes could - // hit foreign files. Refuse. + // Managed-dir guard: non-empty and no sentinel means postmaster never wrote here — + // bulk deletes could hit foreign files. Refuse. match rustix::fs::statat( dir_fd, MANAGED_SENTINEL, @@ -340,8 +338,8 @@ pub(crate) fn prune_stale_at( } for name in &names { let Some(name_str) = name.to_str() else { - // Every other skip in this loop logs; a foreign file with a - // non-UTF8 name must not persist silently (sweep 2026-08-07 X7). + // Every other skip in this loop logs; a foreign file with a non-UTF8 name + // must not persist silently. crate::server::log(&format!( "{}: prune: skipping non-UTF8 entry name", dir.display() @@ -385,8 +383,8 @@ mod tests { fn tdir(tag: &str) -> crate::test_util::temp_dir::TestDir { let d = crate::test_util::temp_dir::TestDir::new(tag); - // prune_stale requires a postmaster-managed (owner-only) dir - // (audit 2026-08-02 A19); match real deployments. + // prune_stale requires a postmaster-managed (owner-only) dir; match real + // deployments. use std::os::unix::fs::PermissionsExt; fs::set_permissions(&d, fs::Permissions::from_mode(0o700)).unwrap(); d @@ -567,7 +565,7 @@ mod tests { fn prune_stale_removes_unconfigured_files() { let dir = tdir("prune"); // Simulate a previous launch that wrote KEY_A and KEY_B (the - // sentinel marks the dir as postmaster-managed — A19). + // sentinel marks the directory as managed). fs::write(dir.join("KEY_A"), b"old-a").unwrap(); fs::write(dir.join("KEY_B"), b"old-b").unwrap(); fs::write(dir.join(MANAGED_SENTINEL), b"").unwrap(); @@ -585,9 +583,8 @@ mod tests { #[test] fn prune_stale_refuses_unmanaged_dir() { - // audit 2026-08-02 A19: a non-empty dir without the sentinel was - // never written by postmaster; bulk deletes could hit foreign - // files. + // A non-empty dir without the sentinel was never written by postmaster; bulk + // deletes could hit foreign files. let dir = tdir("prune-unmanaged"); fs::write(dir.join("FOREIGN"), b"not-ours").unwrap(); diff --git a/src/server.rs b/src/server.rs index 8e57ef0..50b1d0a 100644 --- a/src/server.rs +++ b/src/server.rs @@ -65,10 +65,9 @@ pub fn serve( continue; } }; - // Peer ACL (sweep 2026-08-07 D1): a configured peer_user is - // ALWAYS enforced — --allow-nonroot widens root→configured-user, - // never root→anyone. The flag skips verification only when no - // peer_user is configured (the dev loop it exists for). + // Peer ACL: a configured peer_user is ALWAYS enforced — --allow-nonroot widens + // root→configured-user, never root→anyone. The flag skips verification only + // when no peer_user is configured (the dev loop it exists for). if !allow_nonroot || peer_uid.is_some() { match peer_euid(&stream) { Ok(0) => {} @@ -105,8 +104,7 @@ pub fn serve( /// Maximum bytes accepted for a credential fetch payload, bundle JSON, or config /// read. These payloads are small; the cap keeps a hostile or broken -/// peer (or a swapped-in special file) from forcing unbounded heap -/// allocation. 16 MiB is far above any legitimate payload. +/// peer from forcing unbounded heap allocation. Oversized payloads fail. const MAX_READ_BYTES: u64 = 16 * 1024 * 1024; /// Read `reader` to EOF with a hard size cap. @@ -145,8 +143,8 @@ pub fn fetch_bytes(path: &Path) -> Result>, String> { Ok(buf) } -/// Client half for platforms without LoadCredential (darwin wrappers): -/// connect, read one credential to EOF, emit on stdout. Zero bytes means +/// Connect to a local credential socket, read to EOF, and write to stdout. +/// Available on Linux and macOS. Zero bytes means /// the server refused to serve — fail closed, exactly like LoadCredential /// failing the unit. pub fn fetch(path: &Path) -> Result<(), String> { @@ -201,9 +199,8 @@ fn peer_euid(stream: &UnixStream) -> std::io::Result { /// Failures are logged. Dumpability and memory locks reset across exec. #[cfg(target_os = "linux")] pub fn harden_process() { - // No core dumps, no ptrace from non-privileged peers. Best-effort by - // policy, but a failure is security-relevant — log it (audit - // 2026-08-02 A10). + // No core dumps, no ptrace from non-privileged peers. Best-effort by policy, but a + // failure is security-relevant — log it. if let Err(e) = rustix::process::set_dumpable_behavior(rustix::process::DumpableBehavior::NotDumpable) { @@ -227,9 +224,8 @@ pub fn harden_process() { /// Failures are logged. #[cfg(target_os = "macos")] pub fn harden_process() { - // Closest analog to PR_SET_DUMPABLE for dumps: no core files, ever. - // Best-effort by policy, but failures are security-relevant — log - // them (audit 2026-08-02 A10). + // Closest analog to PR_SET_DUMPABLE for dumps: no core files, ever. Best-effort by + // policy, but failures are security-relevant — log them. if let Err(e) = rustix::process::setrlimit( rustix::process::Resource::Core, rustix::process::Rlimit { @@ -260,14 +256,12 @@ pub fn harden_process() { /// Resolve a user name to a uid without getpwnam FFI. pub fn uid_of(name: &str) -> Result { - // Trust boundary (audit 2026-08-02 O2): a compromised `id` returning - // a wrong uid would defeat the socket peer-uid ACL. macOS invokes - // /usr/bin/id by absolute path under SIP, verified via codesign. - // Linux never uses PATH resolution — a PATH-resolved `id` would - // inherit a potentially attacker-controlled PATH; instead the first - // candidate absolute path that verifies (regular file, root-owned, - // no group/other write bits — checked by fstat on an - // O_NOFOLLOW|CLOEXEC fd) is invoked, and if none verifies the lookup + // Trust boundary: a compromised `id` returning a wrong uid would defeat the socket + // peer-uid ACL. macOS invokes /usr/bin/id by absolute path under SIP, verified via + // codesign. Linux never uses PATH resolution — a PATH-resolved `id` would inherit a + // potentially attacker-controlled PATH; instead the first candidate absolute path + // that verifies (regular file, root-owned, no group/other write bits — checked by + // fstat on an O_NOFOLLOW|CLOEXEC fd) is invoked, and if none verifies the lookup // fails closed. #[cfg(target_os = "macos")] let id = { @@ -348,11 +342,10 @@ fn verify_id_candidate(path: &str) -> Result { pub fn keys_path(source: &KeysSource) -> Result { match source { KeysSource::Credential(name) => { - // Same discipline as the exec-config credential source - // (audit 2026-08-02 A8): the name must be a single relative - // path component — otherwise "../../…" would escape - // $CREDENTIALS_DIRECTORY and read an arbitrary root-readable - // file as key material. + // Same discipline as the exec-config credential source: the name must be a + // single relative path component — otherwise "../../…" would escape + // $CREDENTIALS_DIRECTORY and read an arbitrary root-readable file as key + // material. crate::exec_config::validate_credential_source_name(name)?; let dir = std::env::var_os("CREDENTIALS_DIRECTORY").ok_or( "keys.credential configured but $CREDENTIALS_DIRECTORY is unset \ @@ -472,11 +465,10 @@ pub fn acquire_listeners( for path in cfg.credentials.keys() { let expected = peer_uids.get(path).copied().flatten(); if let Some(parent) = path.parent() { - // Refuse a symlinked socket parent unconditionally in - // bind mode (sweep 2026-08-07 D2): create_dir_all, - // remove_file, and bind all follow a swapped parent, and - // the O_NOFOLLOW fd discipline below only runs when - // privileged with a configured peer_user. + // Refuse a symlinked socket parent unconditionally in bind mode: + // create_dir_all, remove_file, and bind all follow a swapped parent, + // and the O_NOFOLLOW fd discipline below only runs when privileged with + // a configured peer_user. match fs::symlink_metadata(parent) { Ok(md) if md.file_type().is_symlink() => { return Err(format!( @@ -499,11 +491,9 @@ pub fn acquire_listeners( // only that user (and root) can even reach the socket. Only // meaningful when we run privileged; dev runs skip it. if am_root && let Some(uid) = expected { - // Open the directory and operate on the fd throughout: - // O_NOFOLLOW rejects a symlink at the final component - // (audit 2026-08-02 A1/A2), and fchown/fchmod on the fd - // act on the pinned inode, immune to path swaps - // (audit finding #6). + // Open the directory and operate on the fd throughout: O_NOFOLLOW + // rejects a symlink at the final component, and fchown/fchmod on + // the fd act on the pinned inode, immune to path swaps. let dir_fd = rustix::fs::open( parent, rustix::fs::OFlags::RDONLY @@ -560,7 +550,7 @@ pub fn acquire_listeners( let mut seen: Vec = Vec::new(); let mut out = Vec::new(); for fd in fds { - // SAFETY: the sole unsafe in the program. sd_listen_fds() proved + // SAFETY: sd_listen_fds() proved // LISTEN_PID names this process, so fds [3, 3+n) are listening // sockets systemd created for us and nothing else owns them; taking // ownership here is exactly the sd_listen_fds(3) contract. @@ -675,8 +665,8 @@ pub fn run(args: &Args) -> Result<(), String> { "preflight ok: {} credential(s) decryptable", cfg.credentials.len() )); - // --allow-nonroot never overrides a configured peer_user (sweep - // 2026-08-07 D1); say so once at startup when both are present. + // --allow-nonroot never overrides a configured peer_user; say so once at startup + // when both are present. if args.allow_nonroot && peer_uids.values().any(Option::is_some) { log( "note: --allow-nonroot does not override configured peer_user ACLs — peer_user sockets still verify the connecting uid", @@ -688,9 +678,8 @@ pub fn run(args: &Args) -> Result<(), String> { for (listener, path) in listeners { let entry = match cfg.credentials.get(&path) { Some(e) => e.clone(), - // Unreachable (listeners derive from cfg.credentials), but a - // clear error beats an abort under panic=abort (audit - // 2026-08-02 A22). + // Unreachable (listeners derive from cfg.credentials), but a clear error + // beats an abort under panic=abort. None => { return Err(format!( "{}: internal: listener path missing from config", @@ -807,8 +796,8 @@ mod tests { #[test] fn preflight_rejects_empty_resolved_value() { - // sweep 2026-08-07 D4: zero bytes means refusal on the wire, so - // an empty value must fail at startup, not at first fetch. + // Zero bytes means refusal on the wire, so an empty value must fail at startup, + // not at first fetch. let dir = crate::test_util::temp_dir::TestDir::new("server"); let env_file = dir.join(".env"); fs::write(&env_file, "KEY=\n").unwrap(); @@ -844,7 +833,7 @@ mod tests { #[test] fn validate_absolute_paths_rejects_relative() { - // sweep 2026-08-07 D14: socket and keys paths must be absolute. + // Socket and keys paths must be absolute. let mut credentials = std::collections::HashMap::new(); credentials.insert( PathBuf::from("relative/key.sock"), @@ -873,9 +862,7 @@ mod tests { #[test] fn read_capped_passes_at_cap_and_fails_over_cap() { - // sweep 2026-08-07 T4: the A6 cap boundary itself — an at-cap - // read passes byte-exact; one byte over fails rather than - // truncates (a truncated secret must never be served whole). + // Accept the exact cap; reject excess bytes rather than serving a truncated secret. let at_cap = std::io::repeat(0x41).take(MAX_READ_BYTES); let got = read_capped(at_cap, Path::new("/test")).unwrap(); assert_eq!(got.len() as u64, MAX_READ_BYTES); diff --git a/src/test_util.rs b/src/test_util.rs index 9ee49b0..8ffb811 100644 --- a/src/test_util.rs +++ b/src/test_util.rs @@ -11,8 +11,6 @@ pub(crate) mod temp_dir; /// racing another test's mutation, is a data race; edition 2024 marks /// those calls `unsafe`. /// -/// ALL env-touching tests in every module hold this ONE lock for the -/// mutation's full scope. Module-local locks do not exclude each other: -/// separate per-module statics raced, and the loser's panic poisoned a -/// mutex, failing unrelated tests (~1 in 5 baseline runs). +/// Environment-mutating and whole-environment snapshot tests hold this lock +/// for the full scope. Separate module-local locks would not exclude each other. pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 5b168ed..e1360ea 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -55,8 +55,7 @@ pub fn write_keys_file(dir: &Path, env_suffix: &str, sk_hexes: &[&str]) -> PathB }; let p = dir.join(".env.keys"); fs::write(&p, format!("{var}=\"{}\"\n", sk_hexes.join(","))).unwrap(); - // KeyRing::load now enforces 0600-or-stricter permissions and euid - // ownership (audit finding #1). The temp file must pass that check. + // Match the owner-only permissions required by KeyRing::load. fs::set_permissions(&p, fs::Permissions::from_mode(0o600)).unwrap(); p } diff --git a/tests/exec_check.rs b/tests/exec_check.rs index afeb06a..891a7dd 100644 --- a/tests/exec_check.rs +++ b/tests/exec_check.rs @@ -163,7 +163,7 @@ fn docs_exec_schema_covers_every_exec_config_field() { .and_then(serde_json::Value::as_object) .unwrap(); // Keep this list in sync with the fields on `ExecConfig` in - // src/exec_config.rs — it is the schema/parser drift tripwire (T1). + // src/exec_config.rs to catch schema/parser drift. for field in [ "mode", "keys", diff --git a/tests/exec_conformance/bundle.rs b/tests/exec_conformance/bundle.rs index 9436491..2df2191 100644 --- a/tests/exec_conformance/bundle.rs +++ b/tests/exec_conformance/bundle.rs @@ -62,11 +62,7 @@ fn write_keys(dir: &std::path::Path, with_dotenv: bool) -> std::path::PathBuf { #[test] fn bundle_exec_loads_postmaster_key_through_load_ring() { - // Regression for the bundle-ring gap: load_ring hardcoded - // KeyNaming::Env at every source leg, so POSTMASTER_KEY never entered - // the ring and EVERY bundle config failed at exec with "key ring has - // no POSTMASTER_KEY entry". This test drives the real binary through - // load_ring; it fails on the old code and passes on the fix. + // The real launcher must load POSTMASTER_KEY for bundle inputs. let d = common::tmpdir("bundlee2e"); let bundle = write_bundle(&d, &[("SECRET", "bundle-secret-value")]); let keys = write_keys(&d, false); @@ -245,9 +241,8 @@ fn mixed_env_and_bundle_exec_resolves_both_adapters() { #[test] fn bundle_exec_refuses_symlinked_bundle_file() { - // sweep 2026-08-07 T5: the O_NOFOLLOW open on bundle ciphertext - // (audit 2026-08-02 A13) must hold end-to-end — a planted symlink at - // a configured bundle path is a hard error, never a read-through. + // The O_NOFOLLOW open on bundle ciphertext must hold end-to-end — a planted symlink + // at a configured bundle path is a hard error, never a read-through. let d = common::tmpdir("bundle-symlink"); let bundle = write_bundle(&d, &[("SECRET", "unreachable")]); let keys = write_keys(&d, false); @@ -269,9 +264,8 @@ fn bundle_exec_refuses_symlinked_bundle_file() { #[test] fn bundle_env_precedence_matches_env_adapter() { - // sweep 2026-08-07 T10: bundle entries follow the same precedence - // contract as .env values — the process environment wins unless - // overload. + // Bundle values follow dotenv precedence: the process environment wins + // unless overload is enabled. let d = common::tmpdir("bundle-prec"); let bundle = write_bundle(&d, &[("SECRET", "from-bundle")]); let keys = write_keys(&d, false); @@ -392,9 +386,9 @@ fn bundle_shadowed_nul_value_still_fails_closed() { #[test] fn bundle_nul_value_is_a_hard_error_under_any_strictness() { - // sweep 2026-08-07 T10 (X6): an env-bound bundle value containing NUL - // is a HARD error — one rule for every env-bound value. strict:false - // must NOT skip it the way it skips undecryptable values. + // An env-bound bundle value containing NUL is a HARD error — one rule for every + // env-bound value. strict:false must NOT skip it the way it skips undecryptable + // values. let d = common::tmpdir("bundle-nul"); let bundle = write_bundle(&d, &[("SECRET", "before\0after")]); let keys = write_keys(&d, false); diff --git a/tests/exec_conformance/daemon.rs b/tests/exec_conformance/daemon.rs index e7e46e8..1c2b484 100644 --- a/tests/exec_conformance/daemon.rs +++ b/tests/exec_conformance/daemon.rs @@ -1,7 +1,6 @@ -//! Daemon end-to-end conformance (sweep 2026-08-07 T2): the real binary -//! in serve mode, a real bound socket, and the real fetch client — the -//! serve/fetch roundtrip and the startup preflight refusal, which the -//! unit tests only exercise in-process. +//! Daemon end-to-end conformance: the real binary in serve mode, a real bound socket, +//! and the real fetch client — the serve/fetch roundtrip and the startup preflight +//! refusal, which the unit tests only exercise in-process. use sha2::Digest as _; use std::process::Command; @@ -167,10 +166,8 @@ fn daemon_roundtrip(mask: &str, peer_user: Option<&str>) { #[test] fn daemon_preflight_refuses_an_empty_credential_at_startup() { - // sweep 2026-08-07 D4 end-to-end: an empty resolved value can never - // be served (zero bytes means refusal on the wire), so the daemon - // must fail at STARTUP naming the key, not look healthy while every - // fetch comes back empty. + // Zero bytes means refusal on the wire; reject empty values at startup + // and name the key rather than starting a daemon that cannot serve it. let d = common::tmpdir("daemonpre"); let env = common::write_env_file(&d, ".env", &["EMPTY=".to_string()]); let keys = common::write_keys_file(&d, "", &[common::TEST_SK_HEX]); diff --git a/tests/exec_conformance/files_mode.rs b/tests/exec_conformance/files_mode.rs index b05c8a8..3810e10 100644 --- a/tests/exec_conformance/files_mode.rs +++ b/tests/exec_conformance/files_mode.rs @@ -140,10 +140,9 @@ fn credentials_mode_fetch_loop() { ); let out = run_exec(&cfg, &sh, &[]); if !out.status.success() { - // Hang guard (sweep 2026-08-07 T3): a regression that fails - // before connecting would leave the mock parked in accept() and - // the join below would hang the whole suite. Nudge the listener - // with a dummy connection so the thread can finish. + // Hang guard: a regression that fails before connecting would leave the mock + // parked in accept() and the join below would hang the whole suite. Nudge the + // listener with a dummy connection so the thread can finish. let _ = std::os::unix::net::UnixStream::connect(&sock); } server.join().unwrap(); @@ -168,9 +167,8 @@ fn credentials_mode_fetch_loop() { #[test] fn files_mode_exec_failure_leaves_only_the_sentinel() { - // sweep 2026-08-07 T6: an execvp failure (audit 2026-08-02 A9) must - // unwind the plaintext writes — after a failed exec the secrets dir - // holds ONLY the managed sentinel, never secret files. + // An execvp failure must unwind the plaintext writes — after a failed exec the + // secrets dir holds ONLY the managed sentinel, never secret files. let d = common::tmpdir("files-execfail"); let secrets_dir = d.join("secrets"); std::fs::create_dir_all(&secrets_dir).unwrap(); @@ -213,9 +211,8 @@ fn files_mode_exec_failure_leaves_only_the_sentinel() { #[test] fn files_mode_passthrough_nul_fails_closed_with_cleanup() { - // sweep 2026-08-07 T10: a passthrough value containing NUL cannot - // become an env var — fail closed AND unwind the secret file that - // was already written for it. + // A passthrough value containing NUL cannot become an env var — fail closed AND + // unwind the secret file that was already written for it. let d = common::tmpdir("files-ptnul"); let secrets_dir = d.join("secrets"); std::fs::create_dir_all(&secrets_dir).unwrap(); @@ -252,9 +249,8 @@ fn files_mode_passthrough_nul_fails_closed_with_cleanup() { #[test] fn files_mode_refuses_symlinked_secrets_dir() { - // sweep 2026-08-07 T11: a symlinked secrets_dir is a hard error - // before any plaintext is written — and the link target stays - // untouched. + // A symlinked secrets_dir is a hard error before any plaintext is written — and the + // link target stays untouched. let d = common::tmpdir("files-dirlink"); let real = d.join("real-secrets"); std::fs::create_dir_all(&real).unwrap(); diff --git a/tests/exec_conformance/keys_verify.rs b/tests/exec_conformance/keys_verify.rs index fc43921..b79fb81 100644 --- a/tests/exec_conformance/keys_verify.rs +++ b/tests/exec_conformance/keys_verify.rs @@ -133,11 +133,10 @@ fn strict_false_skips_undecryptable_and_continues() { #[test] fn verify_keys_aborts_on_stale_keys_with_strict_false() { - // Audit finding #4: --verify-keys should catch stale keys even when - // strict is false. Encrypt with a different key than the one in the - // keyring, set strict:false, and pass --verify-keys. The exec must - // abort with a --verify-keys error rather than launching the child - // with no secrets. + // --verify-keys should catch stale keys even when strict is false. Encrypt with a + // different key than the one in the keyring, set strict:false, and pass + // --verify-keys. The exec must abort with a --verify-keys error rather than + // launching the child with no secrets. let d = common::tmpdir("verifykeys"); let other_sk_hex = "33".repeat(32); let other_sk_bytes = hex::decode(&other_sk_hex).unwrap(); @@ -198,11 +197,8 @@ fn verify_keys_aborts_on_stale_keys_with_strict_false() { #[test] fn verify_keys_aborts_on_partial_failure_with_strict_false() { - // Audit 2026-08-02 A3: with strict:false, resolution silently skips - // undecryptable values. When SOME values still decrypt, the resolved - // set is non-empty and the old freshness check passed — the child - // launched with a partial secret set. --verify-keys must now abort - // on any recorded skip. + // --verify-keys must reject partial decryption even when strict:false would + // allow the remaining values to launch the child. let d = common::tmpdir("verifykeys-partial"); let other_sk_hex = "33".repeat(32); let other_sk_bytes = hex::decode(&other_sk_hex).unwrap(); @@ -219,7 +215,7 @@ fn verify_keys_aborts_on_partial_failure_with_strict_false() { &[ format!("DOTENV_PUBLIC_KEY_PRODUCTION=\"{}\"", common::test_pk_hex()), // Decrypts with the keyring's key — the resolved set is - // non-empty, which is what fooled the old check. + // non-empty, so a count-only check would miss the failure. format!("SECRET_GOOD=\"{}\"", common::enc("good-secret")), // Encrypted to a key NOT in the keyring — skipped under // strict:false. This is the partial-rotation case. diff --git a/tests/exec_conformance/main.rs b/tests/exec_conformance/main.rs index 88d3764..5032b6f 100644 --- a/tests/exec_conformance/main.rs +++ b/tests/exec_conformance/main.rs @@ -86,13 +86,11 @@ fn run_exec(config: &Path, sh: &str, envs: &[(&str, &str)]) -> std::process::Out c.args(["exec", "--config"]) .arg(config) .args(["--", "/bin/sh", "-c", sh]) - // Hermeticity: an ambient SECRET/PLAIN/A/GOOD/BAD/SECRET_GOOD in - // the test runner's own environment would flip the precedence-test - // outcomes below, since these are exactly the value-variable names - // the suite asserts on. DOTENV_PUBLIC_KEY_PRODUCTION and - // POSTMASTER_SECRETS_DIR are asserted ABSENT in the child; an - // ambient copy would be inherited and flake those assertions - // (sweep 2026-08-07 T8). + // Hermeticity: an ambient SECRET/PLAIN/A/GOOD/BAD/SECRET_GOOD in the test + // runner's own environment would flip the precedence-test outcomes below, since + // these are exactly the value-variable names the suite asserts on. + // DOTENV_PUBLIC_KEY_PRODUCTION and POSTMASTER_SECRETS_DIR are asserted ABSENT + // in the child; an ambient copy would be inherited and flake those assertions. .env_remove("SECRET") .env_remove("PLAIN") .env_remove("FIRST") From 312909695a1dbf4e58cb3ca8c65b9da381b4ef93 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Mon, 9 Nov 2026 21:10:44 -0600 Subject: [PATCH 42/47] docs: correct runtime dependency descriptions --- docs/src/architecture/postmaster.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/src/architecture/postmaster.md b/docs/src/architecture/postmaster.md index 05bb481..3d989dc 100644 --- a/docs/src/architecture/postmaster.md +++ b/docs/src/architecture/postmaster.md @@ -263,14 +263,16 @@ Source builds require Rust 1.99.1 or newer. The flake exports packages and an overlay, not NixOS or nix-darwin service modules. Deployment integrations own the service units, RAM-backed storage, and hardening described above. -Postmaster has 11 direct dependencies (9 portable, 2 platform-gated): +The runtime dependencies are: - `ecies` — crypto (secp256k1 + AES-256-GCM) - `aes-gcm` — bundle-envelope authentication with entry-name AAD -- `dotenvy` — `.env` file parser +- `dotenvy` — private-key file parsing - `serde` + `serde_json` — JSON config deserialization - `base64` — ciphertext decoding - `hex` — key parsing +- `sha2` — SHA-256 authorization of daemon source bytes +- `getrandom` — random names for private temporary files - `rustix` — syscalls (raw syscalls via `linux_raw` on Linux, incl. the monitor's pidfd/poll and the experimental `runtime` signal-mask API; the only libc FFI on Linux is `fork(2)` — see the unsafe registry) From 4fa0607921e77f985b359a8426b36ffe2feb5134 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Tue, 10 Nov 2026 02:09:07 -0600 Subject: [PATCH 43/47] docs: fix mermaid diagram rendering across the book - Labels starting with ordered-list syntax rendered as 'Unsupported markdown: list'; renumber with parens to keep the step labels. - Sequence-diagram message text containing semicolons threw a parse error; use commas instead. - Literal \n in quoted labels rendered as backslash-n text; use
so mermaid produces real line breaks. - Split the single all-modes injection diagram into one diagram per mode so each renders at a readable size. chore: exclude gitignored .aider-desk tool history from markdownlint --- .markdownlint-cli2.jsonc | 4 ++- docs/src/architecture/materialization-abi.md | 10 +++--- docs/src/architecture/postmaster.md | 10 +++--- docs/src/architecture/threat-model.md | 8 ++--- docs/src/getting-started/injection-modes.md | 32 ++++++++++---------- docs/src/getting-started/key-provisioning.md | 16 +++++----- docs/src/introduction.md | 8 ++--- docs/src/reference/launcher-contract.md | 14 ++++----- docs/src/unsafe-code/monitor.md | 12 ++++---- 9 files changed, 58 insertions(+), 56 deletions(-) diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc index 2867622..450dce0 100644 --- a/.markdownlint-cli2.jsonc +++ b/.markdownlint-cli2.jsonc @@ -29,6 +29,8 @@ // Verbatim upstream Contributor Covenant — not house prose. ".github/CODE_OF_CONDUCT.md", // PR templates intentionally start with "## Summary" — MD041 is wrong for them. - ".github/pull_request_template.md" + ".github/pull_request_template.md", + // Local aider tool history (gitignored) — not repo content. + ".aider-desk/" ] } diff --git a/docs/src/architecture/materialization-abi.md b/docs/src/architecture/materialization-abi.md index 3042174..f93ad0b 100644 --- a/docs/src/architecture/materialization-abi.md +++ b/docs/src/architecture/materialization-abi.md @@ -61,11 +61,11 @@ The ABI has five layers. ```mermaid flowchart TD - art["1. Artifact descriptors\nidentify encrypted local inputs"] - key["2. Key-source descriptors\nidentify local private key material"] - res["3. Resolution rules\nturn encrypted entries into plaintext"] - proj["4. Projection policy\ndecides where bytes appear"] - launch["5. Launch semantics\nexecvp replaces postmaster with target"] + art["(1) Artifact descriptors
identify encrypted local inputs"] + key["(2) Key-source descriptors
identify local private key material"] + res["(3) Resolution rules
turn encrypted entries into plaintext"] + proj["(4) Projection policy
decides where bytes appear"] + launch["(5) Launch semantics
execvp replaces postmaster with target"] art --> res key --> res diff --git a/docs/src/architecture/postmaster.md b/docs/src/architecture/postmaster.md index 3d989dc..2d25267 100644 --- a/docs/src/architecture/postmaster.md +++ b/docs/src/architecture/postmaster.md @@ -109,19 +109,19 @@ materialization and the process handoff. ```mermaid flowchart LR subgraph s1["1. Custody"] - vault["Vault / SSM /\n1Password / TPM2"] + vault["Vault / SSM /
1Password / TPM2"] end subgraph s2["2. Rendering"] - nix["Nix / Terraform /\nCDK / Ansible"] + nix["Nix / Terraform /
CDK / Ansible"] end subgraph s3["3. Delivery"] - cred["systemd cred /\nfile / keychain"] + cred["systemd cred /
file / keychain"] end subgraph s4["4. Materialization"] - pm["postmaster\ndecrypt + inject"] + pm["postmaster
decrypt + inject"] end subgraph s5["5. Launch"] - exec["execvp\nchild = MainPID"] + exec["execvp
child = MainPID"] end vault --> nix diff --git a/docs/src/architecture/threat-model.md b/docs/src/architecture/threat-model.md index 392d426..220dc4d 100644 --- a/docs/src/architecture/threat-model.md +++ b/docs/src/architecture/threat-model.md @@ -116,12 +116,12 @@ fetch them remotely. ```mermaid flowchart TB subgraph trusted["Trusted zone"] - keys["Private key material\n(systemd cred / file / keychain)"] - pm["postmaster\n(decrypt + inject)"] - child["Child process\n(your binary)"] + keys["Private key material
(systemd cred / file / keychain)"] + pm["postmaster
(decrypt + inject)"] + child["Child process
(your binary)"] end subgraph untrusted["Public zone"] - ciphertext["Encrypted .env\n(git / Nix store / artifact)"] + ciphertext["Encrypted .env
(git / Nix store / artifact)"] end subgraph outside["Outside trust boundary"] root["Root on host"] diff --git a/docs/src/getting-started/injection-modes.md b/docs/src/getting-started/injection-modes.md index d35196f..1dd3e1b 100644 --- a/docs/src/getting-started/injection-modes.md +++ b/docs/src/getting-started/injection-modes.md @@ -15,26 +15,13 @@ depend on the deployment as well as the selected mode. | `files` | Apps that read `KEY_FILE` pointers (Docker secrets convention) | Only when `passthrough` requests it | No environment copy by default; the app still reads plaintext files | | `credentials` | Apps that read credential files | No additional value copy | Systemd supplies the credentials directory, or Postmaster fetches values from local sockets | -## Mode comparison +## `mode = "env"` ```mermaid -flowchart TB - subgraph env["mode: env"] - pm_env["postmaster"] -->|KEY=value\nin environ| child_env["your binary"] - end - subgraph files["mode: files"] - pm_files["postmaster"] -->|write 0600 file| tmpfs["tmpfs / ramdisk"] - tmpfs -->|KEY_FILE=/run/.../KEY| child_files["your binary"] - end - subgraph cred["mode: credentials"] - daemon["postmaster credential daemon"] -->|decrypted bytes over local socket| systemd["systemd"] - systemd -->|LoadCredential=| ramfs["ramfs\n$CREDENTIALS_DIRECTORY"] - ramfs -->|KEY_FILE=$CREDENTIALS_DIRECTORY/KEY| child_cred["your binary"] - end +flowchart LR + pm_env["postmaster
(decrypt + inject)"] -->|"KEY=value
in environ"| child_env["your binary"] ``` -## `mode = "env"` - Postmaster exports resolved values into the application environment and replaces the launcher with your binary. @@ -53,6 +40,12 @@ preserve `${VAR}` literally. `$(cmd)` does not execute a command. ## `mode = "files"` +```mermaid +flowchart LR + pm_files["postmaster
(decrypt + inject)"] -->|"write 0600 file"| tmpfs["tmpfs / ramdisk
(secrets_dir)"] + tmpfs -->|"KEY_FILE=/run/postmaster/KEY"| child_files["your binary"] +``` + Deployments provide a namespace-private tmpfs for one-file-per-key output (`TemporaryFileSystem=/run/postmaster`; on macOS, a per-service directory on an HFS RAM disk) and only `_FILE` pointer variables are exported @@ -94,6 +87,13 @@ rejection, since they become environment variables). ## `mode = "credentials"` +```mermaid +flowchart LR + daemon["postmaster credential daemon
(local socket)"] -->|"decrypted bytes
over socket"| systemd["systemd
(LoadCredential=)"] + systemd -->|"credential files"| ramfs["ramfs
$CREDENTIALS_DIRECTORY"] + ramfs -->|"KEY_FILE=$CREDENTIALS_DIRECTORY/KEY"| child_cred["your binary"] +``` + The launcher exports `_FILE` pointers into credentials that systemd has already supplied. Systemd can obtain those credentials from Postmaster's daemon. In that deployment, the consumer's unit gets diff --git a/docs/src/getting-started/key-provisioning.md b/docs/src/getting-started/key-provisioning.md index 3ed3e70..16b8006 100644 --- a/docs/src/getting-started/key-provisioning.md +++ b/docs/src/getting-started/key-provisioning.md @@ -21,10 +21,10 @@ fetches from remote systems. ```mermaid flowchart TB subgraph sources["Key sources (local only)"] - cred["systemd credentials\n(LoadCredential=)"] - file["file\n(.env.keys on disk)"] - kc["keychain\n(macOS only)"] - env["environment\n(DOTENV_PRIVATE_KEY*)"] + cred["systemd credentials
(LoadCredential=)"] + file["file
(.env.keys on disk)"] + kc["keychain
(macOS only)"] + env["environment
(DOTENV_PRIVATE_KEY*)"] end pm["postmaster"] @@ -135,10 +135,10 @@ no per-environment suffix — follows the same convention): ```mermaid flowchart TD - step1["Step 1: Author new keypair locally\nDecrypt env, delete old pub key, re-encrypt with fresh keypair"] - step2["Step 2: Set DOTENV_PRIVATE_KEY=new,old\nBoth keys accepted; restarts decrypt either generation"] - step3["Step 3: Deploy new ciphertext\nnixos-rebuild switch — new units decrypt with new key\nOld units still running on old key"] - step4["Step 4: Drop old key (after rollback horizon)\nSet DOTENV_PRIVATE_KEY=new only\nOld generations + new-only key = broken restarts"] + step1["Step 1: Author new keypair locally
Decrypt env, delete old pub key, re-encrypt with fresh keypair"] + step2["Step 2: Set DOTENV_PRIVATE_KEY=new,old
Both keys accepted; restarts decrypt either generation"] + step3["Step 3: Deploy new ciphertext
nixos-rebuild switch — new units decrypt with new key
Old units still running on old key"] + step4["Step 4: Drop old key (after rollback horizon)
Set DOTENV_PRIVATE_KEY=new only
Old generations + new-only key = broken restarts"] step1 --> step2 step2 --> step3 diff --git a/docs/src/introduction.md b/docs/src/introduction.md index 1ae4977..7afaae3 100644 --- a/docs/src/introduction.md +++ b/docs/src/introduction.md @@ -76,15 +76,15 @@ protection. The application keeps access to the secrets it uses. ```mermaid flowchart LR - store["Encrypted .env file\n(nix store / git / artifact)"] - keys["Private key\n(systemd cred / file / keychain)"] + store["Encrypted .env file
(nix store / git / artifact)"] + keys["Private key
(systemd cred / file / keychain)"] pm["postmaster exec"] - child["Your binary\n(MainPID)"] + child["Your binary
(MainPID)"] store --> pm keys --> pm pm -->|decrypt + inject| child - pm -.->|execvp replaces\npostmaster| child + pm -.->|execvp replaces
postmaster| child ``` The ciphertext is designed to be public. Every value is diff --git a/docs/src/reference/launcher-contract.md b/docs/src/reference/launcher-contract.md index 5558b44..c053b90 100644 --- a/docs/src/reference/launcher-contract.md +++ b/docs/src/reference/launcher-contract.md @@ -51,13 +51,13 @@ service-manager wiring require separate validation. ```mermaid flowchart TD - cfg["exec.json\n(mode, keys, env_files, bundle_files)"] - check["--check\nconfig shape only"] - recheck["setup --recheck\nkey source accessible?"] - resolve["resolve_all + resolve_bundle\ndecrypt + resolve"] - verify["--verify-keys\nstale key check"] - inject["inject\n(env / files / credentials)"] - execvp["execvp\nchild = MainPID"] + cfg["exec.json
(mode, keys, env_files, bundle_files)"] + check["--check
config shape only"] + recheck["setup --recheck
key source accessible?"] + resolve["resolve_all + resolve_bundle
decrypt + resolve"] + verify["--verify-keys
stale key check"] + inject["inject
(env / files / credentials)"] + execvp["execvp
child = MainPID"] cfg --> check cfg --> recheck diff --git a/docs/src/unsafe-code/monitor.md b/docs/src/unsafe-code/monitor.md index 0bde0c2..537f423 100644 --- a/docs/src/unsafe-code/monitor.md +++ b/docs/src/unsafe-code/monitor.md @@ -13,10 +13,10 @@ sequenceDiagram participant M as Monitor (fork-child) participant S as Service (exec'd parent) - L->>L: block stop signals; materialize; wipe ring and resolved buffers + L->>L: block stop signals, materialize, wipe ring and resolved buffers L->>M: fork() - Note over M: scrub projected pairs; retain original environment; keep mask blocked - L->>S: restore mask; execvp becomes service + Note over M: scrub projected pairs, retain original environment, keep mask blocked + L->>S: restore mask, execvp becomes service loop poll tick M->>S: liveness (pidfd+poll / kqueue NOTE_EXIT) M->>M: stop signal pending? (sigpending then sigwait) @@ -25,13 +25,13 @@ sequenceDiagram M->>S: forward the signal Note over M,S: bounded grace (250 ms) alt service exits within the grace - M->>M: cleanup plaintext files; exit 0 + M->>M: cleanup plaintext files, exit 0 else grace expires M->>S: SIGKILL - M->>M: cleanup plaintext files; exit 0 + M->>M: cleanup plaintext files, exit 0 end else service death (exit, crash, kill -9) - M->>M: cleanup plaintext files; exit 0 + M->>M: cleanup plaintext files, exit 0 end ``` From 9bd5fb4db5365b227cc747342317e3efbc128b36 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Tue, 10 Nov 2026 05:05:36 -0600 Subject: [PATCH 44/47] fix: isolate monitor tests and refresh crypto dependencies --- CHANGELOG.md | 9 +++++--- Cargo.lock | 14 ++++++------ Cargo.toml | 2 +- docs/src/unsafe-code/monitor.md | 4 +++- src/monitor/tests.rs | 40 +++++++++++++++++++++++++++++++++ 5 files changed, 57 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b72b0fa..8869ba7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,6 +67,8 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). dotenv parsing rules, including variable substitution. - Zeroizes the key ring and resolved value buffers before launch. `KeyRing` and `Resolution` debug output redacts secret material. + ECIES secret-key debug output also redacts key bytes, and secret-key + comparisons use constant-time equality. - Keeps the application as the service's main PID. A sibling monitor forwards stop signals, allows a 250 ms grace period before SIGKILL, and tracks service exit with Linux pidfds or macOS kqueue. It attempts file @@ -121,9 +123,10 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - Provides `postmaster cleanup --config ` for managed plaintext-file cleanup and `fetch` for local credential retrieval. - Separates key handling, CLI parsing, and adapters into focused modules. - Monitor tests live beside the monitor module, adapter mapping tests live - with the adapters, and binary conformance tests cover each launch mode. -- Uses registry dependencies including base64 0.23.1, ecies 0.2.13, + Monitor tests live beside the monitor module and run fork-based cases in + isolated processes. Adapter mapping tests live with the adapters, and + binary conformance tests cover each launch mode. +- Uses registry dependencies including base64 0.23.1, ecies 0.2.14, serde 1.0.229, serde_json 1.0.154, zeroize 1.9.1, rustix 1.1.6, and libc 0.2.191. AES-GCM 0.11.1 handles bundle authentication. - Requires Rust 1.99.1 or newer. Release builds use LTO, stripped symbols, diff --git a/Cargo.lock b/Cargo.lock index b5fe26a..732f0cb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -146,9 +146,9 @@ checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" [[package]] name = "crypto-bigint" -version = "0.7.10" +version = "0.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" +checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82" dependencies = [ "cpubits", "ctutils", @@ -218,9 +218,9 @@ checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" [[package]] name = "ecies" -version = "0.2.13" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05585cd8ca04e63c7bb5d7308fd7583cc8df9fcf3e6ff9132562c57209a7f231" +checksum = "7789c0aca3f3a992a12684c7a1089235faf38e399c7340a523f71bb4790f6e8b" dependencies = [ "aes-gcm", "getrandom 0.2.17", @@ -697,7 +697,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -755,9 +755,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.3" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index e23904c..64f09d0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -100,7 +100,7 @@ used_underscore_binding = "warn" # Wire-compatible with eciesjs (dotenvx's crypto): secp256k1 + HKDF-SHA256 + # AES-256-GCM with the ecies family's 16-byte nonce default. `pure` selects # the RustCrypto AES backend — no openssl in the closure. -ecies = { version = "0.2.13", default-features = false, features = ["pure", "secp256k1", "std"] } +ecies = { version = "0.2.14", default-features = false, features = ["pure", "secp256k1", "std"] } # The bundle adapter owns its AAD envelope; RustCrypto performs AES-GCM. aes-gcm = { version = "0.11.1", default-features = false, features = ["aes", "zeroize"] } dotenvy = "0.15" diff --git a/docs/src/unsafe-code/monitor.md b/docs/src/unsafe-code/monitor.md index 537f423..86075e9 100644 --- a/docs/src/unsafe-code/monitor.md +++ b/docs/src/unsafe-code/monitor.md @@ -135,7 +135,9 @@ The launcher and monitor import it as `runtime`. ## Tests -`monitor::tests` fork the REAL monitor loop in a real fork-child against +Each fork-based `monitor::tests` case runs in an isolated test process so +other tests cannot race native-library initialization with fork callbacks. +The tests fork the real monitor loop in a real fork-child against real service processes (deterministic; grace/poll injectable; no env mutation): natural `kill -9` death → cleanup + exit; TERM to the monitor → forwarded (service dies by TERM, proving no escalation) → cleanup + diff --git a/src/monitor/tests.rs b/src/monitor/tests.rs index 6688a24..c74c761 100644 --- a/src/monitor/tests.rs +++ b/src/monitor/tests.rs @@ -14,6 +14,31 @@ use rustix::process::{WaitOptions, waitpid}; use crate::launcher::TerminationGuard; use crate::secret_files::open_secrets_dir; +/// Keep fork callbacks separate from native-library initialization in other tests. +/// Return true when the current test completed in the isolated child process. +fn run_isolated() -> bool { + let thread = std::thread::current(); + let name = thread.name().unwrap(); + let args = ["--exact", name, "--nocapture"]; + if std::env::args_os() + .skip(1) + .eq(args.map(std::ffi::OsString::from)) + { + return false; + } + let output = Command::new(std::env::current_exe().unwrap()) + .args(args) + .output() + .unwrap(); + assert!( + output.status.success(), + "isolated {name}: {}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + true +} + fn tdir(tag: &str) -> crate::test_util::temp_dir::TestDir { crate::test_util::temp_dir::TestDir::new(tag) } @@ -142,6 +167,9 @@ fn fork_term_ignoring_service() -> Pid { /// stand-in) must still trigger cleanup and monitor exit. #[test] fn natural_service_death_triggers_cleanup_and_monitor_exit() { + if run_isolated() { + return; + } let dir = tdir("natural"); let names = write_dummies(&dir); let mut service = Command::new("sleep").arg("30").spawn().unwrap(); @@ -175,6 +203,9 @@ fn natural_service_death_triggers_cleanup_and_monitor_exit() { /// no settle sleep is needed. #[test] fn stop_signal_is_forwarded_then_grace_then_cleanup() { + if run_isolated() { + return; + } let dir = tdir("forward"); let names = write_dummies(&dir); let mut service = Command::new("sleep").arg("30").spawn().unwrap(); @@ -208,6 +239,9 @@ fn stop_signal_is_forwarded_then_grace_then_cleanup() { /// elapses; cleanup still runs and the monitor exits 0. #[test] fn term_ignoring_service_is_sigkilled_after_grace() { + if run_isolated() { + return; + } let dir = tdir("grace"); let names = write_dummies(&dir); let service_pid = fork_term_ignoring_service(); @@ -261,6 +295,9 @@ fn wipe_pair_scrubs_both_buffers() { /// still exits when the service dies. #[test] fn env_mode_monitor_with_no_files_exits_on_service_death() { + if run_isolated() { + return; + } let mut service = Command::new("sleep").arg("30").spawn().unwrap(); let service_pid = Pid::from_child(&service); let _reap = ReapOnDrop(service_pid); @@ -285,6 +322,9 @@ fn env_mode_monitor_with_no_files_exits_on_service_death() { /// process that died before it began watching. #[test] fn pre_dead_service_triggers_immediate_cleanup_and_exit() { + if run_isolated() { + return; + } let dir = tdir("predead"); let names = write_dummies(&dir); let mut service = Command::new("sleep").arg("30").spawn().unwrap(); From 3b46f74aaa6aab589e7c649e507b77cc0861b78b Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Tue, 10 Nov 2026 05:44:20 -0600 Subject: [PATCH 45/47] fix: refresh stable Rust before CI setup checks --- .github/actions/setup-rust/action.yml | 3 +- .github/actions/setup-rust/test.py | 83 ++++++++++++++++++++++++++- CHANGELOG.md | 3 +- 3 files changed, 85 insertions(+), 4 deletions(-) diff --git a/.github/actions/setup-rust/action.yml b/.github/actions/setup-rust/action.yml index 3a686bc..1bc8e1c 100644 --- a/.github/actions/setup-rust/action.yml +++ b/.github/actions/setup-rust/action.yml @@ -63,7 +63,8 @@ runs: if [[ -n "${GITHUB_PATH:-}" ]]; then echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" fi - # Installs the toolchain and components pinned in rust-toolchain.toml. + # Refresh stable before resolving the repository's components and targets. + rustup update stable --no-self-update rustup show if [[ -n "$RUST_TARGETS" ]]; then rustup target add $RUST_TARGETS diff --git a/.github/actions/setup-rust/test.py b/.github/actions/setup-rust/test.py index 009dcee..8bb2593 100644 --- a/.github/actions/setup-rust/test.py +++ b/.github/actions/setup-rust/test.py @@ -1,4 +1,4 @@ -"""Exercise Cargo tool setup without installing packages. +"""Exercise Rust and Cargo tool setup without installing packages. Run: python3 .github/actions/setup-rust/test.py [path-to-bash] """ @@ -117,6 +117,85 @@ except (AssertionError, ValueError, FileNotFoundError) as error: failures.append(f"{tool}/{scenario}: {error}") +rust_scenarios = ( + "outdated", "current", "fresh", "targets", "update-fails", "show-fails", + "target-fails", "missing", +) +section = action.split(" - name: Install pinned Rust toolchain\n", 1)[1].split("\n - name:", 1)[0] +body = textwrap.dedent(section.split(" run: |\n", 1)[1]) +for scenario in rust_scenarios: + with tempfile.TemporaryDirectory(prefix="postmaster-rustup-") as tmp: + root = Path(tmp) + home = root / "home" + home.mkdir() + shims = root / "shims" + shims.mkdir() + log = root / "rustup.log" + state = root / "version" + if scenario != "fresh": + state.write_text("1.99.1\n" if scenario == "current" else "1.98.0\n") + targets = "aarch64-unknown-linux-gnu wasm32-unknown-unknown" if scenario in ("targets", "target-fails") else "" + env = { + **os.environ, + "HOME": str(home), + "PATH": str(shims), + "GITHUB_PATH": str(root / "github-path"), + "RUST_TARGETS": targets, + "TEST_SCENARIO": scenario, + "TEST_RUSTUP_LOG": str(log), + "TEST_RUSTUP_STATE": str(state), + } + if scenario != "missing": + rustup = shims / "rustup" + rustup.write_text(r"""#!/bin/bash +set -eu +printf '%s\n' "$*" >> "$TEST_RUSTUP_LOG" +case "$1" in + update) + [[ "$*" == 'update stable --no-self-update' ]] || exit 2 + [[ "$TEST_SCENARIO" != update-fails ]] || exit 1 + printf '1.99.1\n' > "$TEST_RUSTUP_STATE" + ;; + show) + [[ "$TEST_SCENARIO" != show-fails ]] || exit 1 + [[ -f "$TEST_RUSTUP_STATE" ]] || printf '1.99.1\n' > "$TEST_RUSTUP_STATE" + ;; + target) + [[ "$TEST_SCENARIO" != target-fails ]] || exit 1 + ;; + *) exit 2 ;; +esac +""") + rustup.chmod(0o755) + result = subprocess.run( + [str(bash), "-c", body], env=env, capture_output=True, text=True, + timeout=10, + ) + try: + should_fail = scenario in ("update-fails", "show-fails", "target-fails", "missing") + assert (result.returncode != 0) == should_fail, result.stdout + result.stderr + calls = log.read_text().splitlines() if log.exists() else [] + if not should_fail: + assert state.read_text().strip() == "1.99.1", "stable remains below the required Rust version" + assert "show" in calls, "repository components and targets were not resolved" + if scenario == "outdated": + assert calls.index("update stable --no-self-update") < calls.index("show"), calls + expected_targets = [f"target add {targets}"] if targets else [] + assert [call for call in calls if call.startswith("target ")] == expected_targets, calls + elif scenario == "update-fails": + assert calls == ["update stable --no-self-update"], calls + elif scenario == "show-fails": + assert calls[-1] == "show", calls + elif scenario == "target-fails": + assert calls[-1] == f"target add {targets}", calls + else: + assert not calls, calls + assert "rustup must be preinstalled" in result.stderr, result.stderr + if scenario != "missing": + assert (root / "github-path").read_text().splitlines() == [str(home / ".cargo/bin")] + except (AssertionError, ValueError, FileNotFoundError, IndexError) as error: + failures.append(f"rustup/{scenario}: {error}") + if failures: raise SystemExit("\n".join(failures)) -print(f"Cargo tool setup: {len(tools) * len(scenarios)} cases pass") +print(f"Cargo tool setup: {len(tools) * len(scenarios)} cases pass; Rust toolchain setup: {len(rust_scenarios)} cases pass") diff --git a/CHANGELOG.md b/CHANGELOG.md index 8869ba7..e820825 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -137,7 +137,8 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Cross builds use `cargo zigbuild`; builds preserve compiler flags and profile overrides, and `max` builds remap source paths. - Uses Justfile recipes for local checks and GitHub workflow definitions. - In-repo setup actions configure toolchains; Nix installation verifies + In-repo setup actions refresh stable before resolving the repository's + components and targets. Nix installation verifies the pinned installer digest before execution. Official GitHub actions and helper tools use pinned versions. Nix installer temporary files work with GNU and macOS `mktemp`. From aaa263f7e4abdbc4448b2c3aa9d3a34db33734a6 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Tue, 10 Nov 2026 05:59:39 -0600 Subject: [PATCH 46/47] ci: enable hosted quality, security, Nix and docs checks --- .github/workflows/ci.yml | 3 --- .github/workflows/docs.yml | 3 --- .github/workflows/nix.yml | 3 --- .github/workflows/security.yml | 4 ---- 4 files changed, 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2295ed5..3603e1b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,5 @@ name: CI -# Disabled: GitHub Actions budget exhausted. -# Remove the `if: false` on each job to re-enable. on: push: branches: [main] @@ -22,7 +20,6 @@ jobs: quality: name: Quality (${{ matrix.os }}) runs-on: ${{ matrix.os }} - if: false timeout-minutes: 30 strategy: fail-fast: false diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index a33cf6b..934e0d8 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,7 +1,5 @@ name: Docs -# Disabled: GitHub Actions budget exhausted. -# Remove the `if: false` on each job to re-enable. on: push: branches: [main] @@ -25,7 +23,6 @@ jobs: build: name: Build book runs-on: ubuntu-latest - if: false timeout-minutes: 15 steps: - name: Checkout diff --git a/.github/workflows/nix.yml b/.github/workflows/nix.yml index df9566e..0d7f6f2 100644 --- a/.github/workflows/nix.yml +++ b/.github/workflows/nix.yml @@ -1,7 +1,5 @@ name: Nix -# Disabled: GitHub Actions budget exhausted. -# Remove the `if: false` on each job to re-enable. on: push: branches: [main] @@ -19,7 +17,6 @@ jobs: flake-check: name: flake check (${{ matrix.os }}) runs-on: ${{ matrix.os }} - if: false timeout-minutes: 30 strategy: fail-fast: false diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index b8005b5..12619ab 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -1,7 +1,5 @@ name: Security -# Disabled: GitHub Actions budget exhausted. -# Remove the `if: false` on each job to re-enable. on: schedule: # Run daily at 9am UTC @@ -28,7 +26,6 @@ jobs: audit: name: Security Audit runs-on: ubuntu-latest - if: false timeout-minutes: 15 steps: - name: Checkout @@ -47,7 +44,6 @@ jobs: deny: name: Dependency Check runs-on: ubuntu-latest - if: false timeout-minutes: 15 steps: - name: Checkout From 837df44bafdcbc23614242b9968dd2737c5c69b8 Mon Sep 17 00:00:00 2001 From: beardedeagle Date: Tue, 10 Nov 2026 06:40:47 -0600 Subject: [PATCH 47/47] test: assert fail-closed behavior in isolated builds --- src/keys/provisioning/mod.rs | 34 +++++++++++++++++++++++--------- src/ramdisk.rs | 5 ++--- src/secret_files.rs | 38 +++++++++++++++++++++++------------- src/server.rs | 32 ++++++++++++++++++++---------- src/test_util.rs | 7 +++++++ 5 files changed, 80 insertions(+), 36 deletions(-) diff --git a/src/keys/provisioning/mod.rs b/src/keys/provisioning/mod.rs index ff6a9bc..9c78a4b 100644 --- a/src/keys/provisioning/mod.rs +++ b/src/keys/provisioning/mod.rs @@ -594,15 +594,21 @@ mod tests { use std::os::unix::fs::PermissionsExt; let d = crate::test_util::temp_dir::TestDir::new("mod"); let keys = d.join(".env.keys"); - fs::write(&keys, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); + let contents = format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32)); + fs::write(&keys, &contents).unwrap(); fs::set_permissions(&keys, fs::Permissions::from_mode(0o600)).unwrap(); let err = ensure_keys_file(&keys, true, true).expect_err("force + unattended must fail closed"); - assert!(err.contains("unattended"), "{err}"); - - // Non-force unattended with a valid file verifies fine. - ensure_keys_file(&keys, false, true).expect("valid file must verify without force"); + let verification = ensure_keys_file(&keys, false, true); + if crate::test_util::root_has_trusted_owner() { + assert!(err.contains("unattended"), "{err}"); + verification.expect("valid file must verify without force"); + } else { + assert_eq!(err, "/: directory path is owned by an untrusted user"); + assert_eq!(verification.unwrap_err(), err); + } + assert_eq!(fs::read_to_string(&keys).unwrap(), contents); let _ = fs::remove_dir_all(&d); } @@ -743,17 +749,27 @@ mod tests { use std::os::unix::fs::PermissionsExt; let d = crate::test_util::temp_dir::TestDir::new("mod"); let keys = d.join(".env.keys"); - fs::write(&keys, format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32))).unwrap(); + let contents = format!("DOTENV_PRIVATE_KEY={}\n", "11".repeat(32)); + fs::write(&keys, &contents).unwrap(); fs::set_permissions(&keys, fs::Permissions::from_mode(0o644)).unwrap(); - ensure_keys_file(&keys, false, true).expect("verify/correct should succeed"); + let verification = ensure_keys_file(&keys, false, true); let mode = fs::metadata(&keys).unwrap().permissions().mode() & 0o777; - assert_eq!(mode, 0o600, "a 0644 keys file must be corrected to 0600"); let missing = d.join("absent.keys"); let err = ensure_keys_file(&missing, false, true) .expect_err("missing file + unattended must fail closed"); - assert!(err.contains("unattended mode"), "{err}"); + if crate::test_util::root_has_trusted_owner() { + verification.expect("verify/correct should succeed"); + assert_eq!(mode, 0o600, "a 0644 keys file must be corrected to 0600"); + assert!(err.contains("unattended mode"), "{err}"); + } else { + assert_eq!(err, "/: directory path is owned by an untrusted user"); + assert_eq!(verification.unwrap_err(), err); + assert_eq!(mode, 0o644, "untrusted ancestry must prevent mutation"); + } + assert_eq!(fs::read_to_string(&keys).unwrap(), contents); + assert!(!missing.exists()); let _ = fs::remove_dir_all(&d); } diff --git a/src/ramdisk.rs b/src/ramdisk.rs index 8c0e480..ed550c5 100644 --- a/src/ramdisk.rs +++ b/src/ramdisk.rs @@ -323,9 +323,8 @@ image-type : read/write let candidate = mount.join("link/service"); assert!(path_beneath(&candidate, &mount)); assert!(fs::symlink_metadata(&candidate).unwrap().is_dir()); - // /dev is a distinct filesystem on supported Linux/macOS hosts. - let expected_device = fs::metadata("/dev").unwrap().dev(); - assert_ne!(expected_device, fs::metadata(&candidate).unwrap().dev()); + // Inject a different device ID; /dev can share the build filesystem. + let expected_device = fs::metadata(&candidate).unwrap().dev() ^ 1; let err = open_verified_dir(&mount, &candidate, expected_device).unwrap_err(); diff --git a/src/secret_files.rs b/src/secret_files.rs index aff0cc1..efe9219 100644 --- a/src/secret_files.rs +++ b/src/secret_files.rs @@ -496,22 +496,32 @@ mod tests { fs::set_permissions(&shared, fs::Permissions::from_mode(0o777)).unwrap(); let fd = open_secrets_dir(&secret).unwrap(); let error = validate_projection(&fd, &secret).unwrap_err(); - assert!(error.contains("untrusted replacement"), "{error}"); + let trusted_root = crate::test_util::root_has_trusted_owner(); + if trusted_root { + assert!(error.contains("untrusted replacement"), "{error}"); + } else { + assert_eq!(error, "/: directory path is owned by an untrusted user"); + } fs::set_permissions(&shared, fs::Permissions::from_mode(0o1777)).unwrap(); - assert_eq!(validate_projection(&fd, &secret).unwrap(), secret); + let direct = validate_projection(&fd, &secret); std::os::unix::fs::symlink(&shared, dir.join("alias")).unwrap(); - assert_eq!( - validate_projection(&fd, &dir.join("alias/service")).unwrap(), - secret - ); - write_secret_file(&fd, &secret, "KEY", b"secret").unwrap(); - let child = std::process::Command::new("/bin/sh") - .args(["-c", "cat \"$KEY_FILE\""]) - .env("KEY_FILE", secret.join("KEY")) - .output() - .unwrap(); - assert!(child.status.success()); - assert_eq!(child.stdout, b"secret"); + let alias = validate_projection(&fd, &dir.join("alias/service")); + if trusted_root { + assert_eq!(direct.unwrap(), secret); + assert_eq!(alias.unwrap(), secret); + write_secret_file(&fd, &secret, "KEY", b"secret").unwrap(); + let child = std::process::Command::new("/bin/sh") + .args(["-c", "cat \"$KEY_FILE\""]) + .env("KEY_FILE", secret.join("KEY")) + .output() + .unwrap(); + assert!(child.status.success()); + assert_eq!(child.stdout, b"secret"); + } else { + assert_eq!(direct.unwrap_err(), error); + assert_eq!(alias.unwrap_err(), error); + assert!(!secret.join("KEY").exists()); + } } #[test] diff --git a/src/server.rs b/src/server.rs index 50b1d0a..e92ac7f 100644 --- a/src/server.rs +++ b/src/server.rs @@ -745,20 +745,32 @@ mod tests { let err = verify_id_candidate(&p).unwrap_err(); let _ = fs::remove_file(&path); - assert!( - err.contains("owned by uid") || err.contains("writable"), - "{err}" - ); + if crate::test_util::root_has_trusted_owner() { + assert!( + err.contains("owned by uid") || err.contains("writable"), + "{err}" + ); + } else { + assert_eq!(err, "/: directory path is owned by an untrusted user"); + } } #[test] #[cfg(not(target_os = "macos"))] - fn verified_id_binary_finds_a_system_id() { - // On any Linux host at least one candidate must verify — glibc - // systems have /usr/bin/id or /bin/id, NixOS has - // /run/current-system/sw/bin/id. - let id = verified_id_binary().unwrap(); - assert!(id.is_absolute()); + fn verified_id_binary_uses_system_paths_or_fails_closed() { + let paths = ["/usr/bin/id", "/bin/id", "/run/current-system/sw/bin/id"]; + let available = paths.iter().any(|p| Path::new(p).try_exists().unwrap()); + let result = verified_id_binary(); + if available && crate::test_util::root_has_trusted_owner() { + assert!(result.unwrap().is_absolute()); + } else { + let err = result.unwrap_err(); + assert!(err.starts_with("no trustworthy `id` binary found"), "{err}"); + assert!(err.contains("refusing PATH resolution"), "{err}"); + for path in paths { + assert!(err.contains(path), "{err}"); + } + } } #[test] diff --git a/src/test_util.rs b/src/test_util.rs index 8ffb811..166b909 100644 --- a/src/test_util.rs +++ b/src/test_util.rs @@ -4,6 +4,13 @@ pub(crate) mod aad_fixture; pub(crate) mod pty; pub(crate) mod temp_dir; +/// Whether `/` is owned by root or the current effective user. +pub(crate) fn root_has_trusted_owner() -> bool { + use std::os::unix::fs::MetadataExt as _; + let owner = std::fs::metadata("/").expect("stat filesystem root").uid(); + owner == 0 || owner == rustix::process::geteuid().as_raw() +} + /// Process-wide lock serializing every unit test that mutates — or /// wholesale snapshots — the process-global environment. The test /// harness runs tests in parallel threads of one process, so