diff --git a/.cargo/audit.toml b/.cargo/audit.toml new file mode 100644 index 00000000..c5dbca07 --- /dev/null +++ b/.cargo/audit.toml @@ -0,0 +1,16 @@ +# cargo-audit configuration. +# +# This file exists so `cargo audit` and `cargo deny check advisories` reach the +# same verdict. It mirrors `deny.toml`'s `[advisories].ignore` list exactly; +# `scripts/check-advisories.sh` fails if the two sets differ. +# +# Policy and rationale: `deny.toml` (the normative source) and +# `plans/adrs/ADR-0003-advisory-remediation-and-suppression-policy.md`. +# Remove an entry here in the same change that adopts the fixed release. +[advisories] +ignore = [ + "RUSTSEC-2026-0459", + "RUSTSEC-2026-0370", + "RUSTSEC-2026-0371", + "RUSTSEC-2026-0372", +] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 722124a4..2d18ce8e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,5 +1,14 @@ name: CI +# Action pinning policy +# -------------------- +# Every third-party action is pinned to a full 40-character commit SHA with a +# trailing `# vX.Y.Z` comment. The comment is load-bearing: Dependabot's +# `github-actions` entry (`.github/dependabot.yml`) updates the SHA and the +# comment together, so the pin stays reviewable. Never replace a pin with a +# mutable tag or branch. See +# `plans/implementation/security-assurance/002-ci-advisory-gates-and-action-pinning.md`. + on: push: branches: [main] @@ -17,13 +26,32 @@ env: CARGO_TERM_COLOR: always jobs: + advisory-gate: + name: Advisory and license gate + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + # Prebuilt binaries keep the job short; the tool versions are exact and + # must match the versions recorded in the milestone closure evidence. + - uses: taiki-e/install-action@ab49d3c64680143e184118bed66a46419fc15519 # v2.90.5 + with: + tool: cargo-audit@0.23.0,cargo-deny@0.20.2 + # The gate itself lives in the repository so local and CI verdicts agree + # by construction. No `continue-on-error`, no retry loop: a failure here + # must fail the pull request. + - name: Advisory and license policy + run: bash scripts/check-advisories.sh + linux-correctness: name: Linux correctness runs-on: ubuntu-latest timeout-minutes: 35 steps: - - uses: actions/checkout@v5 - - uses: dtolnay/rust-toolchain@stable + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable branch as of 2026-11-17 with: toolchain: "1.94" components: rustfmt, clippy @@ -38,7 +66,7 @@ jobs: sleep 10 done sudo apt-get install -y --no-install-recommends libdbus-1-dev pkg-config - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@2201cc584a476d1b508be977bbe4b7d1c7a52e9c # v2.9.3 - name: Linux checks run: bash scripts/check.sh @@ -51,11 +79,11 @@ jobs: matrix: os: [macos-latest, windows-latest] steps: - - uses: actions/checkout@v5 - - uses: dtolnay/rust-toolchain@stable + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable branch as of 2026-11-17 with: toolchain: "1.94" - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@2201cc584a476d1b508be977bbe4b7d1c7a52e9c # v2.9.3 - name: Check workspace run: cargo check --workspace --all-targets - name: CLI/platform smoke diff --git a/.github/workflows/distribution-consumer-smoke.yml b/.github/workflows/distribution-consumer-smoke.yml index 621266e9..2420329a 100644 --- a/.github/workflows/distribution-consumer-smoke.yml +++ b/.github/workflows/distribution-consumer-smoke.yml @@ -1,5 +1,9 @@ name: Distribution consumer smoke +# Action pinning policy: third-party actions are pinned to full commit SHAs with +# a trailing `# vX.Y.Z` comment so Dependabot can keep them current. See +# `plans/implementation/security-assurance/002-ci-advisory-gates-and-action-pinning.md`. + on: workflow_dispatch: inputs: @@ -62,7 +66,7 @@ jobs: SNP_VERSION: ${{ inputs.snp_version }} SYNC_VERSION: ${{ inputs.snip_sync_version }} steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Install public snp release asset if: ${{ inputs.snp_version != '' }} shell: bash @@ -107,7 +111,7 @@ jobs: SNP_VERSION: ${{ inputs.snp_version }} SYNC_VERSION: ${{ inputs.snip_sync_version }} steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Install public snp release asset if: ${{ inputs.snp_version != '' }} shell: bash @@ -152,7 +156,7 @@ jobs: SNP_VERSION: ${{ inputs.snp_version }} SYNC_VERSION: ${{ inputs.snip_sync_version }} steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Install public snp release asset if: ${{ inputs.snp_version != '' }} shell: bash @@ -197,7 +201,7 @@ jobs: SNP_VERSION: ${{ inputs.snp_version }} SYNC_VERSION: ${{ inputs.snip_sync_version }} steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Install public snp release asset if: ${{ inputs.snp_version != '' }} shell: bash @@ -242,7 +246,7 @@ jobs: SNP_VERSION: ${{ inputs.snp_version }} SYNC_VERSION: ${{ inputs.snip_sync_version }} steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Install public snp release asset if: ${{ inputs.snp_version != '' }} shell: pwsh @@ -299,7 +303,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Exercise exact README default snp bootstrap shell: bash run: | @@ -330,7 +334,7 @@ jobs: runs-on: ubuntu-24.04-arm timeout-minutes: 10 steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Exercise exact README default snp bootstrap shell: bash run: | diff --git a/.github/workflows/link-check.yml b/.github/workflows/link-check.yml index aa1e634e..2eb08270 100644 --- a/.github/workflows/link-check.yml +++ b/.github/workflows/link-check.yml @@ -15,7 +15,7 @@ jobs: name: Markdown link check runs-on: ubuntu-latest steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Check links in README and the user guide uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0 with: diff --git a/.github/workflows/release-binaries.yml b/.github/workflows/release-binaries.yml index 2c5a0427..3efc1ee1 100644 --- a/.github/workflows/release-binaries.yml +++ b/.github/workflows/release-binaries.yml @@ -1,5 +1,9 @@ name: Release binaries +# Action pinning policy: third-party actions are pinned to full commit SHAs with +# a trailing `# vX.Y.Z` comment so Dependabot can keep them current. See +# `plans/implementation/security-assurance/002-ci-advisory-gates-and-action-pinning.md`. + on: push: tags: @@ -45,7 +49,7 @@ jobs: mode: ${{ steps.validate.outputs.mode }} steps: - name: Check out the requested tag - uses: actions/checkout@v5 + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 with: # For workflow_dispatch, github.ref is the branch containing this # workflow, so the explicit tag input must take precedence. @@ -140,13 +144,13 @@ jobs: steps: - name: Check out the validated tag - uses: actions/checkout@v5 + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 with: ref: ${{ needs.preflight.outputs.tag }} fetch-depth: 0 - name: Install Rust toolchain and target - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable branch as of 2026-11-17 with: toolchain: ${{ env.RUST_TOOLCHAIN }} targets: ${{ matrix.target }} @@ -161,7 +165,7 @@ jobs: - name: Install pinned Zig if: runner.os == 'Linux' - uses: goto-bus-stop/setup-zig@abea47f85e598557f500fa1fd2ab7464fcb39406 + uses: goto-bus-stop/setup-zig@abea47f85e598557f500fa1fd2ab7464fcb39406 # v2.2.1 with: version: ${{ env.ZIG_VERSION }} @@ -415,7 +419,7 @@ jobs: } - name: Upload verified staged artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: release-${{ matrix.target }} path: dist/ @@ -428,7 +432,7 @@ jobs: runs-on: ubuntu-24.04 steps: - name: Download staged artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: pattern: release-* path: dist @@ -469,7 +473,7 @@ jobs: fi - name: Preserve verified asset set for optional attachment - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: release-aggregate path: dist/ @@ -485,7 +489,7 @@ jobs: contents: write steps: - name: Download verified aggregate - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: release-aggregate path: dist diff --git a/.gitignore b/.gitignore index 673f6201..a0fd5d70 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,9 @@ # But allow committing .cargo/config.toml (needed for Windows stack size, etc.) !/.cargo/config.toml !/.cargo/config +# cargo-audit reads this so its verdict matches `cargo deny check`; the advisory +# gate is only reproducible if the suppression list is committed. +!/.cargo/audit.toml # Rust documentation files **/*.html diff --git a/.skills/encryption-module.md b/.skills/encryption-module.md index 83d81884..fdba8f55 100644 --- a/.skills/encryption-module.md +++ b/.skills/encryption-module.md @@ -18,7 +18,7 @@ const ARGON2_PARALLELISM: u32 = 4; // 4 threads — matches typical desktop CPU Memory cost is `1 << 14` (16 MiB), time cost 3, parallelism 4 (`src/encryption.rs:37-39`). -**WARNING**: Changing Argon2 parameters is a **breaking change**. All existing encrypted snippets will fail to decrypt because the same salt + different parameters produces a different derived key. If changing, add parameter versioning to `EncryptedPayload` (1-byte version header) and support decrypting with old parameters for backward compatibility. +**WARNING**: Changing Argon2 parameters is a **breaking change**. All existing encrypted snippets would fail to decrypt because the same salt + different parameters produces a different derived key. The payload already carries a 1-byte version header that selects the parameters (`argon2_params_for_version`), so a parameter change must introduce a **new version** with the old parameters retained for reading — never retune an existing version in place. See [`architecture/encryption.md`](../architecture/encryption.md) § Versioning Constraint. ## Key Derivation @@ -121,9 +121,12 @@ Derived keys are cached per-session to avoid re-running Argon2id for the same (a ## Known Limitations 1. Key material persists in AES-GCM cipher key schedule (not zeroized) -2. No parameter versioning — changing Argon2 constants breaks all stored data +2. Retuning an existing payload version's Argon2 parameters breaks all stored + data — a parameter change needs a new version instead 3. `DerivedKey` implements `Zeroize` but the copy inside `Aes256Gcm` is not zeroized 4. No streaming API — entire plaintext/ciphertext must fit in memory +5. Payload version 2 (id-bound AAD) is **read-only** in this build; the write + switch is release-gated. Do not document it as an active protection. ## Tests diff --git a/.skills/planning.md b/.skills/planning.md index 7824e89f..482186fd 100644 --- a/.skills/planning.md +++ b/.skills/planning.md @@ -105,7 +105,8 @@ Pre-convention `Status: complete` in promoted flat plans maps to `closed`. Stable subsystem names: `distribution-release`, `server-lifecycle-http`, `updater-transport`, `cli-library-sync-consolidation`, `mcp-integration`, `eggstack-dependency-refresh`, `maintenance-consolidation`, -`locking-convergence`, `snippet-crud-surface`, `sync-cursor-protocol`. +`locking-convergence`, `snippet-crud-surface`, `sync-cursor-protocol`, +`security-assurance`. ## Work classification diff --git a/Cargo.lock b/Cargo.lock index 0c7cc545..10fa49de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -71,15 +71,6 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - [[package]] name = "anstyle" version = "1.0.14" @@ -167,9 +158,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.14.0" +version = "1.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" dependencies = [ "async-task", "concurrent-queue", @@ -520,29 +511,15 @@ checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chacha20" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", "cpufeatures 0.3.0", "rand_core 0.10.1", ] -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - [[package]] name = "cipher" version = "0.4.4" @@ -827,9 +804,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.2" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ "cmov", ] @@ -1627,30 +1604,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" version = "2.3.0" @@ -2914,9 +2867,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 2.13.1", "errno", @@ -2927,9 +2880,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.43" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "log", "once_cell", @@ -2963,9 +2916,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.14" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0527518605e68109d875e248ea259b6758801cf165e4b2c2733ae3b51f12535a" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "ring", "rustls-pki-types", @@ -3261,7 +3214,6 @@ dependencies = [ "arboard", "argon2", "base64 0.23.1", - "chrono", "clap", "clap_complete", "clipboard-win", @@ -3314,11 +3266,10 @@ dependencies = [ [[package]] name = "snip-sync" -version = "0.1.8" +version = "0.2.0" dependencies = [ "argon2", "base64 0.23.1", - "chrono", "clap", "clap_complete", "dirs", @@ -3337,6 +3288,7 @@ dependencies = [ "subtle", "tempfile", "thiserror 2.0.21", + "time", "tokio", "tokio-stream", "toml", @@ -3388,7 +3340,6 @@ dependencies = [ "base64 0.22.1", "bytes", "cfg-if", - "chrono", "crc", "crossbeam-queue", "either", @@ -3462,7 +3413,6 @@ dependencies = [ "bitflags 2.13.1", "byteorder", "bytes", - "chrono", "crc", "digest 0.11.3", "dotenvy", @@ -3490,7 +3440,6 @@ dependencies = [ "base64 0.22.1", "bitflags 2.13.1", "byteorder", - "chrono", "crc", "dotenvy", "etcetera", @@ -3523,7 +3472,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "488e99c397a62007e4229aec669a179816339afc6d2620ca6fa420dbee2e982c" dependencies = [ "atoi", - "chrono", "flume", "form_urlencoded", "futures-channel", @@ -3660,7 +3608,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", "windows-sys 0.61.2", @@ -4343,14 +4291,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.9", + "webpki-roots 1.0.12", ] [[package]] name = "webpki-roots" -version = "1.0.9" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" dependencies = [ "rustls-pki-types", ] @@ -4455,41 +4403,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "windows-link" version = "0.2.1" @@ -4509,24 +4422,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - [[package]] name = "windows-sys" version = "0.52.0" @@ -4716,9 +4611,9 @@ dependencies = [ [[package]] name = "zbus-secret-service-keyring-store" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ccede190ba363386a24e8021c7f3848393976609ec9f5d1f8c6c09ef37075b4" +checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" dependencies = [ "keyring-core", "secret-service", @@ -4742,9 +4637,9 @@ dependencies = [ [[package]] name = "zbus_names" -version = "4.3.4" +version = "4.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" dependencies = [ "serde", "winnow", @@ -4848,9 +4743,9 @@ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" [[package]] name = "zvariant" -version = "5.14.0" +version = "5.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e28c25bd8bb8da5a1f3e7065d0c156b9ee9a7973adf78b0e35eaefdf3b1b5c" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" dependencies = [ "endi", "enumflags2", @@ -4863,9 +4758,9 @@ dependencies = [ [[package]] name = "zvariant_derive" -version = "5.14.0" +version = "5.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d496a145685283b67e232bd9e47377f6b60ad9d51e3601b23867f77c42477f96" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -4876,9 +4771,9 @@ dependencies = [ [[package]] name = "zvariant_utils" -version = "4.0.0" +version = "4.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "629d80ece222cad20fe0e8741be493c4ab166acf3b85341bdc2cdbcfd8f3c2d6" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 6582d6a6..e8a4b418 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -141,7 +141,6 @@ fuzzy-matcher = "0.3" tracing = "0.1" tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "registry", "env-filter"] } tracing-appender = "0.2" -chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } thiserror = "2" tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] } uuid = { version = "1", features = ["v4"] } @@ -157,7 +156,7 @@ zeroize = { version = "1", features = ["derive"] } keyring = "4" crc32fast = "1.4" sha2 = "0.11" -time = ">=0.3.36, <0.4" +time = { version = ">=0.3.36, <0.4", features = ["formatting", "macros", "local-offset"] } unicode-width = "0.2" shell-words = "1.1" tempfile = "3.10" @@ -173,7 +172,7 @@ futures-util = { version = "0.3", default-features = false, features = ["alloc"] [dev-dependencies] tempfile = "3.10" subtle = "2" -snip-sync = { version = "0.1.8", path = "snip-sync", features = ["test-helpers"] } +snip-sync = { version = "0.2.0", path = "snip-sync", features = ["test-helpers"] } portable-pty = "0.9" libc = "0.2" crc32fast = "1.4" diff --git a/SECURITY.md b/SECURITY.md index cc8b8f26..ccca59ba 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,12 +2,17 @@ ## Supported Versions -| Version | Supported | -| ------- | ------------------ | -| 1.3.x | :white_check_mark: | -| 1.2.x | :white_check_mark: | -| 1.1.x | :white_check_mark: | -| < 1.1 | :x: | +| Version | Supported | Notes | +| ------- | ------------------ | ----- | +| 1.4.x | :white_check_mark: | Full support | +| 1.3.x | :warning: | Security fixes only | +| < 1.3 | :x: | Unsupported | + +The table always includes the version in the repository's `Cargo.toml`; if it +does not, this document is stale. Security fixes are backported one minor +release behind the current line. Payload-format compatibility across devices is +a separate, stricter contract and is stated in +[Sync Encryption](#sync-encryption). ## Threat Model @@ -33,8 +38,9 @@ body (`description`, `command`, `tags`) is encrypted; routing metadata (`id`, timestamps, `device_id`, `deleted`) travels in the clear — see [Sync Encryption](#sync-encryption). -- **Algorithm:** AES-256-GCM (authenticated encryption with - associated data). +- **Algorithm:** AES-256-GCM (an AEAD cipher). Payload version 1 does not use + associated data; version 2 binds the ciphertext to the snippet id. See + [Sync Encryption](#sync-encryption) for the version support matrix. - **Key derivation:** Argon2id with 16 MiB memory cost, 3 iterations, and 4 degrees of parallelism (OWASP-recommended parameters). The encryption key is derived from the API key and a per-payload random @@ -79,8 +85,14 @@ they are passed through file descriptors or environment variables only. ### Supply Chain -- `cargo deny check` (via `deny.toml`) is the local supply-chain gate for - known security advisories and license compliance; it does not run in CI. +- `scripts/check-advisories.sh` is the supply-chain gate. It runs `cargo audit` + and `cargo deny check` over the committed `Cargo.lock`, and fails if the local + suppression lists drift from this document. +- The same script runs in CI on every push and pull request to `main` + (`.github/workflows/ci.yml`, `advisory-gate`), so a new advisory fails a pull + request instead of reaching a release. Tool versions are pinned. +- Third-party workflow actions are pinned to full commit SHAs with a version + comment; Dependabot keeps them current. - Locked `Cargo.lock` files ensure reproducible builds and prevent silent dependency version changes. @@ -149,25 +161,74 @@ checksum of the downloaded archive before extraction. Archive entries are validated: absolute paths, parent-directory traversal, symlinks, and hard links are rejected. HTTPS-only downloads prevent MITM attacks. +**Limitation:** the checksum is fetched from the same origin as the archive and +is not signed. There is no release signature or attestation, so an attacker who +controls the release channel can serve a matching archive and checksum. The +check defends against in-transit corruption and partial compromise of the +channel; it does not establish publisher identity. + ### Sync Encryption -- **In transit:** Snippet **content** is encrypted client-side with - **AES-256-GCM** before being sent to the server; the server stores only - ciphertext for those fields. Per-snippet metadata — `id`, `created_at`, - `updated_at`, `device_id`, `deleted` — is sent as **plaintext** proto fields, - because the server needs it for merge ordering and deletion tombstones. `output` - is local-only and is never sent. So a compromised server cannot read snippet - content, but it can see snippet identifiers, timestamps, and deletion state. -- **Key derivation:** Per-snippet **Argon2id** (16 MiB memory, 3 - iterations, 4 threads — OWASP-recommended parameters) derives an - encryption key from the API key and a per-payload random salt. -- **API keys:** Stored in the OS keychain (macOS Keychain, GNOME +Read this as three separate statements, because they have three different +strengths. + +**1. What is encrypted.** Snippet *content* — `description`, `command`, and +`tags` — is encrypted client-side with **AES-256-GCM** before it leaves the +device, and the server stores only ciphertext for those fields. Per-snippet +metadata is **plaintext** by design: `id`, `created_at`, `updated_at`, +`device_id`, and `deleted` are proto fields the server needs for merge ordering +and deletion tombstones. `output` is local-only and never sent. The key is +derived with **Argon2id** (16 MiB memory, 3 iterations, 4 lanes — OWASP +recommended parameters) from the API key and a per-payload random salt. + +**2. What the server can do.** A server that stores ciphertext and never sees +the key cannot decrypt the content it holds. That is *not* the current +deployment model: clients send the API key as a bearer token in gRPC +`authorization` metadata on every request, so the server, a TLS-terminating +proxy, or a request log that observes the token can re-derive the same Argon2id +key and decrypt — and re-encrypt — any payload it holds or relays. The +protection this design actually provides is **transport confidentiality plus +at-rest obfuscation of snippet bodies, not server-blindness**. Treat a sync +server as a party that can read and modify your snippet content; trust it for +availability and for not leaking what it stores, not for confidentiality from +itself. + +**3. What the authentication tag proves.** The GCM tag proves that a party +*without* the key did not modify the ciphertext: tampering by a key-blind +party fails. It does not prevent a key holder from forging content — a party +with the key can seal any plaintext it likes. It also does not bind the +ciphertext to the snippet row it is stored under until payload version 2 is +written; see the version matrix below. + +**Payload version support matrix:** + +| Payload version | Read | Written | Binds ciphertext to snippet id | +| --------------- | ---- | ------- | ------------------------------ | +| 0 (legacy, pre-magic) | Yes | No | No | +| 1 | Yes | Yes | No | +| 2 | Yes | Not yet | Yes (AAD over the snippet id) | + +Version 1 payloads remain readable indefinitely; no stored payload is ever +rewritten. Version 2 read support exists so a later release can switch the write +path once the fleet can read it — until that write switch ships, every payload +on the wire is still version 1 and the id binding is *not* in effect. The +decision and the two-phase rollout are recorded in +[ADR-0002](plans/adrs/ADR-0002-encryption-payload-identity-binding.md); the +implementation-level description is +[`architecture/encryption.md`](architecture/encryption.md). + +**Other properties:** + +- **API keys at rest:** Stored in the OS keychain (macOS Keychain, GNOME Keyring, Windows Credential Manager) by default. Fall back to a plaintext `sync.toml` only when `SNP_ALLOW_PLAINTEXT_API_KEY=true` - is set; a warning is emitted at runtime. -- **Integrity:** `sync.toml` carries a CRC32 comment line to detect - accidental corruption. This is *not* a cryptographic integrity check - — the threat model assumes local-only access. + is set; a warning is emitted at runtime. That variable is a test-only seam and + has no effect in a production build — see + [Credential Storage](#credential-storage). +- **Transport:** TLS via `https://`. The client rejects plaintext `http://` to + non-loopback hosts unless `SNIP_SYNC_ALLOW_HTTP=true` is set. +- **`sync.toml` integrity:** a CRC32 comment line detects accidental + corruption. This is *not* a cryptographic integrity check. - **Authentication:** Current clients send the API key as a bearer token in gRPC `authorization` metadata. The proto request-body `api_key` fields remain for backward compatibility with older @@ -175,17 +236,53 @@ and hard links are rejected. HTTPS-only downloads prevent MITM attacks. ### Advisory Exceptions -`deny.toml` currently carries no active suppressions (`ignore = []`). Past -suppressions are removed once the upstream crate fixes the advisory — do not -re-add without a fresh exploitability analysis. The server uses -`prometheus 0.14` (text encoder for `/metrics` only). +`deny.toml` is the normative suppression list; `.cargo/audit.toml` mirrors it +so `cargo audit` and `cargo deny check` reach the same verdict. Both are checked +by `scripts/check-advisories.sh`. Every entry is an advisory **ID only** — never +a crate name, version, or wildcard — and carries the rationale block defined by +[ADR-0003](plans/adrs/ADR-0003-advisory-remediation-and-suppression-policy.md): +scope, exploitability analysis, added date, review-by date, and the upstream +condition that removes it. + + + +| Advisory | Crate | Kind | Status | +| -------- | ----- | ---- | ------ | +| `RUSTSEC-2026-0459` | `libsqlite3-sys` (bundled SQLite) | Vulnerability, CVSS 6.8 | Accepted until `sqlx` accepts `libsqlite3-sys >= 0.39.0` | +| `RUSTSEC-2026-0370` | `zvariant` | Unmaintained | Accepted until the Linux keyring chain moves to `zbus 6.x` | +| `RUSTSEC-2026-0371` | `zbus_names` | Unmaintained | Accepted until the Linux keyring chain moves to `zbus 6.x` | +| `RUSTSEC-2026-0372` | `zvariant_derive` | Unmaintained | Accepted until the Linux keyring chain moves to `zbus 6.x` | + +What each exception means in practice: + +- **`RUSTSEC-2026-0459`** is reachable only in the `snip-sync` server binary, and + only with a local vector: an attacker must already be able to write a crafted + database and a sibling `-wal` file next to the server's data. The server data + directory is owner-only on Unix (see + [Local File Permissions](#local-file-permissions)), so an unprivileged local + user cannot meet that precondition. The `snp` client is unaffected. +- **`RUSTSEC-2026-0370`/`0371`/`0372`** are unmaintained notices with no CVE and + no fixed standalone release; the crates were folded into `zbus 6.x`. They are + compiled only for the Linux Secret Service keyring backend and parse D-Bus + traffic from a trusted same-session peer. + +Suppressions are never a destination: an entry is deleted in the same change +that adopts the fixed release, without waiting for its review date. Do not add +an entry without a fresh exploitability analysis, and do not relax +`unmaintained` globally — the gate must keep failing on anything new. + +Check locally with `scripts/check-advisories.sh`; pass `--self-test` to prove the +gate still rejects an unsuppressed advisory. ### Server Deployment If you self-host the `snip-sync` server: -- **Enable TLS in production.** The client refuses to connect over - plaintext HTTP unless `SNIP_SYNC_ALLOW_HTTP=true` is set. +- **Terminate TLS in front of the server.** `snip-sync` does **not** terminate + TLS itself: it builds its gRPC listener without any TLS configuration. + `TLS_ENABLED=true` is an assertion that a reverse proxy terminates TLS for it, + not a switch that enables TLS in the binary. Binding a non-loopback address + without such a proxy serves plaintext. - **Use a reverse proxy** (nginx, traefik, Caddy) to terminate TLS with a real certificate (Let's Encrypt, etc.). - **Use strong, unique API keys.** The server enforces a minimum @@ -199,6 +296,13 @@ If you self-host the `snip-sync` server: - **Restrict metrics endpoint access.** The `/metrics` endpoint returns Prometheus-format data; require basic auth (`[server.metrics]` `username`/`password`) or expose it only on an internal interface. + Repeated failed authentications are rate-limited (`429` with `Retry-After`) + by a process-local failure budget; successful scrapes are never throttled. +- **Keep the data directory private.** On Unix the server creates its data + directory `0o700` and the SQLite database with its `-wal`/`-shm` siblings + `0o600`. An existing broader mode that cannot be tightened produces a startup + warning naming the path and its mode. Windows ACL enforcement is not + implemented; restrict the directory with filesystem permissions yourself. - **Back up the SQLite database** (`snippets.db` by default) using the same backup strategy you would for any user data store. @@ -219,11 +323,29 @@ when the keychain is unavailable. protocol authenticates via API key bearer tokens only. Clients without a valid API key are rejected, but additional client certificate verification is not currently supported. +- **`/health` discloses the exact server version** to any caller that can reach + the endpoint, without authentication. This is intentional fleet diagnostics; + hide the endpoint behind your proxy if that disclosure matters to you. +- **Update integrity is checksum-only.** The updater verifies a same-origin + SHA-256 sidecar and no signature; a compromised release channel defeats it. +- **Payload identity binding is not yet written.** Payload version 2 binds + ciphertext to the snippet id, and the client can read it, but the write switch + has not shipped — see [Sync Encryption](#sync-encryption). +- **Server data permissions are enforced on Unix only.** Windows deployments + must restrict the data directory themselves. ## Security Audit -For detailed audit findings and the methodology used, refer to -[`docs/SECURITY_AUDIT.md`](docs/archive/SECURITY_AUDIT.md). +[`docs/archive/SECURITY_AUDIT.md`](docs/archive/SECURITY_AUDIT.md) is a +**historical snapshot**, not a current contract: it is archived, and the paths +and line references it cites have moved. It is retained as the record of the +methodology used at the time. + +The current posture is this document plus +[`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md) and the deep dives under +[`architecture/`](architecture/). Dependency findings and their scoped +exceptions are in [Advisory Exceptions](#advisory-exceptions). Any future audit +summary belongs in a new document rather than in the frozen archive. ## Scope diff --git a/architecture/commands/backup_cmd.md b/architecture/commands/backup_cmd.md index 20172b0d..cf7a3988 100644 --- a/architecture/commands/backup_cmd.md +++ b/architecture/commands/backup_cmd.md @@ -45,7 +45,7 @@ The `data` spelling is an alias, not a separate command: `DataCommands::Backup(B 1. **Config directory must exist.** A missing config directory is a hard error (`src/commands/backup_cmd.rs:45-51`) — backup does not create the config tree. 2. **Canonicalize the config directory** (`:52-54`). This becomes the containment root for every source file. -3. **Compute the timestamp and destination** (`:55-59`): `chrono::Utc::now().format("%Y%m%d_%H%M%S")`. +3. **Compute the timestamp and destination** (`:55-59`): `time::OffsetDateTime::now_utc().format("[year][month][day]_[hour][minute][second]")`. 4. **Build the staging directory** (`:60-67`): `final_backup_dir.with_extension(".staging.")`. Because `with_extension` *replaces* the last extension, `…/20260101_120000` becomes `…/20260101_120000.staging.`, while `…/backup.tar.gz` becomes `…/backup.tar.staging.`. The final directory only appears via an atomic rename at the end. 5. **Acquire the local-data lock** (`:72-73`): diff --git a/architecture/encryption.md b/architecture/encryption.md index ff5d4e0b..baa7e593 100644 --- a/architecture/encryption.md +++ b/architecture/encryption.md @@ -68,7 +68,7 @@ ARGON2_TIME_COST, ARGON2_PARALLELISM, Some(32))` with ``` ```rust -// src/encryption.rs:142-150 +// src/encryption.rs pub struct EncryptedPayload { pub version: u8, // payload layout version (0 = legacy, unversioned) pub salt: Vec, // 16 bytes @@ -76,8 +76,8 @@ pub struct EncryptedPayload { pub ciphertext: Vec, // AES-GCM output + auth tag } impl EncryptedPayload { - pub fn to_base64(&self) -> String; // src/encryption.rs:155 - pub fn from_base64(data: &str) -> CryptoResult; // src/encryption.rs:165 + pub fn to_base64(&self) -> String; + pub fn from_base64(data: &str) -> CryptoResult; } ``` @@ -85,34 +85,73 @@ impl EncryptedPayload { 8-byte magic (`SNIP-PAY`) is long enough that a legacy payload — whose first bytes are random salt — cannot be mistaken for a versioned one. -`from_base64` accepts **both** layouts: a payload that starts with the magic -is parsed as versioned (and an unknown version is rejected with -`InvalidData("Unsupported payload version …")`), anything else is parsed as -the legacy unversioned layout. It rejects payloads shorter than 28 bytes -(`SALT_SIZE + NONCE_SIZE`) with `InvalidData("Data too short")`, and -non-base64 input with `InvalidData("Failed to decode base64: …")`. +`from_base64` accepts **all three** layouts: a payload that starts with the +magic is parsed as versioned (versions 1 and 2 are accepted; an unknown version +is rejected with `InvalidData("Unsupported payload version …")`), anything else +is parsed as the legacy unversioned layout (version 0). It rejects payloads +shorter than 28 bytes (`SALT_SIZE + NONCE_SIZE`) with +`InvalidData("Data too short")`, and non-base64 input with +`InvalidData("Failed to decode base64: …")`. -## Key Derivation — `src/encryption.rs:178-227` +### Payload versions and identity binding + +| Version | Header | AAD | Written by this build | Read by this build | +|---------|--------|-----|-----------------------|--------------------| +| 0 | none (`salt ‖ nonce ‖ ct`) | none | no | yes | +| 1 | `magic ‖ 1` | none | **yes** | yes | +| 2 | `magic ‖ 2` | snippet id | no | yes | + +Version 2 authenticates the snippet id as AES-GCM associated data +([ADR-0002](../plans/adrs/ADR-0002-encryption-payload-identity-binding.md)): + +```text +AAD = b"snip-payload-v2\0" ‖ u32_le(id.len()) ‖ id.as_bytes() +``` + +The domain tag separates this use from any future AAD use, and the length +prefix removes concatenation ambiguity (`("ab", "c")` must not hash like +`("a", "bc")`). AAD is public data: it adds no key material and is never +logged. + +Because the AAD is authenticated, a ciphertext sealed for one snippet fails the +tag check when presented under another id. The failure is a plain +`DecryptionFailed` — the same shape as a wrong key — so the error does not +reveal which of the two was wrong. The sync pull path +(`decrypt_snippet`, `src/sync.rs`) supplies the proto row's `id`, and a +substituted row is counted in `server_decrypt_failed_count` and reported in +`skipped_ids` rather than aborting the library. + +**Write path.** This build writes version 1 only. Version 2 read support is the +first phase of a two-phase rollout; the write switch is a separate, +release-gated milestone, because a client that only understands version 1 skips +every version-2 payload. `decrypt` (the identity-less entry point) is compiled +for test builds only and rejects version 2 explicitly, so no production caller +can decrypt a bound payload without supplying its identity. + +The key cache is keyed by `(hashed api_key, base64(salt), version)`, so the +version-2 read path does not disturb version-1 caching or add KDF work: AAD +does not affect key derivation. + +## Key Derivation ```rust fn derive_key(api_key: &str, salt: &[u8], version: u8) -> CryptoResult ``` 1. Select the Argon2id parameters for the payload version - (`argon2_params_for_version`); an unknown version is an error. + (`argon2_params_for_version`); an unknown version is an error. Versions 0, 1, + and 2 all use the same parameters — only the AAD differs. 2. Build the cache key `(SHA-256(api_key) hex, base64(salt), version)`; return - a clone on a hit (`hash_api_key`, `src/encryption.rs:49-58`). The version is - part of the key because two versions may use the same salt with different - KDF parameters. -2. Run Argon2id with the fixed parameters above into `[u8; 32]`. -3. Insert into the session cache (10 000-entry cap, evict-half on overflow) - and return a `DerivedKey`, zeroizing the stack buffer - (`src/encryption.rs:207-226`). - -`DerivedKey` (`src/encryption.rs:102-113`) is `Zeroize + ZeroizeOnDrop + -Default`; callers explicitly `zeroize()` / `drop(mem::take(&mut key))` after -use (`src/encryption.rs:332`, `:359`). Cache keys hash the API key with the -full SHA-256 digest so one user's entry can never collide with another's. + a clone on a hit (`hash_api_key`). The version is part of the key because a + future version may use the same salt with different KDF parameters. +3. Run Argon2id with the fixed parameters above into `[u8; 32]`. +4. Insert into the session cache (10 000-entry cap, evict-half on overflow) + and return a `DerivedKey`, zeroizing the stack buffer. + +`DerivedKey` is `Zeroize + ZeroizeOnDrop + Default`; callers explicitly +`zeroize()` / `drop(mem::take(&mut key))` after use. Cache keys hash the API key +with the full SHA-256 digest so one user's entry can never collide with +another's. ### Versioning Constraint diff --git a/architecture/overview.md b/architecture/overview.md index a26a5d61..46ae4b42 100644 --- a/architecture/overview.md +++ b/architecture/overview.md @@ -42,11 +42,11 @@ variable expansion, an AI-agent (MCP) surface, and optional encrypted multi-device sync against a self-hosted server. > **On "end-to-end encryption":** snippet *bodies* are encrypted with -> AES-256-GCM under an Argon2id-derived key, and the server stores only -> ciphertext it cannot read. But the API key is sent as a `Bearer` token on -> every request (`src/sync.rs:306-314`), so anything that observes that token -> can re-derive the key. The guarantee is transport + at-rest protection, not -> server-blindness. See [encryption.md](encryption.md). +> AES-256-GCM under an Argon2id-derived key, and the server stores and relays +> only ciphertext. But the API key is sent as a `Bearer` token on every request +> (`src/sync.rs`), so the server — or any proxy or log that observes that token +> — can re-derive the key and decrypt. The guarantee is transport + at-rest +> protection, not server-blindness. See [encryption.md](encryption.md). Four things make it unusual, and they are where most of the engineering complexity lives: diff --git a/architecture/proto.md b/architecture/proto.md index 3b00a3a2..e3ff96d3 100644 --- a/architecture/proto.md +++ b/architecture/proto.md @@ -477,7 +477,7 @@ snip-proto → snip-sync → snip-it | Crate | Version | Path dependency | |-------|---------|-----------------| | `snip-proto` | 0.1.4 | — | -| `snip-sync` | 0.1.8 | `snip-proto = { version = "0.1.4", path = "../snip-proto" }` (`snip-sync/Cargo.toml:58`) | +| `snip-sync` | 0.2.0 | `snip-proto = { version = "0.1.4", path = "../snip-proto" }` (`snip-sync/Cargo.toml:58`) | | `snip-it` | 1.4.1 | `snip-proto = { version = "0.1.4", path = "snip-proto" }` (`Cargo.toml:140`) | **A proto change requires bumping `snip-proto`'s version in both diff --git a/architecture/server.md b/architecture/server.md index 8da938fd..9e8683b9 100644 --- a/architecture/server.md +++ b/architecture/server.md @@ -489,7 +489,8 @@ so a legitimate second library can collide with the first. `max_encrypted_payload_length` 1 MiB, `max_description_length` 1024, `max_tags` 50, `max_tag_length` 100, `max_id_length` 128, `max_device_id_length` 128, `max_api_key_length` 512, - `rate_limit_per_minute` 120, `db_max_connections` 5, + `rate_limit_per_minute` 120, `register_per_minute` 10, + `metrics_auth_failures_per_minute` 10, `db_max_connections` 5, `grpc_max_message_size` 4 MiB, `request_timeout_secs` 30. Plaintext snippets require a non-blank command and are capped by `max_command_length`. Encrypted snippets require a non-blank payload but @@ -637,9 +638,19 @@ leaf service built with `eggserve_server::service_fn_head`; only - HTTP auth failures increment the same `snip_sync_auth_failures_total` counter as the gRPC path, so a password-protected `/metrics` is observable under brute force - (`snip-sync/src/http.rs:176-187`). + (`snip-sync/src/http.rs`). +- Failed authentications are also **budgeted** + (`metrics_auth_failures_per_minute`, default 10). Once the budget is + exhausted, further failures return `429` with `Retry-After: 60` and + increment `snip_sync_rate_limit_hits_total`. A `429` deliberately carries + no `WWW-Authenticate` (challenging a throttled caller invites the retry the + budget exists to bound). Correct credentials never consult the budget, so an + attacker cannot deny the operator their own scrape. +- The budget is **global**, not per address: the EggServe HTTP leaf receives + only `RequestHead`, which carries no peer address, so a per-caller budget is + not expressible in the current handler shape. - Disabled metrics is a `404` from the application, not the router - (`snip-sync/src/http.rs:150-156`). + (`snip-sync/src/http.rs`). ### CORS and security headers @@ -708,7 +719,9 @@ spend the budget of a legitimate one: |--------|-----|-------|----------| | pre-auth | `pre-auth:` | `rate_limit_per_minute` × `PRE_AUTH_RATE_LIMIT_MULTIPLIER` (10) | before the API-key lookup | | authenticated | `` | `rate_limit_per_minute` | after a **valid** API key was accepted | -| registration | `register:` | `rate_limit_per_minute` | `register` only (unauthenticated by nature) | +| registration (per peer) | `register:` | `rate_limit_per_minute` | `register` only (unauthenticated by nature) | +| registration (global) | `register-global` | `register_per_minute` (10) | `register` only, after the per-peer bucket | +| metrics authentication | `metrics-auth` | `metrics_auth_failures_per_minute` (10) | failed `/metrics` Basic auth only | The pre-auth bucket only has to bound the cost of the key lookup, so it is generous by design. The authenticated bucket is the per-caller ceiling: only @@ -717,8 +730,19 @@ never lock out a legitimate caller behind the same peer address. `register` gets its own bucket for the same reason — it is unauthenticated and must not consume the authenticated budget. -Over-limit calls return `Status::resource_exhausted` and increment -`snip_sync_rate_limit_hits_total`. +The two global buckets exist because a per-peer budget cannot bound a caller +that rotates addresses. `register-global` caps total account creation (each +successful call inserts a user plus a default library); `metrics-auth` caps +password guessing on the HTTP leaf, which has no peer address available. Both +are separate keys on purpose: exhausting one never denies another, and +`metrics-auth` is failure-only so a valid scrape is never throttled. + +The gRPC service and the HTTP leaf share **one** `Arc` through +`AppState`, so `MAX_ENTRIES` and its eviction remain a single process-wide +bound. + +Over-limit calls return `Status::resource_exhausted` (gRPC) or `429` (HTTP) and +increment `snip_sync_rate_limit_hits_total`. ### Trusted proxies and `x-forwarded-for` diff --git a/architecture/test-infrastructure.md b/architecture/test-infrastructure.md index cd0ca4c9..450942bc 100644 --- a/architecture/test-infrastructure.md +++ b/architecture/test-infrastructure.md @@ -892,7 +892,7 @@ The `snip-it` crate pulls `snip-sync` in as a dev-dependency with the feature already on (`Cargo.toml:166`): ```toml -snip-sync = { version = "0.1.8", path = "snip-sync", features = ["test-helpers"] } +snip-sync = { version = "0.2.0", path = "snip-sync", features = ["test-helpers"] } ``` ### Production Seam Proof diff --git a/architecture/usage.md b/architecture/usage.md index e128a6c1..42f2cf3f 100644 --- a/architecture/usage.md +++ b/architecture/usage.md @@ -107,7 +107,7 @@ last_used_at = 1700000000 | `entries` | array of tables | The single top-level key; `#[serde(default)]`, so an empty file deserializes to an empty index | | `id` | string | The snippet's deterministic ID — `legacy-`, **not** a UUID (`docs/IDENTITY_CONTRACT.md`) | | `use_count` | integer | `u64`, incremented with `saturating_add` (`src/usage.rs:86`) | -| `last_used_at` | integer or absent | Unix epoch **seconds** (`i64`), from `chrono::Utc::now().timestamp()` (`src/usage.rs:84`) | +| `last_used_at` | integer or absent | Unix epoch **seconds** (`i64`), from `time::OffsetDateTime::now_utc().unix_timestamp()` (`src/usage.rs:84`) | > The module doc comment at `src/usage.rs:10-17` matches this format: it shows > `[[entries]]` with `id = "legacy-"`. There is no serde rename on diff --git a/deny.toml b/deny.toml index 2d336d6f..11af4765 100644 --- a/deny.toml +++ b/deny.toml @@ -3,14 +3,75 @@ # use the [output] section to control severity, and the [advisories] # table only needs `ignore` for explicit suppressions. # -# RUSTSEC-2024-0437: uncontrolled recursion / stack overflow in -# `protobuf` 2.28.0, pulled in transitively by `prometheus` 0.13.x. -# The server does not parse untrusted protobuf data on this code path -# (snip-sync only uses prometheus's text encoder for /metrics, and -# protobuf is in the build graph only for `prometheus` itself), so this -# advisory is not exploitable in the snip-it / snip-sync build. -# Track removal once `prometheus` upgrades to `protobuf >= 3.7.2`. -ignore = [] +# Suppression policy: `plans/adrs/ADR-0003-advisory-remediation-and-suppression-policy.md`. +# Every entry is an advisory ID only (never a crate name, version, or wildcard), +# carries the six fields below, and is mirrored in SECURITY.md +# § Advisory Exceptions. `scripts/check-advisories.sh` fails if the two lists +# diverge. Remove an entry in the same change that adopts the fixed release. +# +# There is deliberately no global lint relaxation here (`unmaintained = +# "workspace"` and friends are prohibited): the gate must keep failing on +# anything new. +ignore = [ + # ID: RUSTSEC-2026-0459 + # Scope: bundled SQLite (< 3.54.0) compiled into the `snip-sync` + # server binary through `sqlx` -> `libsqlite3-sys 0.37.0`. + # The `snp` client is not affected; its only `sqlx` edge is a + # dev-dependency, so the bundled C library is absent there. + # Why: Local vector. It requires an attacker who can already write a + # database file and a sibling `-wal` file with a mismatched page + # size next to the victim's server data; the only gain is + # disclosure of uninitialized page-cache memory. The server data + # directory is `0o700` with `0o600` files on Unix, so an + # unprivileged local user cannot satisfy the precondition, and a + # privileged local user is outside the threat model. There is no + # network-reachable path: no client-supplied database file is + # ever opened by the server. + # Added: 2026-11-17 + # Review by: 2027-02-15 + # Remove when: `sqlx` publishes a release that accepts `libsqlite3-sys + # >=0.39.0` (the widening is merged upstream but unreleased); + # cargo tree -i libsqlite3-sys then shows >=0.39.0. + "RUSTSEC-2026-0459", + + # ID: RUSTSEC-2026-0370 + # Scope: `zvariant 5.15.1`, reached only through the Linux keyring + # chain (`keyring` -> `zbus-secret-service-keyring-store` -> + # `secret-service` -> `zbus`). Not compiled on macOS or Windows. + # Why: Unmaintained, not a vulnerability: no CVE, no known defect. + # The crate was folded into `zbus 6.x`; there is no fixed + # standalone release, so "upgrade" means a keyring-major + # migration. It parses only D-Bus traffic from the local + # Secret Service, which is a trusted, same-session peer. + # Added: 2026-11-17 + # Review by: 2027-02-15 + # Remove when: `keyring` ships a release backed by `zbus 6.x` (or another + # maintained Secret Service backend) and the lockfile no longer + # contains `zvariant`. + "RUSTSEC-2026-0370", + + # ID: RUSTSEC-2026-0371 + # Scope: `zbus_names 4.3.5`, same Linux keyring chain as + # RUSTSEC-2026-0370. + # Why: Unmaintained, not a vulnerability. Same trusted-peer + # reasoning: D-Bus name validation on the local session bus. + # Added: 2026-11-17 + # Review by: 2027-02-15 + # Remove when: the same keyring/`zbus 6.x` migration as RUSTSEC-2026-0370 + # removes `zbus_names` from the lockfile. + "RUSTSEC-2026-0371", + + # ID: RUSTSEC-2026-0372 + # Scope: `zvariant_derive 5.15.1`, derive macros for the same Linux + # keyring chain. + # Why: Unmaintained, not a vulnerability. It is a compile-time + # macro crate: it cannot execute in the shipped binary. + # Added: 2026-11-17 + # Review by: 2027-02-15 + # Remove when: the same keyring/`zbus 6.x` migration as RUSTSEC-2026-0370 + # removes `zvariant_derive` from the lockfile. + "RUSTSEC-2026-0372", +] [licenses] # In cargo-deny 0.19+, the global `unlicensed` key was removed; the @@ -19,6 +80,11 @@ ignore = [] allow = [ "MIT", "Apache-2.0", + # Retained by policy, not by need: no crate in the current graph is + # BSD-2-Clause, so `cargo deny` reports it as `license-not-encountered`. + # Kept because the allowlist is a pre-approved policy set for permissive + # licenses, and re-admitting it under time pressure is the worse trade. + # This warning is not a gate. "BSD-2-Clause", "BSD-3-Clause", "ISC", @@ -27,6 +93,10 @@ allow = [ "0BSD", "MPL-2.0", "BSL-1.0", + # Certificate-root data bundle (`webpki-roots`, both the 0.26 and 1.0 + # lines). Permissive data license: it covers a list of root certificates, + # not code that runs. + "CDLA-Permissive-2.0", ] # r-efi is dual-licensed MIT/Apache-2.0/LGPL-2.1-or-later but only diff --git a/docs/SUPPLY_CHAIN_POLICY.md b/docs/SUPPLY_CHAIN_POLICY.md index 13e0dd83..9a26ea36 100644 --- a/docs/SUPPLY_CHAIN_POLICY.md +++ b/docs/SUPPLY_CHAIN_POLICY.md @@ -41,25 +41,32 @@ panic = "abort" ## cargo-deny Configuration The project uses `cargo-deny` (configuration in `deny.toml` at the workspace root) -as a **local supply-chain gate** — it is not a CI step. See -[CI Verification Commands](#ci-verification-commands). +for advisories, licenses, bans, and sources, plus `cargo-audit` with the mirror +configuration in `.cargo/audit.toml`. Both run through +`scripts/check-advisories.sh`, which is a **blocking CI step** +(`.github/workflows/ci.yml`, job `advisory-gate`). The policy for suppressions is +[ADR-0003](../plans/adrs/ADR-0003-advisory-remediation-and-suppression-policy.md). ### Advisory Settings -```toml -[advisories] -ignore = [] -``` +`deny.toml` carries one `ignore` list of bare advisory IDs. Each entry is +preceded by a comment block with `ID`, `Scope`, `Why`, `Added`, `Review by`, and +`Remove when`; `scripts/check-advisories.sh` fails if a field is missing, if an +entry is not a bare `RUSTSEC-*` ID, or if `.cargo/audit.toml` and +`SECURITY.md`'s `advisory-ignore-ids` marker disagree with it. + +Current suppressions (all mitigated, none a permanent destination): -The advisory ignore list is empty — no advisory is suppressed, so any advisory that -`cargo deny check advisories` reports is a hard failure of the local gate. **The -gate does not currently pass**: `cargo deny check` reports open advisories against -`rustls`, `rustls-webpki`, `webpki-roots`, and the unmaintained `zbus_names`, -`zvariant`, and `zvariant_derive` crates. See -[Known Gaps](#cargo-deny-check-currently-fails). If a future advisory cannot be -immediately resolved (e.g., transitive dependency lag), it must be documented with -a rationale, owner, and review date (see -[Advisory Exception Format](#advisory-exception-format)). +| Advisory | Crate | Removal condition | +| -------- | ----- | ----------------- | +| `RUSTSEC-2026-0459` | `libsqlite3-sys` (bundled SQLite, server only) | `sqlx` accepts `libsqlite3-sys >= 0.39.0` | +| `RUSTSEC-2026-0370` | `zvariant` | Linux keyring chain moves to `zbus 6.x` | +| `RUSTSEC-2026-0371` | `zbus_names` | Linux keyring chain moves to `zbus 6.x` | +| `RUSTSEC-2026-0372` | `zvariant_derive` | Linux keyring chain moves to `zbus 6.x` | + +Global lint-level relaxation is prohibited: `unmaintained` advisories must be +listed individually so a **new** unmaintained or vulnerable crate still fails the +gate. ### License Settings @@ -76,6 +83,7 @@ allow = [ "0BSD", "MPL-2.0", "BSL-1.0", + "CDLA-Permissive-2.0", ] ``` @@ -120,17 +128,15 @@ The following licenses are approved for use in the snip-it workspace: | 0BSD | `0BSD` | Zero-clause BSD; minimal restrictions | | Mozilla Public License 2.0 | `MPL-2.0` | File-level copyleft; compatible with MIT | | Boost Software License 1.0 | `BSL-1.0` | Permissive; Rust's Boost Software License, used by `clipboard-win` and `error-code` | +| Community Data License Agreement – Permissive 2.0 | `CDLA-Permissive-2.0` | Permissive **data** license; covers certificate-root bundles (`webpki-roots`), not executable code | Licenses not on this list will cause `cargo deny check licenses` to fail unless explicitly added to the allow list. The list is a policy ceiling, not a snapshot of the resolved graph: `BSD-2-Clause` is currently allowed but not reached by any crate in the resolved graph, and `cargo deny` reports it as an unmatched -allowance. - -The allow list also does not cover every license present in `Cargo.lock`: -`webpki-roots` (pulled in by `eggfetch-core`) is `CDLA-Permissive-2.0`, which is -not on the list and therefore fails the license check. See -[Known Gaps](#cargo-deny-check-currently-fails). +allowance. That warning is not a gate and the entry is retained deliberately, so +the next crate that needs it does not require a policy change under time +pressure. --- @@ -192,7 +198,7 @@ All dependencies must come from crates.io (the only allowed registry). Git depen |-------|---------|-------------| | `snip-it` | 1.4.1 | Main binary crate (`snp`). CLI, TUI, sync client, encryption, auto-sync. | | `snip-proto` | 0.1.4 | Protobuf definitions and tonic-generated gRPC code. | -| `snip-sync` | 0.1.8 | gRPC sync server (EggServe HTTP leaf + tonic gRPC, SQLite storage). | +| `snip-sync` | 0.2.0 | gRPC sync server (EggServe HTTP leaf + tonic gRPC, SQLite storage). | All three crates share the same license (MIT), Rust edition (2024), and minimum supported Rust version (1.94). @@ -220,63 +226,69 @@ Other notable dependencies include `serde`/`toml` for configuration persistence, ## CI Verification Commands -Linux CI runs `bash scripts/check.sh`: installer contract, `cargo fmt --all -- --check`, -`cargo clippy --workspace --all-targets -- -D warnings` (NOT `--all-features`), -`cargo test --workspace --lib`, plus focused integration targets with -`--features test-support` (see `AGENTS.md`). `cargo deny check` is a local -supply-chain gate via `deny.toml`, not a CI step. +Linux CI runs two independent jobs in `.github/workflows/ci.yml`: + +- `advisory-gate` — `bash scripts/check-advisories.sh`, with `cargo-audit` and + `cargo-deny` installed at exact pinned versions. It fails on an unexpected + advisory, a missing rationale field, or a suppression-list mismatch. +- `linux-correctness` — `bash scripts/check.sh`: installer contract, + `cargo fmt --all -- --check`, + `cargo clippy --workspace --all-targets -- -D warnings` (NOT `--all-features`), + `cargo test --workspace --lib`, plus focused integration targets with + `--features test-support` (see `AGENTS.md`). + +`macos-latest` and `windows-latest` run `cargo check --workspace --all-targets` +and `platform_smoke`; Windows additionally runs the PowerShell installer contract. + +Locally, `bash scripts/check-advisories.sh --self-test` additionally proves the +gate still fails with one suppression removed. --- ## Advisory Exception Format -If a security advisory must be temporarily ignored (e.g., waiting for an upstream fix), the following metadata is required in `deny.toml`: +If a security advisory cannot be resolved immediately (for example, a transitive +dependency has not widened its version bound yet), it is suppressed by **bare +advisory ID** in `deny.toml`, with a comment block immediately above it: ```toml -[advisories] -ignore = [ - { - id = "RUSTSEC-YYYY-NNNN", - reason = "Short description of why this advisory is not exploitable or is safe to ignore", - owner = "GitHub username or team responsible", - review_date = "YYYY-MM-DD" - } -] + # ID: RUSTSEC-YYYY-NNNN + # Scope: which crate and which build unit is affected + # Why: exploitability analysis (attack vector, preconditions, blast radius) + # Added: YYYY-MM-DD + # Review by: YYYY-MM-DD (<= 90 days) + # Remove when: the concrete upstream condition that ends the exception + "RUSTSEC-YYYY-NNNN", ``` -Each entry must include: +Every entry must supply all six fields. `scripts/check-advisories.sh` enforces +their presence and rejects anything that is not a bare advisory ID — crate names, +version ranges, and wildcards are not permitted, because those would silently +cover future unrelated findings. The same ID must appear in +`.cargo/audit.toml` and in `SECURITY.md`'s `advisory-ignore-ids` marker. -- **id:** The RUSTSEC advisory identifier. -- **reason:** A clear explanation of why the advisory does not affect this project (e.g., the vulnerable code path is not reachable, the dependency is not used in production, or an upgrade is in progress). -- **owner:** The person or team responsible for resolving or re-evaluating the exception. -- **review_date:** The date by which the exception must be re-evaluated. - -Exceptions without all four fields are not accepted. +`cargo-deny` does not accept structured tables inside `ignore`; the rationale +lives in comments by design. An exception is removed in the same change that +adopts the fixed release, without waiting for its review date. --- ## Known Gaps -### `cargo deny check` Currently Fails - -The local supply-chain gate does not currently pass. As of the last review, -`cargo deny check` reports: - -- **Advisories (9 open):** `rustls 0.23.43` - (RUSTSEC-2026-0285, RUSTSEC-2026-0346, RUSTSEC-2026-0348, RUSTSEC-2026-0349), - `rustls-webpki 0.103.14` (RUSTSEC-2026-0382), `webpki-roots 1.0.9` - (RUSTSEC-2026-0381), and the unmaintained crates `zbus_names` - (RUSTSEC-2026-0371), `zvariant` (RUSTSEC-2026-0370), and `zvariant_derive` - (RUSTSEC-2026-0372). -- **Licenses:** `webpki-roots` is `CDLA-Permissive-2.0`, which is not on the - license allow list (it reaches the workspace through `eggfetch-core`). - -`bans` and `sources` pass. Because `cargo deny` is a local gate and not a CI -step, this failure does not block a merge — it is a standing gap, not a -regression detector. Resolve it by upgrading the affected crates, by extending -the license allow list with a documented rationale, or by adding an explicit -advisory exception with an owner and review date (see -[Advisory Exception Format](#advisory-exception-format)). +### Advisory Suppressions Awaiting Upstream + +`cargo audit` and `cargo deny check` pass, but only because four advisory IDs are +suppressed with named removal conditions (see +[Advisory Settings](#advisory-settings)). The accepted residual risk is the +bundled SQLite vulnerability in the `snip-sync` server binary; its local attack +vector is blocked by owner-only server data permissions on Unix. The actual +findings, rationale, and review dates are in `deny.toml` and +`SECURITY.md` § Advisory Exceptions — this document does not duplicate them, so +it cannot drift. + +The removal conditions are upstream facts. If `sqlx` publishes a release that +accepts `libsqlite3-sys >= 0.39.0`, or the `keyring` chain adopts `zbus 6.x`, +the corresponding entries are deleted rather than re-reviewed. ### No SBOM Generation diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 9ecebf76..8e28388a 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -126,12 +126,14 @@ production build. **Description:** The local gRPC client communicates with the snip-sync server. -**Properties:** Snippet *content* is end-to-end encrypted — the server never sees plaintext commands, descriptions, or tags. Snippet *metadata* is not: `id`, `created_at`, `updated_at`, `device_id`, and `deleted` are sent as plaintext proto fields, because the server needs them for merge ordering and deletion tombstones. `output` is local-only and never leaves the device. Bearer token in gRPC metadata. TLS via `https://` URLs; plaintext `http://` is rejected for non-loopback hosts in the client. +**Properties:** Snippet *content* is encrypted in transit and at rest — the server stores and relays only ciphertext commands, descriptions, and tags — but the server receives the bearer API key on every request and is therefore **not blind** to content it holds or relays. Snippet *metadata* is plaintext by design: `id`, `created_at`, `updated_at`, `device_id`, and `deleted` are proto fields the server needs for merge ordering and deletion tombstones. `output` is local-only and never leaves the device. Bearer token in gRPC metadata. TLS via `https://` URLs; plaintext `http://` is rejected for non-loopback hosts in the client. **Mitigations:** AES-256-GCM encryption with random nonces, TLS via `https://`, client-side loopback check rejecting plaintext to non-loopback hosts, `SNIP_SYNC_ALLOW_HTTP` env var overrides the loopback check (loopback hosts are always allowed), server stores Argon2id hashes of API keys (not plaintext). **Trust boundary note:** the API key itself reaches the server as a `Bearer` token on every request, so the server is not blind to the key it could use to decrypt. The precise trust statement lives in [architecture/encryption.md](../architecture/encryption.md); see [T3](#t3-compromised--malformed-sync-server) for the residual risk. +**Disclosure note:** the server's unauthenticated `/health` endpoint returns its exact version. This is deliberate fleet diagnostics; a version string is not a secret and does not enable an attack by itself, but it lets a caller correlate a deployment with published advisories. Operators who consider that unacceptable should restrict the endpoint at the proxy. + ### Boundary 7: Local Archive Restore **Description:** Restoring from a local backup archive. @@ -220,7 +222,7 @@ cryptographic signature is verified — see [Boundary 10](#boundary-10-ci--relea | **Description** | The sync server is compromised, returns malformed responses, or is impersonated. It could attempt to serve crafted encrypted payloads or harvest credentials. | | **Attack vector** | Server-side compromise, DNS hijacking (with invalid TLS policy), or supply-chain attack on server deployment. | | **Mitigations** | Snippet *content* is encrypted client-side with AES-256-GCM and random 12-byte nonces, so the server never stores or relays plaintext commands, descriptions, or tags; authentication tag verification on decryption rejects tampered ciphertext. The API key is Argon2id-hashed server-side (server never stores plaintext). TLS required for non-loopback connections. | -| **Residual risk** | Medium. A compromised server *does* learn per-snippet metadata — `id`, `created_at`, `updated_at`, `device_id`, `deleted` — plus record counts and rough payload sizes, because those fields are plaintext proto fields, not envelope headers. It also learns library names and which snippets were deleted when. Because the client sends the API key as a `Bearer` token on every request, a server (or a TLS-terminating proxy) that observes it can re-derive the same Argon2id key and decrypt any payload it holds or relays — the guarantee is transport confidentiality and at-rest obfuscation of snippet bodies, not server-blindness (see [architecture/encryption.md](../architecture/encryption.md)). It cannot forge content: the GCM tag rejects it. Denial of service is possible. | +| **Residual risk** | Medium. A compromised server *does* learn per-snippet metadata — `id`, `created_at`, `updated_at`, `device_id`, `deleted` — plus record counts and rough payload sizes, because those fields are plaintext proto fields, not envelope headers. It also learns library names and which snippets were deleted when. Because the client sends the API key as a `Bearer` token on every request, a server (or a TLS-terminating proxy) that observes it can re-derive the same Argon2id key and decrypt any payload it holds or relays — the guarantee is transport confidentiality and at-rest obfuscation of snippet bodies, not server-blindness (see [architecture/encryption.md](../architecture/encryption.md)). A party **with** the key can also produce valid ciphertext for any plaintext, so the GCM tag prevents forgery only by parties **without** the key; content integrity against a key holder is not provided. Payload version 1 does not bind ciphertext to a snippet id, so a key-blind party that can move stored ciphertext between rows can make content appear under a different id; version 2 adds that binding and is read-capable but not yet written ([ADR-0002](../plans/adrs/ADR-0002-encryption-payload-identity-binding.md), closing in the security-assurance workstream's M005/M006). Denial of service is possible. | | **User responsibility** | Verify your sync server URL is correct. Use a trusted server deployment. | | **Tests / evidence** | `tests/sync_integration.rs`, `tests/sync_contracts.rs`. Encryption unit tests in `src/encryption.rs`. | | **Owner / module** | `src/sync.rs`, `src/sync_commands.rs`, `src/encryption.rs`, `src/config/` | @@ -339,10 +341,10 @@ cryptographic signature is verified — see [Boundary 10](#boundary-10-ci--relea |-------|--------| | **Description** | A crate dependency is compromised, introducing malicious code into the build or runtime. | | **Attack vector** | Malicious crate publication, typosquatting, maintainer account compromise. | -| **Mitigations** | `cargo-deny` enforces license and advisory checks via `deny.toml` — a **local** gate, not a CI step; its current status is tracked in `docs/SUPPLY_CHAIN_POLICY.md`. Locked builds via `Cargo.lock`. Unknown registries and git sources are denied. | -| **Residual risk** | Low. `cargo-deny` and lockfiles reduce but do not eliminate supply-chain risk. A compromised transitive dependency that passes `cargo-deny` checks could still introduce vulnerabilities. Because the gate is not run in CI, it does not block a merge on its own. | +| **Mitigations** | `cargo audit` and `cargo deny check` enforce advisory and license policy through a blocking CI job (`advisory-gate`) that runs `scripts/check-advisories.sh` on every push and pull request. Suppressions are bare advisory IDs with a rationale block and a removal condition, mirrored in `SECURITY.md`; the script fails if the mirrors disagree. Policy: `docs/SUPPLY_CHAIN_POLICY.md`. Locked builds via `Cargo.lock`. Unknown registries and git sources are denied. Workflow actions are pinned to commit SHAs. | +| **Residual risk** | Low. `cargo-deny` and lockfiles reduce but do not eliminate supply-chain risk. A compromised transitive dependency that passes the advisory gate could still introduce vulnerabilities — the gate only knows published advisories. Malicious code merged upstream *before* an advisory exists is not detected. | | **User responsibility** | Review dependency changes when updating `Cargo.lock`. Monitor security advisories. | -| **Tests / evidence** | `cargo deny check` is a **local** supply-chain gate driven by `deny.toml` — it is **not** a CI step. CI (`.github/workflows/ci.yml`) runs `bash scripts/check.sh` and `cargo check --workspace --all-targets` + `cargo test --test platform_smoke`. | +| **Tests / evidence** | `scripts/check-advisories.sh` (and `--self-test`) is the gate, wired into CI as the `advisory-gate` job. `cargo deny check` is also runnable locally against the same `deny.toml`. | | **Owner / module** | `Cargo.toml`, `Cargo.lock`, CI configuration. | ### T14: Test Seam Activation in Production Binary diff --git a/plans/README.md b/plans/README.md index 65d62290..3348b6d0 100644 --- a/plans/README.md +++ b/plans/README.md @@ -67,6 +67,7 @@ Closure records and archive | Locking protocol and ordering convergence | `subsystems/locking-convergence-roadmap.md` | M001-M003 (owned-record protocol, kernel-lock protocol, ordering contract) | active | | Snippet CRUD surface | `subsystems/snippet-crud-surface-roadmap.md` | M001-M003 (non-interactive delete, folder/favorite write path, field update) | active | | Sync cursor protocol | `subsystems/sync-cursor-protocol-roadmap.md` | M001-M002 (monotonic sequence cursor, cursor-precision convergence) | closed | +| Security assurance | `subsystems/security-assurance-roadmap.md` | M001-M006 (advisory posture, CI gates, claim reconciliation, server hardening, payload v2 read/write) | proposed | Pre-convention flat-plan mapping: `000` → archived direction (superseded by canonical docs plus `distribution-release`/`mcp-integration`); diff --git a/plans/adrs/ADR-0002-encryption-payload-identity-binding.md b/plans/adrs/ADR-0002-encryption-payload-identity-binding.md new file mode 100644 index 00000000..e9075bc2 --- /dev/null +++ b/plans/adrs/ADR-0002-encryption-payload-identity-binding.md @@ -0,0 +1,241 @@ +# ADR-0002: Bind encrypted sync payloads to snippet identity + +Status: accepted + +Status history: + +- 2026-11-17 — proposed +- 2026-11-17 — accepted (maintainer directed implementation of the + security-assurance workstream) + +Date: 2026-11-17 + +Decision owners: project maintainers + +Related specification sections: + +- `plans/000-long-term-specification.md#6-sync-invariants` — encrypted fields, + merge identity, and the local-only field split +- `plans/000-long-term-specification.md#10-verification-and-evidence-rules` — + evidence required for a payload-format change +- `plans/001-terminology-and-domain-model.md#synced-fields` — the synced / + local-only field boundary + +Affected subsystem roadmaps: + +- `plans/subsystems/security-assurance-roadmap.md` (proposed; owns the + implementation) +- `plans/subsystems/sync-cursor-protocol-roadmap.md` (closed; context only — + its versioning convention for additive sync changes is reused) + +## Context + +`src/encryption.rs` seals payloads with AES-256-GCM and no associated data: +`cipher.encrypt(&nonce, plaintext.as_bytes())` (`src/encryption.rs:328-330`) +and `cipher.decrypt(&nonce, payload.ciphertext.as_ref())` +(`src/encryption.rs:355-357`). GCM authenticates the ciphertext, but nothing +cryptographically ties that ciphertext to the row it belongs to. + +The payload that `encrypt_snippet` produces covers only three fields — +`description`, `command`, `tags` (`src/sync.rs:333-338`) — while the routing +fields `id`, `created_at`, `updated_at`, `device_id`, and `deleted` travel as +plaintext proto fields (`src/sync.rs:1516-1535`; `architecture/encryption.md` +"Scope boundary"). The ciphertext is carried in the proto `command` field and +the record is marked `encrypted = true`. + +Consequences of the missing binding: + +1. **Cross-row substitution.** A server, a database operator, or anyone able + to reorder stored rows can copy a valid ciphertext from one of a user's + snippets into another snippet row with a different `id`. The client + decrypts successfully and accepts the content as the target row's + content. The substitution cannot invent new plaintext, but it can + rearrange the user's existing content across descriptions and ids. +2. **No fail-loud signal.** Because the tag still verifies, the client + cannot distinguish "this is the content that was sealed for this id" from + "this is content sealed for a different id". +3. **Boundary with the documented limitation.** The same server also + observes the bearer API key on every request (`src/sync.rs:323-343`), and + any party holding that key can decrypt and re-encrypt arbitrary content. + This ADR does **not** close that — see `SECURITY.md` § Sync Encryption and + `architecture/encryption.md`'s trust-boundary note. It closes the + narrower, key-blind case (a store that can move ciphertext but cannot use + the key), and it makes the two failure modes distinguishable in the + payload format. + +The defect is recorded as finding L8 in the 2026-11-17 security audit. + +## Decision drivers + +- A ciphertext must only decrypt for the snippet identity it was sealed for. +- Existing v1 payloads must keep decrypting indefinitely; history cannot be + rewritten. +- `snip-proto` must not change: the ciphertext already travels opaquely in + `command`, and no new field is needed. +- Old clients must not be forced to understand the new format before the + fleet is ready, because a failed decrypt currently surfaces as a skipped + snippet and a retried sync. +- Argon2id cost must not grow per snippet: the batch-shared salt and the + derived-key cache stay valid, because AAD does not affect key derivation. +- The change must not touch the client merge order, `updated_at` semantics, + or snippet-id determinism (`docs/IDENTITY_CONTRACT.md`). + +## Considered options + +### Option A — Payload version 2 with AAD over the snippet id (recommended) + +Keep `magic‖version‖salt‖nonce‖ciphertext`. Version `2` means the ciphertext +was sealed with associated data derived from the snippet identity: + +```text +AAD = b"snip-payload-v2\0" ‖ u32_le(id.len()) ‖ id.as_bytes() +``` + +The length prefix removes concatenation ambiguity. `id` is the same +content-addressable id the client already stores, sends, and merges on; the +server treats `id` as an ordinary primary-key column and does not need to +interpret it. + +- **Benefits.** Substitution across ids fails authentication and surfaces as + a normal `DecryptionFailed`. No protocol change, no server change, no new + KDF work. The version byte already exists in the header, so the format is + self-describing. +- **Costs.** A mixed-version fleet: a client that only understands v1 cannot + decrypt a v2 payload written by another device. `from_base64` currently + rejects any version other than 1 with `Unsupported payload version` + (`src/encryption.rs:190-194`), and `decrypt_snippet` counts the failure as + `server_decrypt_failed_count` (`src/sync.rs:919-926`). +- **Failure modes.** If writes switch to v2 before every device can read it, + older devices skip those snippets on every sync until upgraded. + +### Option B — AAD over id and device_id + +Same as Option A plus `device_id`. + +- **Benefits.** Also binds the writing device. +- **Costs.** `device_id` is client-supplied and can legitimately change on a + re-registered device; a re-registered device would then fail to decrypt its + own earlier payloads after a restore. The id already identifies the row, so + the extra binding buys little against substitution. +- **Failure modes.** Restore/re-registration turns a routine operation into + mass decryption failure. + +### Option C — AAD over id and library id + +- **Benefits.** Prevents cross-library replay as well as cross-id replay. +- **Costs.** The library identifier is not currently threaded into + `encrypt_snippets` (`src/sync.rs:1580-1593`); doing so touches the batch + API and every caller. It also couples the payload to a server-assigned + library id whose lifetime is managed by the server. +- **Failure modes.** Library rename/relink semantics (missing-library + recovery) would have to guarantee the library id is stable across relink — + not something this ADR can assert today. + +### Option D — No format change; document the residual risk + +- **Benefits.** Zero compatibility cost. +- **Costs.** Leaves the key-blind substitution path open, and the threat model + cannot truthfully state that the tag authenticates *which* snippet the + content belongs to. +- **Failure modes.** The gap is indistinguishable from "content integrity is + complete" to future maintainers. + +## Decision + +**Option A is selected, introduced in two phases.** + +- **Phase 1 — read support (this workstream's M005).** Accept + `PAYLOAD_VERSION_V2`, implement the AAD construction and the v1/v2 + decryption dispatch, and keep **writing v1**. No behavior change for + existing fleets; v2 payloads decrypt correctly and substitutions fail. +- **Phase 2 — write support (M006).** Switch `encrypt_with_salt` to write v2 + with AAD after the named release-adoption precondition is satisfied: one + published `snp` release that reads v2 must be available, and the minimum + supported client version in `SECURITY.md` must include it. + +Phase 2 is deliberately not bundled with Phase 1. The audited risk is low and +local; a fleet-wide decryption regression is a worse outcome than a delayed +switch. The roadmap records Phase 2 as blocked on Phase 1 plus the release +precondition rather than leaving it as an unstated follow-up. + +Library-id binding (Option C) is deferred: it is a strictly larger change +whose identity-stability precondition (missing-library recovery and relink) +must be established first. + +## Consequences + +### Positive + +- A ciphertext is cryptographically bound to its snippet id; cross-row + substitution fails with `DecryptionFailed` instead of silently succeeding. +- No proto, server, storage, merge-order, or KDF-parameter change. +- v1 remains readable forever; existing libraries need no migration. +- The threat model can state precisely what the tag guarantees: content + integrity for the bound identity, not confidentiality against a party that + observes the bearer key. + +### Negative + +- Two payload versions must be maintained, tested, and documented. +- The write switch needs a coordinated minimum-client-version statement; until + M006 lands, the implemented protection is read-side only. +- Old clients cannot read v2 payloads, which is why Phase 2 is gated. + +### Neutral or deferred + +- AAD coverage of `library_id` and `device_id` is deferred (Options B/C), + with reasons recorded above. +- Per-snippet random salts remain unnecessary for security given unique + nonces; the batch-shared salt perf optimization stands. + +## Compatibility and migration + +- `EncryptedPayload::from_base64` accepts version `1` and `2`; any other + version remains a hard `InvalidData` error. +- `argon2_params_for_version` returns the same parameters for versions 0, 1, + and 2, so the derived-key cache keyed by `(api_key, salt, version)` + (`src/encryption.rs:249-260`) hits for all of them; no re-derivation cost is + introduced by the version byte. +- Decryption of a v2 payload requires the snippet id. The public + `decrypt(api_key, data)` cannot supply it, so it must keep rejecting v2 with + an explicit error; a new `decrypt_for_snippet(api_key, data, id)` is used by + `decrypt_snippet`. This is a fail-loud API split, not a silent default. +- No database or wire migration. A v2 payload stored by a future client in an + existing database is simply opaque bytes to the server. + +## Security and reliability implications + +- **Integrity.** Substitution of ciphertext between ids of the same key fails + the GCM tag check because the AAD differs. +- **Confidentiality.** Unchanged: the key still derives from the API key and + the per-payload salt; a bearer-token observer can still decrypt. +- **Denial of service.** A malicious server can still withhold or replay + payloads; AAD does not address availability. Replaying an identical payload + for the same id is indistinguishable from a legitimate re-send and remains + covered by the merge rules, not by the tag. +- **Migration.** No destructive step; v1 payloads are never rewritten in + place. A user who downgrades after M006 will skip v2 payloads, which is the + documented cost of the write switch. +- **No new secret.** AAD is public data; it adds no key material and no + storage. + +## Verification + +- Unit: v2 roundtrip with the correct id; v2 payload decrypted with a + different id fails with `DecryptionFailed`. +- Unit: v1 payload still decrypts with `decrypt` and with + `decrypt_for_snippet`; `decrypt` on a v2 payload returns the explicit + "requires identity binding" error rather than a generic tag failure. +- Unit: unknown version (`3`) is still rejected as `InvalidData`. +- Integration: `sync` pulls a library containing one v1 and one v2 row, and + both land with their original ids (`tests/sync_integration.rs`). +- Guard: a test asserting a decrypted v2 snippet keeps the id it was sealed + under after save/load id normalization (`docs/IDENTITY_CONTRACT.md`). +- Phase 2 additionally: mixed-version negative test proving an old-format-only + decrypt path cannot read a v2 write, so the release precondition is + documented rather than assumed. + +## Supersession + +None. If library-id binding is later adopted, it must arrive as a new payload +version under a new ADR; version 2 is not redefined in place. diff --git a/plans/adrs/ADR-0003-advisory-remediation-and-suppression-policy.md b/plans/adrs/ADR-0003-advisory-remediation-and-suppression-policy.md new file mode 100644 index 00000000..58b260f2 --- /dev/null +++ b/plans/adrs/ADR-0003-advisory-remediation-and-suppression-policy.md @@ -0,0 +1,244 @@ +# ADR-0003: Advisory remediation and suppression policy + +Status: accepted + +Status history: + +- 2026-11-17 — proposed +- 2026-11-17 — accepted (maintainer directed implementation of the + security-assurance workstream) + +Date: 2026-11-17 + +Decision owners: project maintainers + +Related specification sections: + +- `plans/000-long-term-specification.md#9-distribution-and-release-invariants` — + published-crate and dependency-source rules +- `plans/000-long-term-specification.md#10-verification-and-evidence-rules` — + what counts as evidence for a security exception +- `plans/001-terminology-and-domain-model.md#8-distribution-and-update-terms` — + release and package terms + +Affected subsystem roadmaps: + +- `plans/subsystems/security-assurance-roadmap.md` (proposed; owns the + implementation) +- `plans/subsystems/eggstack-dependency-refresh-roadmap.md` (closed; precedent + for exact-pin dependency work) + +## Context + +The 2026-11-17 security audit ran `cargo audit` and `cargo deny check` against +the working tree and left five dependency findings open: + +| Kind | Crate | Advisory | Fixed by | +|------|-------|----------|----------| +| Vulnerability (CVSS 6.8) | `libsqlite3-sys 0.37.0` (bundled SQLite < 3.54.0) | RUSTSEC-2026-0459 | `>=0.39.0` | +| Unmaintained | `zbus_names 4.3.5` | RUSTSEC-2026-0371 | none published | +| Unmaintained | `zvariant 5.15.1` | RUSTSEC-2026-0370 | none published | +| Unmaintained | `zvariant_derive 5.15.1` | RUSTSEC-2026-0372 | none published | +| License | `webpki-roots 0.26.11`, `1.0.12` | `CDLA-Permissive-2.0` not allowlisted | allowlist decision | + +The SQLite advisory is reachable only through `snip-sync`'s `sqlx` dependency +(`snip-sync/Cargo.toml:41`); `cargo tree -e features -i libsqlite3-sys` proves +the **bundled** C library is compiled in. The desktop `snp` binary is not +affected: its only `sqlx` edge is a dev-dependency (`Cargo.toml:179`). The +advisory is local-vector: an attacker able to write a crafted database plus a +sibling `-wal` file with a mismatched page size can make ordinary queries +return uninitialized page-cache memory. + +The blocker is version arithmetic, not effort. `sqlx 0.9.0` depends on +`libsqlite3-sys >=0.30.1, <0.38.0` (dependency metadata), while the patched +release is `>=0.39.0`. Upstream's bound-widening change is merged but +unreleased. There is no published `sqlx` that both compiles this workspace and +clears the advisory. + +Two repo rules constrain the response: + +1. `snip-sync` and `snip-it` are published crates; crates.io rejects a + dependency on a git source. A pinned git patch would make the next + `snip-sync` publish impossible until it is removed. +2. `deny.toml` states that past suppressions are removed once upstream fixes + the advisory, and "do not re-add without a fresh exploitability analysis". + An undocumented suppression is therefore a policy violation, not a shortcut. + +The same audit found that no CI workflow runs either advisory tool +(`grep -rn "cargo audit\|cargo deny" .github/workflows/` returns nothing), so +the local gate is the only gate. That gap is owned by the security-assurance +roadmap's M002; this ADR decides what the gate should contain. + +## Decision drivers + +- Keep dependency sources on crates.io so both published crates stay + publishable. +- Keep the gate **blocking** for new findings; a broad lint-level relaxation + would hide future vulnerabilities. +- Every exception must name the advisory, the reason, the date, and the + condition that removes it. +- Prefer a real upgrade whenever one exists; an exception is a waiting state, + never a destination. +- Do not broaden the license allowlist beyond the license actually required. +- Do not add crates, tooling, or a second advisory database. + +## Considered options + +### Option A — Pin an unreleased `sqlx` git revision + +Add `[patch.crates-io] sqlx = { git = ..., rev = ... }` (or a direct git +dependency) until the bound widening is released. + +- **Benefits.** Clears RUSTSEC-2026-0459 immediately; the build is + reproducible by revision. +- **Costs.** `snip-sync` cannot be published to crates.io while the patch is + present, so the next release either drops the fix or drops the publish. + Reviewers must audit an unreviewed third-party revision. The workspace would + temporarily depend on code that is not in any release channel. +- **Failure modes.** A release cut under time pressure ships with the patch + removed and the advisory silently reinstated, or ships with the patch and + fails the publish step. + +### Option B — Stay on published crates; scope, justify, and time-box an exception (recommended) + +Keep `sqlx 0.9` from crates.io. Add explicit `ignore` entries for the four +advisory IDs, each with a structured comment containing the exploitability +analysis, the added date, the review-by date, and the removal condition. Add +the one license the graph actually needs. Mitigate the local exposure that the +SQLite advisory depends on (see M004: private database directory). + +- **Benefits.** Both crates remain publishable. The gate turns green and keeps + failing on anything **new**. The exception is visible in the diff and in + `SECURITY.md` § Advisory Exceptions, so it cannot quietly become permanent. +- **Costs.** The bundled CVE remains present in the server binary until + upstream releases, mitigated but not removed. Suppression discipline is + manual. +- **Failure modes.** The review date passes unnoticed. Mitigation: M001 adds a + deterministic check script and M002 runs it in CI; the roadmap tracks the + removal condition. + +### Option C — Link system SQLite instead of bundling + +Switch `sqlx` to the unbundled SQLite feature so the advisory (which applies to +the bundled copy) no longer describes the build. + +- **Benefits.** Removes the vulnerable bundled source from the binary. +- **Costs.** The server would depend on a system `libsqlite3` at build and run + time on every target, including the Windows and macOS release matrix; it also + removes the reproducible bundled version and shifts the vulnerability + question to whatever the host ships. +- **Failure modes.** A host with an older system SQLite reintroduces the same + advisory silently, with no lockfile evidence. + +### Option D — Leave the gate red until upstream releases + +- **Benefits.** No policy change; no suppression. +- **Costs.** A permanently failing gate trains maintainers to ignore it, and + the three unmaintained advisories have no fix at all, so the gate could never + go green. +- **Failure modes.** The next real vulnerability is indistinguishable from the + known noise. + +## Decision + +**Option B is selected.** + +1. `deny.toml` keeps a single `[advisories] ignore` list. Each entry is an + advisory **ID only** — never a crate name, version, or wildcard — and is + preceded by a comment block with these fields: + + ```text + ID: RUSTSEC-YYYY-NNNN + Scope: which crate and which build unit is affected + Why: exploitability analysis (attack vector, preconditions, blast radius) + Added: YYYY-MM-DD + Review by: YYYY-MM-DD (<= 90 days) + Remove when: the concrete upstream condition that ends the exception + ``` + +2. The license allowlist gains exactly `CDLA-Permissive-2.0`, with a one-line + rationale (permissive data license covering a certificate-root bundle). The + `license-not-encountered` warning for an unused allowance is cleaned up in + the same change; that warning is not a gate, so removing the entry is + optional but preferred. + +3. The three unmaintained advisories are suppressed by explicit ID. Setting + `unmaintained = "workspace"` (or any global lint-level relaxation) is + **prohibited**: it would hide unmaintained crates in the workspace itself + and any new transitive finding. + +4. The SQLite suppression's named mitigation is the private server data + directory from M004 (`0o700` directory, `0o600` files on Unix). The + suppression is not justified on "the server is usually local" alone. + +5. A suppression is removed in the same change that adopts the fixed release. + Removing an exception never requires an ADR or a roadmap change. + +6. `SECURITY.md` § Advisory Exceptions is the human-readable mirror of the + `deny.toml` list. The two are updated in the same commit; M001 adds a check + that every ignored ID appears in both. + +## Consequences + +### Positive + +- `cargo audit` and `cargo deny check` become deterministic and green, so + M002 can make them blocking. +- Every exception is auditable in one place with an expiry. +- Published-crate constraints are respected; no git dependency enters the + release graph. + +### Negative + +- The server continues to ship the vulnerable bundled SQLite until upstream + releases; the mitigation reduces but does not eliminate the local vector. +- Maintainers must actively review the exceptions; the review date is a + process control, not an automated one. +- The allowlist grows by one license. + +### Neutral or deferred + +- The unmaintained advisories have no upstream fix; they stay until the + keyring/zbus dependency ships a maintained replacement. Their review is + bundled with the quarterly dependency refresh. +- If `sqlx` publishes a compatible release, the SQLite exception is deleted + immediately, without waiting for the review date. + +## Compatibility and migration + +- No dependency source changes, so `Cargo.lock` and both published crates keep + their current publishing story. +- No protocol, storage, or CLI change. +- `deny.toml` remains the local source of truth; CI reads the same file in + M002, so local and CI verdicts agree by construction. + +## Security and reliability implications + +- **Residual risk.** The SQLite advisory is a local information-disclosure + primitive requiring attacker write access adjacent to the database. With + `0o700`/`0o600` server data, a non-privileged local user cannot satisfy the + precondition. A privileged local user is already outside the threat model. +- **No new authority.** A suppression does not change runtime behavior; it + only changes what the gate reports. +- **Availability.** None. No daemon, lock, or migration behavior changes. +- **Supply chain.** Keeping crates.io-only sources preserves the existing + `[sources]` policy (`unknown-registry = "deny"`, `unknown-git = "deny"`). + +## Verification + +- `cargo audit` exits 0 with only the suppressed IDs reported as warnings. +- `cargo deny check` ends with `advisories ok, bans ok, licenses ok, sources ok`. +- A negative check proves the gate still fails on an unsuppressed advisory: + temporarily removing one `ignore` entry (or pointing at a copy of the list + without it) must fail the check. This is a manual verification step, not a + committed test that depends on the advisory database content. +- Every `ignore` ID appears in `SECURITY.md` § Advisory Exceptions, and every + documented ID appears in `deny.toml` (M001's check script). +- `cargo tree -e features -i libsqlite3-sys` still shows the bundled feature + and shows the `snp` binary is unaffected. + +## Supersession + +None. When the upstream fixes land, this ADR is not rewritten; the exceptions +are deleted and the record stays as the policy of how they were handled. A +future decision to vendor a patched SQLite would be a new ADR. diff --git a/plans/closure/security-assurance/001-status.md b/plans/closure/security-assurance/001-status.md new file mode 100644 index 00000000..7b77e9af --- /dev/null +++ b/plans/closure/security-assurance/001-status.md @@ -0,0 +1,150 @@ +# Security Assurance M001 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/security-assurance/001-advisory-posture-and-license-policy.md` + +Source subsystem roadmap: + +- `plans/subsystems/security-assurance-roadmap.md#milestone-001--advisory-posture-and-license-policy` + +Repository baseline reviewed: `0f3bc98` (`chore/prune-comments-and-plans`), plus +the uncommitted dependency-refresh and doc-pruning changes already present in +that worktree. Implementation is uncommitted; the SHA is recorded at commit time. + +Implementation commits or pull requests: + +- Uncommitted working tree on `chore/prune-comments-and-plans` — `deny.toml`, + `.cargo/audit.toml`, `SECURITY.md`, `scripts/check-advisories.sh`, + `docs/SUPPLY_CHAIN_POLICY.md`, ADR-0003 status. + +Primary class: infrastructure. Policy and local gate only; no runtime change. + +## 1. Executive finding + +M001 is complete. `cargo audit` and `cargo deny check` both exit 0 on the +working tree with exactly four advisory IDs suppressed, each carrying the +six-field rationale block from ADR-0003, and `CDLA-Permissive-2.0` is the only +license added. `scripts/check-advisories.sh` proves the three-way suppression +mirror and fails on an unsuppressed advisory, on a missing rationale field, and +on a non-ID suppression. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| `cargo audit` exits 0 | `cargo audit` | pass | 468 crate dependencies scanned; four suppressed IDs reported as allowed warnings | +| `cargo deny check` exits 0 | `cargo deny check` | pass | `advisories ok, bans ok, licenses ok, sources ok` | +| Exactly four advisory IDs, each with ID/scope/why/added/review-by/remove-when | `deny.toml` | pass | Fields enforced by the script, see next row | +| Missing rationale field fails the gate | removed `Scope:` from the `RUSTSEC-2026-0370` block in a temp edit | pass | `FAIL: RUSTSEC-2026-0370 has an incomplete rationale block`; edit reverted | +| No crate-name or wildcard suppression | script parses the `ignore` array | pass | Every element must match `^"RUSTSEC-NNNN-NNNN"$` | +| `CDLA-Permissive-2.0` is the only license addition | `deny.toml` diff | pass | `node_modules`-free; one line plus rationale comment | +| Every ignored ID appears in both machine lists and in `SECURITY.md` | script set comparison | pass | `deny.toml` = `.cargo/audit.toml` = `advisory-ignore-ids` marker (4 IDs) | +| A drifted mirror fails | removed one ID from the `SECURITY.md` marker in a temp edit | pass | `FAIL: deny.toml and SECURITY.md suppress different advisory sets`; edit reverted | +| Unsuppressed advisory still fails | `--self-test` | pass | Removed `RUSTSEC-2026-0370` from a temp config; gate failed and the output named the ID | +| No dependency-source change | `Cargo.lock`, `deny.toml` `[sources]` | pass | crates.io only; `unknown-registry`/`unknown-git` still `deny` | +| SQLite scope unchanged | `cargo tree -e features -i libsqlite3-sys` | pass | `bundled` present, reached through `snip-sync`; `snip-it` edge remains a dev-dependency | +| Workspace still builds | `cargo check --workspace --all-targets` | pass | No lockfile churn beyond the working tree's existing state | + +## 3. Production implementation evidence + +- `deny.toml`: four `ignore` entries with rationale blocks; policy comment + pointing at ADR-0003; `CDLA-Permissive-2.0` allowed; the unused + `BSD-2-Clause` allowance retained with a written justification (it is a + deliberate policy ceiling, and the resulting `license-not-encountered` + warning is not a gate). The stale RUSTSEC-2024-0437 comment was removed: + `protobuf` is now 3.7.2, above the patched threshold the comment named. +- `.cargo/audit.toml`: mirrors the same four IDs so a bare `cargo audit` agrees + with `cargo deny`. +- `scripts/check-advisories.sh`: tool-presence check, both tools, three-way + mirror comparison, rationale-field validation, ID-only validation, and + `--self-test`. +- `SECURITY.md` § Advisory Exceptions: operator-facing mirror, the + machine-readable marker line, a per-advisory table with removal conditions, + and the per-finding exploitability summary. + +## 4. Verification executed + +```bash +cargo audit +cargo deny check +bash scripts/check-advisories.sh +bash scripts/check-advisories.sh --self-test +cargo check --workspace --all-targets +cargo tree -e features -i libsqlite3-sys +``` + +Results: all pass. `cargo audit` exit 0; `cargo deny check` exit 0; both script +modes exit 0; the negative proofs above exited 1 for the intended reason and +were reverted. `cargo check --workspace --all-targets` passes (one pre-existing +macOS-only `dead_code` warning; see § 10). + +## 5. Invariant review + +- `Cargo.lock` remains the single resolution source; the only lockfile change is + the `snip-sync` version bump owned by M004. +- Dependency sources remain crates.io only. +- Both published crates stay publishable; no git or path dependency entered the + release graph. +- Suppressions are ID-only and scoped; no global lint relaxation exists. The + prohibited `unmaintained = "workspace"` setting was not introduced. +- The allowlist gained exactly one entry. +- No blanket dependency refresh was performed. + +## 6. Failure and recovery review + +- A missing tool is an environment failure with an install hint, never a silent + pass. +- Network failure fetching the advisory database fails the command; it is not + converted into a clean verdict. +- `--self-test` writes only to `mktemp -d` and removes it on exit; it does not + mutate the repository. +- Re-running the script is idempotent. + +## 7. Migration and compatibility review + +No source, wire, storage, or CLI change. `deny.toml`, `.cargo/audit.toml`, and +the script are excluded from the published crate (`Cargo.toml` `exclude` list +covers `deny.toml`; `scripts/` is excluded too). No version bump is required by +this milestone. + +## 8. Security review + +- Suppressions do not change runtime authorization or behavior; they change + what the gate reports. +- The SQLite exception's named mitigation is M004's owner-only server data + directory, not "the server is usually local". +- The three unmaintained advisories are suppressed individually, so a **new** + unmaintained dependency still fails the gate. +- No secret was introduced; the rationale blocks contain no credential. + +## 9. Documentation and operations + +- `SECURITY.md` § Advisory Exceptions (new mirror and discipline). +- `deny.toml` inline rationale. +- `docs/SUPPLY_CHAIN_POLICY.md` rewritten where it contradicted reality: the + "ignore list is empty / gate currently fails / not a CI step" statements, the + license list, the (wrong) structured-ignore-table format, and the stale + `rustls`/`webpki-roots` finding snapshot. +- ADR-0003 flipped to `accepted` with a status-history line. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | `.cargo/audit.toml` is a third machine mirror beyond the two the plan named | A divergence is possible only if the check script is bypassed | None — the script compares all three and fails on drift | +| low | Pre-existing macOS-only clippy failure in `snip-sync/src/startup.rs` (`needless_return` in the `cfg(target_os = "macos")` arm) | `cargo clippy -D warnings` is red on macOS only; Linux CI compiles a different arm | Fix separately; not in this workstream's scope | +| low | Pre-existing macOS-only `dead_code` warning for `McpProcess::pid` in `tests/selector_search_parity.rs` | Same as above | Fix separately | + +## 11. Roadmap disposition + +Milestone closed; M002 may proceed. The SQLite suppression is removed in the +same change that adopts a `sqlx` release accepting `libsqlite3-sys >=0.39.0`, +without waiting for its review date. + +## 12. Registry updates + +`plans/registry.md` and the roadmap § 12 table record M001 as `closed`. No other +registry row changes. diff --git a/plans/closure/security-assurance/002-status.md b/plans/closure/security-assurance/002-status.md new file mode 100644 index 00000000..71ad1f3d --- /dev/null +++ b/plans/closure/security-assurance/002-status.md @@ -0,0 +1,125 @@ +# Security Assurance M002 — Closure Status + +Status: conditionally closed + +Source implementation plan: + +- `plans/implementation/security-assurance/002-ci-advisory-gates-and-action-pinning.md` + +Source subsystem roadmap: + +- `plans/subsystems/security-assurance-roadmap.md#milestone-002--ci-advisory-gates-and-action-pinning` + +Implementation commit reviewed: `49115c3` (`feat(security): add assurance controls and v2 reads`), in [PR #69](https://github.com/eggstack/snip-it/pull/69). GitHub Actions run [44191381652](https://github.com/eggstack/snip-it/actions/runs/44191381652) and Markdown link-check run [44191381677](https://github.com/eggstack/snip-it/actions/runs/44191381677) completed on 2026-11-17. + +Implementation commits or pull requests: + +- Commit `49115c3` in [PR #69](https://github.com/eggstack/snip-it/pull/69): `.github/workflows/ci.yml` (new `advisory-gate` job) and SHA pins in `ci.yml`, `release-binaries.yml`, `distribution-consumer-smoke.yml`, and `link-check.yml`. + +Primary class: infrastructure. **Roadmap authorization:** the source plan's M002 +entry is the revision under which `plans/README.md` permits this CI hardening. + +## 1. Executive finding + +The gate is wired and every mutable action reference is pinned. PR #69 now has a green GitHub Actions run, including the `advisory-gate` job. A deliberately unsuppressed red run and a post-pin Dependabot `github-actions` update remain unverified, so the milestone stays conditionally closed with those two evidence items named. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Advisory job runs on every push/PR to `main` | `.github/workflows/ci.yml` triggers unchanged (`push`/`pull_request` on `main`) and the job has no `if:` filter | pass | Inherits the workflow concurrency group | +| Job fails on an unexpected finding | Job runs `bash scripts/check-advisories.sh`, whose exit code is the job verdict | pass (local) | M001 proved the script fails on an unsuppressed advisory | +| Job passes on the committed policy | `bash scripts/check-advisories.sh` locally | pass | Same file, same script, so local and CI verdicts agree by construction | +| No `continue-on-error`, no retry loop, no `if: always()` | `ci.yml` | pass | Deliberate: a visible outage beats a stale pass | +| Job kept out of `linux-correctness` | separate job | pass | The 35-minute correctness budget stays network-free | +| Tool versions exact and recorded | `taiki-e/install-action` with `cargo-audit@0.23.0,cargo-deny@0.20.2` | pass | Versions match the local tooling used for M001's evidence | +| Third-party actions SHA-pinned with version comments | `grep -rE "uses: [^ ]+@v[0-9]" .github/workflows/` → nothing; `grep -rE "uses: [^ ]+@(stable\|master\|main)$"` → nothing | pass | 5 previously mutable refs pinned; 2 existing pins given version comments | +| `dtolnay/rust-toolchain` no longer a moving branch | pinned to the `stable` branch commit `39008827…` with `toolchain: "1.94"` still explicit | pass | Comment records what the ref meant when pinned | +| Least privilege preserved | workflow `permissions: contents: read`; new job repeats it | pass | `release-binaries.yml`'s narrow `contents: write` on the attach job untouched | +| Workflows still valid | YAML parse of all four workflow files | pass | `ci.yml` jobs: `advisory-gate`, `linux-correctness`, `platform-smoke` | +| Green CI run recorded | [run 44191381652](https://github.com/eggstack/snip-it/actions/runs/44191381652) | pass | Advisory/license gate, Linux correctness, and macOS/Windows platform smoke passed; Markdown link check also passed in [run 44191381677](https://github.com/eggstack/snip-it/actions/runs/44191381677) | +| Red run on an unsuppressed branch recorded | — | not run | A deliberately unsuppressed branch has not been tested | +| Dependabot still updates pins | `.github/dependabot.yml` already tracks `github-actions` | not verified | Needs one Dependabot cycle after the branch lands | + +## 3. Production implementation evidence + +- New `advisory-gate` job: `ubuntu-latest`, 10-minute timeout, + `contents: read`, pinned checkout, pinned install action with exact tool + versions, then `bash scripts/check-advisories.sh`. +- Pins: `actions/checkout@fbc6f399…` (v5.1.0, the same SHA `link-check.yml` + already used), `Swatinem/rust-cache@2201cc58…` (v2.9.3), + `dtolnay/rust-toolchain@39008827…` (stable branch as of 2026-11-17), + `actions/upload-artifact@ea165f8d…` (v4.6.2), + `actions/download-artifact@d3f86a10…` (v4.3.0), + `taiki-e/install-action@ab49d3c6…` (v2.90.5). +- Pin-policy comment added at the top of every mutated workflow, naming + Dependabot's role in keeping the comments and SHAs in step. +- `goto-bus-stop/setup-zig` already carried a SHA but no version comment; it is + now commented `# v2.2.1`. `link-check.yml`'s checkout comment was aligned to + `# v5.1.0` so the two files read identically. + +## 4. Verification executed + +```bash +bash scripts/check-advisories.sh # local reproduction of the job +grep -rE "uses: [^ ]+@v[0-9]" .github/workflows/ || echo "no mutable tags" +grep -rE "uses: [^ ]+@(stable|master|main)$" .github/workflows/ || echo "no mutable branches" +python3 -c 'import yaml,glob; [yaml.safe_load(open(f)) for f in glob.glob(".github/workflows/*.yml")]' +``` + +Local results: the script passes, both greps return nothing, and all four workflow files parse. GitHub Actions run [44191381652](https://github.com/eggstack/snip-it/actions/runs/44191381652) passed the advisory/license gate, Linux correctness, and macOS/Windows platform smoke; Markdown link-check run [44191381677](https://github.com/eggstack/snip-it/actions/runs/44191381677) also passed. `gh pr checks 69 --watch` exited 0 after all five checks completed. + +## 5. Invariant review + +- Least privilege unchanged (`contents: read`; the release attach job keeps its + scoped write). +- No new secret, token, service, or third-party account. +- The gate fails rather than warns. +- `scripts/check.sh` was not modified and keeps its network-free contract. +- `deny.toml` and `SECURITY.md` stay excluded from the published crate. + +## 6. Failure and recovery review + +- Missing tool → job failure with the script's install hint. +- Advisory-database fetch failure → job failure; no retry loop masks it. +- Concurrency cancellation is safe: the job is read-only. +- The job writes nothing to the repository or to caches another job reads. + +## 7. Migration and compatibility review + +Workflow-only change; no crate, protocol, or CLI effect. Pinned SHAs move only +through reviewed Dependabot pull requests. No release identity or publication +change. + +## 8. Security review + +The gate consumes the pull request's own `deny.toml`, so a PR that adds an +unjustified suppression still passes the tool. The control for policy abuse is +review of the rationale block, not the tool — recorded honestly rather than +claimed as detection. Pinning removes mutable-tag substitution as a +build-environment attack, but the pin itself is only as trustworthy as the +reviewed SHA. + +## 9. Documentation and operations + +- Workflow header comments (pin policy, tool versions, authorization). +- `docs/SUPPLY_CHAIN_POLICY.md` and `docs/THREAT_MODEL.md` T13 corrected: the + gate is a blocking CI step, not a local-only tool. +- `SECURITY.md` § Supply Chain now describes the CI job and the pin policy. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| medium | No deliberately unsuppressed red run is recorded | The job's failure behavior on `ubuntu-latest` has not been exercised through GitHub Actions | Run a controlled branch with one suppression removed and record the failed run id | +| low | Dependabot's SHA-update behaviour after pinning is unverified | Pins could stale silently until the next manual bump | Confirm the first `github-actions` PR after landing; if none appears, add the minimal config it needs — do not remove pinning | +| low | `taiki-e/install-action` is a new third-party dependency in the build path | A compromised action could alter the job | It is SHA-pinned and runs only in the read-only advisory job; review its bumps like any other dependency | + +## 11. Roadmap disposition + +Milestone conditionally closed: production implementation complete, green CI evidence is recorded, and the deliberately unsuppressed red run plus one Dependabot cycle remain outstanding. M006 is unaffected by this condition; M005 may proceed. + +## 12. Registry updates + +`plans/registry.md` and the roadmap § 12 table record M002 as `conditionally +closed`, with the CI-evidence condition named. diff --git a/plans/closure/security-assurance/003-status.md b/plans/closure/security-assurance/003-status.md new file mode 100644 index 00000000..c140a731 --- /dev/null +++ b/plans/closure/security-assurance/003-status.md @@ -0,0 +1,137 @@ +# Security Assurance M003 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/security-assurance/003-security-claim-reconciliation.md` + +Source subsystem roadmap: + +- `plans/subsystems/security-assurance-roadmap.md#milestone-003--security-claim-reconciliation` + +Repository baseline reviewed: `0f3bc98` (`chore/prune-comments-and-plans`); +implementation is uncommitted. + +Implementation commits or pull requests: + +- Uncommitted working tree — `SECURITY.md`, `docs/THREAT_MODEL.md`, + `docs/SUPPLY_CHAIN_POLICY.md`, `architecture/overview.md`, + `tests/architecture.rs`, `.skills/encryption-module.md`, + `architecture/encryption.md`. + +Primary class: polish. Documentation plus one narrow regression guard; no +runtime change. + +## 1. Executive finding + +The two false guarantees are gone, replaced by the three-part statement the +implementation supports (what is encrypted, what the server can do, what the +tag proves), and a guard in `tests/architecture.rs` fails if either retracted +sentence returns or if the supported-versions table stops naming the shipped +release. The support window was confirmed by the maintainer on 2026-11-17 +(`1.4.x` full support, `1.3.x` security fixes only, `< 1.3` unsupported), which +was the only outstanding item. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| No document claims a compromised server cannot read content | repo-wide grep for the retracted phrases | pass | Only the guard's own constant contains the strings | +| No document claims the tag prevents forgery by a key holder | `docs/THREAT_MODEL.md` T3 rewritten | pass | States the distinction explicitly | +| Bearer-key consequence stated wherever confidentiality is claimed | `SECURITY.md` § Sync Encryption, `docs/THREAT_MODEL.md` Boundary 6/T3, `architecture/overview.md` | pass | The overview previously said the server "stores only ciphertext it cannot read"; corrected | +| Correction present, not merely a removal | `SECURITY.md` contains "not server-blindness" | pass | Asserted by the guard | +| GCM guarantee scoped to parties without the key | T3 residual risk | pass | | +| Payload-identity limitation stated with its plan | T3 + § Sync Encryption version matrix | pass | Marked as read-capable, not yet written; links ADR-0002 | +| Supported versions include the shipped release | table lists `1.4.x`; `Cargo.toml` is `1.4.1` | pass | Window confirmed by the maintainer 2026-11-17 | +| Archived audit labelled historical | `SECURITY.md` § Security Audit | pass | Names the archive banner and stops calling it current findings | +| TLS assertion, `/health`, checksum-only update explicit | § Server Deployment / § Known Limitations | pass | Each checked against `startup.rs`, `main.rs`, `http.rs`, `update.rs` | +| Guard fails if either historical sentence returns | `cargo test --test architecture --features test-support` | pass | 18 passed | +| Guard detects the sentences | temporary `SECURITY.md` append | pass | Guard failed naming the claim; edit reverted | +| No runtime behavior or contract change | diff scope | pass | Documentation, one test file, one skill doc | + +## 3. Production implementation evidence + +- `SECURITY.md`: new supported-versions window with a stale-table rule; + § Encryption notes that v1 uses no AAD; § Supply Chain describes the CI gate + and pinning; § Self-Update Verification gains the no-signature limitation; + § Sync Encryption is rewritten as three statements plus a payload-version + support matrix; § Server Deployment states that the server does not terminate + TLS and documents the metrics/registration budgets and private data directory; + § Known Limitations gains `/health` disclosure, checksum-only updates, the + not-yet-written v2 binding, and Unix-only data permissions; § Security Audit + labels the archive historical. +- `docs/THREAT_MODEL.md`: Boundary 6 no longer says "end-to-end encrypted" and + gains a version-disclosure note; T3 replaces the forgery sentence with the + key-holder distinction and records the substitution limitation; T13 describes + the blocking CI gate and its residual risk. +- `tests/architecture.rs`: `published_security_claims_match_the_implementation` + plus `forbidden_security_claim_detector_reports_the_retracted_sentences`. The + guard is intentionally narrow: it pins the two historical defects and the + supported-version rule, not general prose quality. + +## 4. Verification executed + +```bash +cargo test --test architecture --features test-support +grep -rn "cannot read snippet content\|cannot forge content\|server cannot read" \ + --include=*.md --include=*.rs . | grep -v ^./plans/ | grep -v docs/archive/ +``` + +Results: 18 tests pass. The grep returns nothing outside the guard's own +constant and the plan/closure documents that quote the retracted wording for +the record. The deliberate-failure transcript is in § 2. + +## 5. Invariant review + +- `architecture/encryption.md` remains the deep-dive source; `SECURITY.md` links + to it rather than duplicating a weaker version. +- The operational "use TLS / use a proxy" guidance is preserved and only + clarified. +- No security control was removed or relaxed by a wording change. +- The archived audit stays archived and was not edited. + +## 6. Failure and recovery review + +Not applicable to runtime behaviour. The concurrent-edit hazard with M001 was +disjoint (M001 owned § Advisory Exceptions; this milestone owned the rest) and +landed in one working tree without conflict. + +## 7. Migration and compatibility review + +No user-visible behaviour change; no version bump. The guard reuses the existing +`architecture` target rather than adding a 56th test target. + +## 8. Security review + +The change corrects overstatement rather than adding control. The one risk is +the opposite direction — understating the protection — which the three-part +statement avoids by naming what *is* provided (transport confidentiality and +at-rest obfuscation) alongside what is not. + +## 9. Documentation and operations + +`SECURITY.md` (six sections), `docs/THREAT_MODEL.md` (Boundary 6, T3, T13), +`docs/SUPPLY_CHAIN_POLICY.md` (policy, licenses, format, known gaps), +`architecture/overview.md` (encryption note), `architecture/encryption.md` +(payload versions), `.skills/encryption-module.md` (versioning warning and +limitations), `tests/architecture.rs` (guard). + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | `docs/archive/SECURITY_AUDIT.md` still contains stale paths and old claims | It is archived and now labelled historical, but a reader who lands there directly may be misled | None required; the banner is explicit | + +The support-window item is resolved: confirmed 2026-11-17 and already reflected +in `SECURITY.md` § Supported Versions. + +## 11. Roadmap disposition + +Milestone closed. The support window is maintainer-confirmed, so no condition +remains. M002's CI evidence is independent of this milestone. + +## 12. Registry updates + +`plans/registry.md` and the roadmap § 12 table record M003 as `closed`; the +support-window condition is discharged. diff --git a/plans/closure/security-assurance/004-status.md b/plans/closure/security-assurance/004-status.md new file mode 100644 index 00000000..3e651949 --- /dev/null +++ b/plans/closure/security-assurance/004-status.md @@ -0,0 +1,163 @@ +# Security Assurance M004 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/security-assurance/004-server-abuse-resistance-and-local-file-hygiene.md` + +Source subsystem roadmap: + +- `plans/subsystems/security-assurance-roadmap.md#milestone-004--server-abuse-resistance-and-local-file-hygiene` + +Repository baseline reviewed: `0f3bc98` (`chore/prune-comments-and-plans`); +implementation is uncommitted. + +Implementation commits or pull requests: + +- Uncommitted working tree — `snip-sync/src/{lib,http,main,db,rate_limiter,test_helpers}.rs`, + `snip-sync/config.toml`, `snip-sync/Cargo.toml` (0.1.8 → 0.2.0), + `tests/snip_sync_lifetime.rs`, `tests/sync_multibatch.rs`, `Cargo.toml`, + `Cargo.lock`, `architecture/server.md`, `SECURITY.md`. + +Primary class: invariant. No proto change; process-local bounds and file modes. + +## 1. Executive finding + +M004 is complete. `/metrics` authentication now has a failure-only global +budget that returns `429` with `Retry-After` and no challenge, registration has +a global budget distinct from the per-peer budget, and the server's data +directory and files are owner-only on Unix. The gRPC service and the HTTP leaf +share one `Arc`, so the bounded entry map stays a single +process-wide limit. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Metrics authentication bounded by a documented limit | `metrics_auth_failures_per_minute`, default 10, `snip-sync/config.toml` + `architecture/server.md` | pass | Global because the HTTP leaf's `RequestHead` carries no peer address | +| Valid credentials never blocked by that budget | integration test: valid scrape returns `200` after exhaustion | pass | Budget is consulted only on the failure path | +| `429` carries `Retry-After` and no `WWW-Authenticate` | integration test | pass | Challenging a throttled caller would invite the retry being bounded | +| First N failures keep returning the `401` challenge | integration test with budget 2 | pass | Wire parity for the ordinary case preserved | +| Registration has a global budget distinct from the per-peer budget | `register-global` key; unit test asserts key isolation | pass | Both budgets remain | +| Rejected registration writes no rows | unit test counts `users` before/after | pass | Rejection happens before `create_user`; no transaction is opened | +| Rejected registration is a typed resource-exhausted status | unit test asserts `Code::ResourceExhausted` and a distinguishable message | pass | | +| Data directory `0o700`, files `0o600` on Unix | `#[cfg(unix)]` tests | pass | Created with the mode at creation; pre-existing broad modes tightened | +| Broad pre-existing mode is tightened or warned with its mode | `preexisting_broad_directory_is_tightened` | pass | Failure path logs path + observed mode, does not abort startup | +| New config keys documented, defaulted, validated | `config.toml` comments; `config_defaults_new_rate_limit_keys_when_absent`; `config_validate_rejects_zero_*` | pass | Zero is a hard error, not "unlimited" | +| Existing configs still load | defaults test with only `requests_per_minute` present | pass | | +| `snip-proto` unchanged | `snip-proto/` has no diff | pass | | +| `snip-sync` takes a semver-appropriate bump | 0.1.8 → 0.2.0 in `snip-sync/Cargo.toml`, `Cargo.toml`, `Cargo.lock` | pass | Public `AppState`/`Config` gained fields | +| Windows behaviour stated as out of scope | `SECURITY.md` § Server Deployment and § Known Limitations | pass | ACL enforcement not implemented | + +## 3. Production implementation evidence + +- `Config` gains `register_per_minute` and `metrics_auth_failures_per_minute`, + read from `[server.rate_limit]` or `REGISTER_PER_MINUTE` / + `METRICS_AUTH_FAILURES_PER_MINUTE`, defaulted, and validated `> 0`. +- `AppState` gains `rate_limiter: Arc`; `main.rs` passes the same + instance the gRPC service already owns. +- `http.rs::metrics_response` is now async: it computes validity first, records + `auth_failures`, then consults a `metrics-auth` failure budget and returns + `429` on exhaustion. `handle_request` adds `Retry-After: 60` for `429` and + keeps `WWW-Authenticate` on `401` only. +- `lib.rs::register` keeps `register:` and adds `register-global` with its + own message and metric increment. +- `db.rs` gains `prepare_data_directory` (creation mode `0o700`, tighten + pre-existing, warn on failure) and `restrict_database_files` (`0o600` on the + database and any existing `-wal`/`-shm`), the latter called after the schema + writes so the siblings exist. Both are Unix-only with no-op counterparts. + +## 4. Verification executed + +```bash +cargo test -p snip-sync --lib # 197 passed +cargo test --test snip_sync_lifetime -- --test-threads=1 # 7 passed, 2 ignored +cargo test --test sync_multibatch --features test-support -- --test-threads=1 # 6 passed +cargo check --workspace --all-targets # pass +``` + +Results: all pass. New unit tests: `register_global_budget_rejects_without_writing_rows`, +`server_budgets_do_not_consume_each_others_keys`, +`config_defaults_new_rate_limit_keys_when_absent`, +`config_reads_new_rate_limit_keys_from_file_and_env`, +`config_validate_rejects_zero_register_per_minute`, +`config_validate_rejects_zero_metrics_auth_failures_per_minute`, +`data_directory_is_created_owner_only`, +`database_file_is_restricted_to_owner_only`, +`preexisting_broad_directory_is_tightened`. New integration test: +`http_metrics_auth_failures_are_rate_limited`. The two ignored lifetime tests +are the pre-existing long-running ones and are unchanged. + +## 5. Invariant review + +- `snip-proto` and the gRPC message contract are unchanged. +- Below the budget, auth semantics are unchanged: missing header `401`, wrong + password `401`, valid credentials `200`. +- Metrics stays `404` when unconfigured; enabling still requires both + credentials. +- Successful scrapes never consume the failure budget. +- Registration still creates exactly one user plus one default library per + successful call. +- The per-peer registration budget remains; the global budget is additive. +- File-mode changes are Unix-only and never change data content. + +## 6. Failure and recovery review + +- Limiter windows are process-local and reset on restart; a restart cannot + leave a permanent lockout. Documented in `config.toml` and the deep dive. +- Concurrent requests race on the async limiter mutex; the bounded map and its + eviction are unchanged and the new keys cannot exceed `MAX_ENTRIES`. +- A rejected registration returns before `begin`, so no rollback path exists. +- A chmod failure is a warning, not a startup abort; a newly created directory + is created `0o700` as part of the creation call rather than chmodded after. +- `Retry-After` is advisory; an earlier retry still receives `429`. + +## 7. Migration and compatibility review + +Two new optional keys; absent keys take defaults, and an existing +`config.toml` keeps loading (proved by test). Behaviour change at release time: +more than ten registrations per minute globally now fail, and more than ten +failed metrics authentications per minute return `429`. Both are documented in +`config.toml` and must appear in `CHANGELOG.md` when the version is released — +this milestone deliberately does not edit the changelog. No storage schema +change. `snip-it` is unaffected by the `snip-sync` bump. + +## 8. Security review + +- The budget is failure-only, so it cannot be used to deny the operator their + own scrape. +- The global registration budget is separate from the per-peer budget so a + legitimate caller is not charged for an attacker's traffic on another address; + it caps total account creation, which is the actual unbounded resource. +- The constant-time credential comparison is unchanged. +- `AAD`-free concerns do not apply here; no secret is introduced. +- Unix file modes protect metadata and Argon2id hashes, not only ciphertext; + Windows ACLs remain the operator's responsibility and are documented as such. + +## 9. Documentation and operations + +- `snip-sync/config.toml` — both keys, defaults, environment overrides, the + behaviour change, and the correction of the stale `persist = false` comment. +- `architecture/server.md` — config defaults, the `/metrics` budget, and the + five-row bucket table including the two global keys and the shared limiter. +- `SECURITY.md` § Server Deployment and § Known Limitations (coordinated with + M003, which owns those sections). +- `docs/SUPPLY_CHAIN_POLICY.md`, `architecture/proto.md`, + `architecture/test-infrastructure.md` — version references updated to 0.2.0. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | Per-IP metrics budgets are not implemented | A distributed guesser is bounded only globally | Would need a peer address in the EggServe HTTP leaf; explicitly deferred by the plan | +| low | Windows ACLs are not enforced | Server data may be readable by other local accounts on Windows | Operator responsibility, documented; a future milestone could add ACL handling | +| low | `register_per_minute = 10` is a proposed default | A busy legitimate deployment could hit it | Documented; operators can raise it; the plan authorised proposing 10 | + +## 11. Roadmap disposition + +Milestone closed. M005 may proceed; nothing depends on this milestone. + +## 12. Registry updates + +`plans/registry.md` and the roadmap § 12 table record M004 as `closed`. diff --git a/plans/closure/security-assurance/005-status.md b/plans/closure/security-assurance/005-status.md new file mode 100644 index 00000000..5a122e8e --- /dev/null +++ b/plans/closure/security-assurance/005-status.md @@ -0,0 +1,151 @@ +# Security Assurance M005 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/security-assurance/005-encryption-payload-v2-read-support.md` + +Source subsystem roadmap: + +- `plans/subsystems/security-assurance-roadmap.md#milestone-005--encryption-payload-v2-read-support` + +Repository baseline reviewed: `0f3bc98` (`chore/prune-comments-and-plans`); +implementation is uncommitted. + +Implementation commits or pull requests: + +- Uncommitted working tree — `src/encryption.rs`, `src/sync.rs`, + `src/sync.rs` test re-export, `tests/sync_integration.rs`, + `architecture/encryption.md`, `.skills/encryption-module.md`. + +Primary class: infrastructure. **This milestone delivers no user-visible +capability** and must not be described as closing the substitution finding. + +## 1. Executive finding + +M005 is complete. The client reads payload version 2, verifying an AES-GCM tag +computed over associated data derived from the snippet id, while still writing +version 1. Version 0 and 1 payloads decrypt unchanged, an unknown version is +still a hard error, and the only version-2 writer is a `test-support`-gated +helper that is provably absent from the production binary. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| v2 decrypts with the correct id | `v2_roundtrip_with_the_correct_id` | pass | | +| v2 fails with a different id | `v2_fails_with_a_different_id` | pass | Fails as `DecryptionFailed`, the same class as a wrong key | +| v1 decrypts unchanged through both entry points | `v1_payloads_still_decrypt_through_both_entry_points` | pass | The id is ignored for v1 | +| Legacy version 0 decrypts unchanged | `legacy_unversioned_payloads_still_decrypt_through_both_entry_points` | pass | | +| Unknown version rejected | `test_unknown_payload_version_is_rejected` | pass | Version 3 rejected at parse and at decrypt | +| `decrypt` without an id fails loudly on v2 | `v2_without_identity_is_rejected_loudly` | pass | Explicit "requires snippet identity" error, not a tag failure | +| Empty id cannot seal a v2 payload | `v2_seal_rejects_an_empty_id` | pass | | +| Tampered v2 ciphertext still fails | `v2_tampered_ciphertext_still_fails_the_tag` | pass | | +| AAD construction is unambiguous | `aad_construction_is_unambiguous` | pass | Length prefix kills concatenation collisions | +| Mixed v1/v2 pull lands both rows with their ids | `mixed_v1_and_v2_payloads_sync_and_a_substituted_v2_row_is_skipped` | pass | Integration, real server | +| A substituted v2 row is skipped and counted | same test | pass | Appears in `skipped_ids`, absent from `snippets`, `success` stays true | +| v1-only library syncs exactly as before | `v1_only_library_still_syncs_unchanged` | pass | | +| No per-snippet KDF cost added | `argon2_params_for_version` returns the same parameters for 0/1/2; cache key unchanged in shape | pass | AAD does not affect derivation | +| v2 writer absent from production | `nm -a target/production-seam/release/snp \| grep -c seal_v2_for_test` → `0` | pass | The AAD domain string appears once because the production read path builds it | +| No proto, server, storage, or merge change | diff scope | pass | `snip-proto/`, `snip-sync/`, `src/sync_commands.rs` untouched | +| Argon2 parameters unchanged | constants untouched | pass | | + +## 3. Production implementation evidence + +- `PAYLOAD_VERSION_V2 = 2`; `from_base64` accepts 1 and 2 and rejects anything + else; `argon2_params_for_version` maps 0/1/2 to the current parameters. +- `payload_aad(id) = b"snip-payload-v2\0" ‖ u32_le(id.len()) ‖ id`. +- `seal_with_salt` and `open_payload` are the single sealing/opening paths, with + the AAD as a parameter; `encrypt_with_salt` passes an empty AAD and version 1, + so version-1 output is byte-identical. +- `decrypt_for_snippet(api_key, data, id)` is the production read entry point; + `decrypt_snippet` passes the proto row's `id`. +- `seal_v2_for_test` is `#[cfg(any(test, feature = "test-support"))]` and reuses + the production cipher and AAD helper; `src/sync.rs` re-exports it under the + same gate for integration tests. + +## 4. Verification executed + +```bash +cargo test --lib encryption # 29 passed (filtered) +XDG_CONFIG_HOME=$(mktemp -d) cargo test --workspace --lib # 1248 passed, 8 ignored; snip-sync 197 passed +cargo test --test sync_integration --features test-support # 11 passed +cargo test --test sync_multibatch --features test-support -- --test-threads=1 # 6 passed +nm -a target/production-seam/release/snp | grep -c seal_v2_for_test # 0 +``` + +Results: all pass. `cargo test --workspace --lib` required an isolated +`XDG_CONFIG_HOME` in this environment because unrelated auto-sync tests read the +developer's real config directory; that is a pre-existing condition, recorded in +§ 10. + +## 5. Invariant review + +- Version 1 payloads decrypt exactly as before; no stored payload is rewritten. +- Argon2id parameters, salt size, nonce size, and payload layout are unchanged. +- The batch-shared salt and derived-key cache still apply; no per-snippet KDF + cost returned. +- Merge order, `updated_at`, and snippet-id determinism are untouched. +- Unknown versions remain hard errors; there is no "try both" fallback. +- `snip-proto` and `snip-sync` are unchanged. + +## 6. Failure and recovery review + +- A v2 payload with an empty id cannot be decrypted; it fails as + `DecryptionFailed` and follows the existing skip-and-count path rather than + aborting the sync. +- Decryption is a pure function over the payload; cancellation, restart, and + concurrency semantics are unchanged. +- A failed v2 decrypt increments `server_decrypt_failed_count` and adds the id + to `skipped_ids`, proved by the substitution test. + +## 7. Migration and compatibility review + +- Old payloads, new client: v1 decrypts unchanged. +- New payloads, old client: not produced by this milestone. A build that writes + v2 would be unreadable by a v1-only reader, which is why the write switch is + M006 and gated on a published v2-reading release. +- No storage migration; the server treats version 2 as opaque bytes. +- No version bump: no public API change is intended, and none occurred (the + module is crate-internal). + +## 8. Security review + +- A wrong id and a wrong key are indistinguishable in kind (both + `DecryptionFailed`), so the error is not an oracle. +- The AAD is public data and is never logged. +- `decrypt` is compiled only for tests. This is a deliberate deviation from the + plan's letter (see § 10): no production caller can hold a payload without its + identity, so the identity-less entry point is a compile-time error in + production rather than a runtime rejection. The runtime rejection is still + proven by unit tests, and it removes dead code from the shipped binary. +- The test-only writer cannot reach a production build, proven by symbol count. + +## 9. Documentation and operations + +- `architecture/encryption.md` — payload version table, AAD bytes, phase split, + write path, and the key-cache interaction. +- `src/encryption.rs` module docs — the three-version read contract and why + `decrypt` rejects v2. +- `.skills/encryption-module.md` — corrected the stale "no parameter versioning" + limitation and recorded that v2 writes are not active. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | Deviation: `decrypt` is test-only rather than a shipped entry point that rejects v2 at runtime | None functionally; the compile-time boundary is stricter than the plan's runtime one | Recorded here; ADR-0002's intent (fail loudly rather than silently decrypt without AAD) is preserved | +| low | `cargo test --workspace --lib` hangs in this environment without an isolated config dir | Verification only; unrelated to this milestone | Pre-existing: several auto-sync tests read the developer's real config dir. Run with `XDG_CONFIG_HOME=$(mktemp -d)` until those tests adopt the thread-local override | +| low | The id binding protects only new payloads, and no new payload exists yet | The audited substitution path is still open for every stored row | M006, blocked on a published v2-reading release | + +## 11. Roadmap disposition + +Milestone closed; M006 remains blocked on its operational precondition (one +published `snp` release that reads v2 plus the stated minimum client version), +not on any code gap here. + +## 12. Registry updates + +`plans/registry.md` and the roadmap § 12 table record M005 as `closed`; M006 +stays `blocked`. diff --git a/plans/implementation/security-assurance/001-advisory-posture-and-license-policy.md b/plans/implementation/security-assurance/001-advisory-posture-and-license-policy.md new file mode 100644 index 00000000..d1a52b93 --- /dev/null +++ b/plans/implementation/security-assurance/001-advisory-posture-and-license-policy.md @@ -0,0 +1,313 @@ +# Security Assurance Milestone 001 — Advisory posture and license policy + +Status: closed + +Repository baseline: `0f3bc98` (`chore/prune-comments-and-plans`), with the +uncommitted dependency refresh and doc-pruning worktree state described in § 3. + +Source roadmap: + +- [`plans/subsystems/security-assurance-roadmap.md` § Milestone 001](../../subsystems/security-assurance-roadmap.md#milestone-001--advisory-posture-and-license-policy) + +Long-term requirements: + +- [`plans/000-long-term-specification.md#9-distribution-and-release-invariants`](../../000-long-term-specification.md#9-distribution-and-release-invariants) +- [`plans/000-long-term-specification.md#10-verification-and-evidence-rules`](../../000-long-term-specification.md#10-verification-and-evidence-rules) +- [`plans/001-terminology-and-domain-model.md#8-distribution-and-update-terms`](../../001-terminology-and-domain-model.md#8-distribution-and-update-terms) +- [`plans/003-planning-process.md`](../../003-planning-process.md) + +Applicable ADRs: + +- [`plans/adrs/ADR-0003-advisory-remediation-and-suppression-policy.md`](../../adrs/ADR-0003-advisory-remediation-and-suppression-policy.md) + (must be accepted before handoff) + +Primary class: infrastructure + +--- + +## 1. Objective + +Make `cargo audit` and `cargo deny check` **deterministic and green** on this +working tree by recording scoped, justified, review-dated exceptions for the +four advisory IDs that have no available fix, and by adding the one license the +dependency graph actually requires — without changing dependency sources, +without adding crates, and without relaxing the gate for future findings. + +## 2. Why this milestone is ready + +- The full finding set is reproduced and attributed (audit, 2026-11-17): + one vulnerability and three unmaintained advisories, all reachable only + through `snip-sync`'s `sqlx` and `keyring` graphs; one license finding on + `webpki-roots`. +- The remediation blocker is version arithmetic, not unknowns: + `sqlx 0.9.0` requires `libsqlite3-sys >=0.30.1, <0.38.0`; the patched release + is `>=0.39.0`; upstream's widening is merged but unpublished. +- The publishing constraint that rules out a git patch is a stated repo rule + (`plans/000-long-term-specification.md#9`), not an inference. +- ADR-0003 selects the policy; this plan only executes it. + +## 3. Current implementation evidence + +`cargo audit` (468 crate dependencies): + +```text +libsqlite3-sys 0.37.0 RUSTSEC-2026-0459 CVSS 6.8 patched >=0.39.0 +zbus_names 4.3.5 RUSTSEC-2026-0371 unmaintained, no fix +zvariant 5.15.1 RUSTSEC-2026-0370 unmaintained, no fix +zvariant_derive 5.15.1 RUSTSEC-2026-0372 unmaintained, no fix +``` + +`cargo deny check`: + +```text +advisories FAILED, bans ok, licenses FAILED, sources ok +``` + +- Vulnerability scope: bundled SQLite is compiled only into `snip-sync` + (`snip-sync/Cargo.toml:41`; `cargo tree -e features -i libsqlite3-sys` shows + `libsqlite3-sys feature "bundled"`). The `snp` client's `sqlx` edge is a + dev-dependency (`Cargo.toml:179`). +- Advisory type: local vector, uninitialized page-cache disclosure when a + crafted database plus mismatched `-wal` file is opened. +- License finding: `webpki-roots 0.26.11` and `1.0.12` declare + `CDLA-Permissive-2.0`; `deny.toml:19-30` does not allow it. +- `deny.toml:13` currently has `ignore = []` with a policy comment saying + suppressions require a fresh exploitability analysis. +- `cargo deny check licenses` also emits `license-not-encountered` for one + allowance; the audit output points at the entry on `deny.toml:22` + (`BSD-2-Clause`). Confirm from the tool output before changing it — this is a + warning, not a gate. +- `SECURITY.md` § Advisory Exceptions (lines 176-181) states + `deny.toml` carries no active suppressions. That statement becomes false the + moment this milestone lands and must be updated atomically. +- No CI workflow invokes either tool; wiring is M002. + +## 4. Invariants that must not regress + +- `Cargo.lock` stays committed and is the single resolution source. +- All dependency sources remain crates.io; `[sources] unknown-registry = deny` + and `unknown-git = deny` are untouched (`deny.toml:45-48`). +- Both published crates remain publishable: no git or path dependency enters + the release graph. +- Suppression entries name an advisory **ID only**; no crate-name or wildcard + suppressions, no global lint-level relaxation. +- The license allowlist gains exactly the license the graph requires. +- No blanket dependency refresh; the working tree's existing bumps are kept, + not extended, unless a version is required to clear a finding. + +## 5. Scope + +### In scope + +- `deny.toml`: ignore entries with structured rationale, one license addition, + cleanup of the unused allowance. +- `SECURITY.md` § Advisory Exceptions: mirror the list and the review + discipline. +- `scripts/check-advisories.sh`: deterministic local gate + policy check. +- Evidence commands and their output captured for the closure record. + +### Explicitly out of scope + +- Any dependency upgrade to a version not already in the working tree. +- `[patch.crates-io]`, git dependencies, vendoring, or switching to system + SQLite (ADR-0003 rejects all four). +- CI wiring (M002). +- Fixing the unmaintained keyring chain (no upstream fix exists). +- Changing the exploitability analysis for any finding that has no fix. + +## 6. Required production changes + +### Security and policy + +`deny.toml` `[advisories].ignore` gains exactly: + +```text +RUSTSEC-2026-0459 (SQLite bundled CVE; server-only; mitigations named) +RUSTSEC-2026-0370 (zvariant unmaintained; Linux keyring chain) +RUSTSEC-2026-0371 (zbus_names unmaintained; Linux keyring chain) +RUSTSEC-2026-0372 (zvariant_derive unmaintained; Linux keyring chain) +``` + +Each is preceded by the ADR-0003 block: ID, scope, why, added, review by +(≤ 90 days), remove when. The SQLite entry names the M004 mitigation +(`0o700` data directory, `0o600` files) as the precondition that keeps the +local vector unreachable by an unprivileged local user. + +`[licenses].allow` gains `CDLA-Permissive-2.0` with a one-line comment naming +`webpki-roots` as the consumer and stating it is a permissive data license for a +certificate-root bundle. + +### Documentation and static guards + +`SECURITY.md` § Advisory Exceptions becomes the human mirror. It carries a +machine-readable line so the check script can compare sets without parsing +prose: + +```html + +``` + +`scripts/check-advisories.sh`: + +1. fails if either tool is missing, with an install hint; +2. runs `cargo audit` and `cargo deny check`; +3. extracts `RUSTSEC-*` IDs from `deny.toml` and from the SECURITY.md marker + line and fails if the sets differ; +4. `--self-test` mode: copies `deny.toml` to a temp file with one ignore entry + removed and asserts `cargo deny check --config ` fails — proving the + gate still catches an unsuppressed finding. + +The script is POSIX-compatible bash and adds no dependency; it is not a +`check.sh` step (that would make the ordinary correctness run depend on network +and tool installation). M002 calls it from its own CI job. + +## 7. Ordered work packages + +### Work package A — Record the decision + +Intent: ADR-0003 is accepted by a maintainer before any suppression is added. + +Required changes: flip ADR-0003 to `accepted` and add a status-history line. + +Acceptance evidence: ADR diff; no `deny.toml` change in the same commit. + +### Work package B — Scoped advisory exceptions + +Intent: turn the four findings into named, removable exceptions. + +Required changes: the four ignore entries and their comment blocks; confirm +each ID against the tool output; do not suppress anything not in the audit set. + +Acceptance evidence: `cargo deny check advisories` passes; removing one entry +in a temp copy fails. + +### Work package C — License allowance + +Intent: make the license check pass without widening the policy beyond the +actual requirement. + +Required changes: add `CDLA-Permissive-2.0`; inspect the +`license-not-encountered` warning and either remove the unused entry or leave it +with a one-line justification. + +Acceptance evidence: `cargo deny check licenses` passes; the allowlist diff is +one line plus comments. + +### Work package D — Deterministic check script + +Intent: one command proves the local posture and the two-file mirror. + +Required changes: `scripts/check-advisories.sh` as specified; run it locally. + +Acceptance evidence: script output shows both tools green and the ID sets +matching; `--self-test` shows a deliberate failure. + +### Work package E — Operator-facing mirror + +Intent: the documented exception list matches the file. + +Required changes: rewrite `SECURITY.md` § Advisory Exceptions with the four +entries, the review date, and the removal conditions; add the marker line. + +Acceptance evidence: `scripts/check-advisories.sh` passes; a reader can tell +which finding is accepted and why. + +## 8. Failure, cancellation, restart, and contention semantics + +- Not applicable to runtime behavior; this milestone changes policy files and + adds a script. +- The script must be re-runnable and must not mutate the repository: the + `--self-test` temp config lives in `mktemp -d` and is removed on exit. +- If network access is unavailable, `cargo audit` fails to fetch the advisory + database; the script must report that as an environment failure, not as a + clean pass. + +## 9. Compatibility and migration + +- No source, wire, storage, or CLI change. +- `deny.toml` is excluded from the published crate (`Cargo.toml` `exclude` + list), so the policy file does not affect consumers. +- No version bump is required by this milestone. + +## 10. Required tests + +### Focused unit tests + +- None; the deliverable is policy plus a shell check. + +### Integration tests + +- `scripts/check-advisories.sh` on a clean checkout: green. +- `scripts/check-advisories.sh --self-test`: red on the deliberately + unsuppressed copy. + +### Migration and compatibility tests + +- `cargo tree -e features -i libsqlite3-sys` still shows `bundled` and still + shows the `snp` binary unaffected. +- `cargo check --workspace --all-targets` still succeeds; no lockfile churn + beyond the working tree's existing state. + +## 11. Required verification commands + +```bash +cargo audit +cargo deny check +bash scripts/check-advisories.sh +bash scripts/check-advisories.sh --self-test +cargo check --workspace --all-targets +``` + +Do not record a pass for a command that was not run. + +## 12. Documentation updates + +- `SECURITY.md` § Advisory Exceptions (mirror + review discipline). +- `deny.toml` comment blocks (policy rationale lives next to the entries). +- `plans/subsystems/security-assurance-roadmap.md` milestone status after + closure only. + +## 13. Acceptance criteria + +- `cargo audit` and `cargo deny check` both exit 0 on the committed tree. +- Exactly four advisory IDs are ignored, each with ID/scope/why/added/review + by/remove when; no crate-name or wildcard suppression exists. +- `CDLA-Permissive-2.0` is the only license addition. +- `scripts/check-advisories.sh` proves the two-file mirror and the + unsuppressed-finding failure mode. +- No dependency source, resolution, or published-crate property changed. + +## 14. Stop conditions + +Stop and report rather than improvise when: + +- ADR-0003 is not accepted; +- a suppression cannot be justified with a concrete exploitability analysis; +- an upstream fix becomes available during the work (then upgrade instead of + suppressing, and shrink the milestone); +- clearing a finding would require a source, version, or feature change that + alters the shipped dependency set; +- the tool output contains an ID that the audit did not record (new finding → + stop, analyze, do not blanket-suppress). + +## 15. Closure evidence required + +- Exact commands and their summarized output for the five verification + commands, labelled local. +- The final `deny.toml` diff and the `SECURITY.md` section. +- The `--self-test` failure transcript. +- A statement of residual risk (the bundled SQLite remains until upstream + releases) and the named removal condition. +- Confirmation that `snip-proto` and both crate versions are unchanged. + +## 16. Handoff notes + +- The advisory database is network-fetched; a sandboxed agent run may fail at + step 1 for environmental reasons. Record that as blocked, not as a pass. +- Do not run `cargo deny` with `--all-features` expectations; it reads the + lockfile and does not need feature selection. +- The working tree already contains dependency bumps and doc changes from the + prior advisory pass. Preserve them; do not reset the tree. +- `deny.toml` is local-only; `bash scripts/check.sh` does not run it. +- Keep the review date within 90 days and in `YYYY-MM-DD` form so a script can + sort it later. diff --git a/plans/implementation/security-assurance/002-ci-advisory-gates-and-action-pinning.md b/plans/implementation/security-assurance/002-ci-advisory-gates-and-action-pinning.md new file mode 100644 index 00000000..8e6bf854 --- /dev/null +++ b/plans/implementation/security-assurance/002-ci-advisory-gates-and-action-pinning.md @@ -0,0 +1,315 @@ +# Security Assurance Milestone 002 — CI advisory gates and action pinning + +Status: conditionally closed + +Repository baseline: `0f3bc98` (`chore/prune-comments-and-plans`) + +Source roadmap: + +- [`plans/subsystems/security-assurance-roadmap.md` § Milestone 002](../../subsystems/security-assurance-roadmap.md#milestone-002--ci-advisory-gates-and-action-pinning) + +Long-term requirements: + +- [`plans/000-long-term-specification.md#9-distribution-and-release-invariants`](../../000-long-term-specification.md#9-distribution-and-release-invariants) +- [`plans/000-long-term-specification.md#10-verification-and-evidence-rules`](../../000-long-term-specification.md#10-verification-and-evidence-rules) +- [`plans/003-planning-process.md`](../../003-planning-process.md) + +Applicable ADRs: + +- [`plans/adrs/ADR-0003-advisory-remediation-and-suppression-policy.md`](../../adrs/ADR-0003-advisory-remediation-and-suppression-policy.md) + (must be accepted; M001 must be closed first) + +Primary class: infrastructure + +> **Execution-policy note.** `plans/README.md` permits additional CI/release +> hardening only when a roadmap revision explicitly authorizes it. This +> milestone **is** that authorization: the security-assurance roadmap's +> M002 entry is the authorizing revision, and a reviewer should reject a CI +> change that exceeds this plan's boundary. + +--- + +## 1. Objective + +Make the advisory and license policy **enforced by CI** on every push and pull +request, and remove mutable action references from the workflows so the build +environment itself is reproducible. + +## 2. Why this milestone is ready + +- M001 leaves the local gate green and deterministic, so a blocking CI run will + not be red on day one. +- ADR-0003 fixes the suppression policy the gate consumes. +- The failure mode is proven: no workflow invokes `cargo audit` or + `cargo deny` today (`grep -rn "cargo audit\|cargo deny" .github/workflows/` + returns nothing), and the working tree reached a red gate without CI + noticing. +- Dependabot already tracks the `github-actions` ecosystem + (`.github/dependabot.yml`), so SHA pinning does not create a maintenance + dead end. + +## 3. Current implementation evidence + +`.github/workflows/ci.yml`: + +- `permissions: contents: read`; workflow-level concurrency with + `cancel-in-progress: true`; +- jobs `linux-correctness` (35-minute timeout, runs + `bash scripts/check.sh`) and `platform-smoke`; +- actions referenced by mutable tags: `actions/checkout@v5`, + `dtolnay/rust-toolchain@stable`, `Swatinem/rust-cache@v2`. + +Repository-wide action references: + +```text +11 actions/checkout@v5 (mutable tag) + 3 dtolnay/rust-toolchain@stable (mutable branch) + 2 actions/upload-artifact@v4 (mutable tag) + 2 actions/download-artifact@v4 (mutable tag) + 2 Swatinem/rust-cache@v2 (mutable tag) + 1 lycheeverse/lychee-action@e747… (SHA-pinned, link-check.yml) + 1 goto-bus-stop/setup-zig@abea… (SHA-pinned, release-binaries.yml) + 1 actions/checkout@fbc6… (SHA-pinned, link-check.yml) +``` + +`.github/workflows/release-binaries.yml` already scopes permissions tightly +(`contents: read` at workflow level, `contents: write` only on the attach job); +this milestone must not widen that. + +`deny.toml` and `SECURITY.md` are excluded from the published crate, so this +milestone does not affect consumers. + +## 4. Invariants that must not regress + +- CI stays least-privilege: `permissions: contents: read` unless a job + demonstrably needs more, and the release attach job keeps its narrow scope. +- No new secret, token, service, or third-party account enters the workflows. +- The advisory job must fail on **unexpected** findings, not warn: a policy + that only advises is not a gate. +- Local and CI verdicts agree by construction: both consume the same + `deny.toml` and the same `scripts/check-advisories.sh`. +- The existing correctness jobs' runtime and required checks are unchanged. +- `check.sh` remains the authoritative correctness gate; the advisory job is + additional, not a replacement. + +## 5. Scope + +### In scope + +- One new job in `.github/workflows/ci.yml`. +- SHA pinning of the five mutable action references listed in § 3. +- A comment convention that keeps Dependabot able to update the pins. +- Workflow-level documentation of the tool versions. + +### Explicitly out of scope + +- Release-workflow redesign, signing, attestation, artifact changes. +- Adding `cargo audit` to `scripts/check.sh` (that would make every local and + CI correctness run depend on network access and installed tools). +- A scheduled nightly advisory job (weekly Dependabot plus per-PR gating + already bounds exposure; add later only with evidence). +- Dependabot policy changes beyond verifying the existing `github-actions` + entry still works with SHA pins. +- Any Rust source, dependency, or version change. + +## 6. Required production changes + +### CI + +Add a job to `.github/workflows/ci.yml`: + +```yaml + advisory-gate: + name: Advisory and license gate + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@ # vX.Y.Z + - uses: @ # pinned; exact tool versions + with: + tool: cargo-audit@,cargo-deny@ + - name: Advisory and license policy + run: bash scripts/check-advisories.sh +``` + +Tool installation — choose one, record the choice in a workflow comment: + +- **Preferred:** a SHA-pinned installer action that fetches prebuilt binaries + (`taiki-e/install-action` is the established choice). It keeps the job short + and pins the tool versions explicitly. +- **Fallback:** `cargo install cargo-audit --locked --version ` plus + `cargo install cargo-deny --locked --version `. No third-party action, + but several minutes of compilation per run. + +Do not use an unpinned `cargo install` without `--version`. + +The job inherits the workflow-level concurrency group. It must not be added to +`linux-correctness`'s step list: a network failure in the advisory job should +not fail the correctness signal. + +### Action pinning + +Replace every mutable reference with a full 40-character commit SHA and a +trailing version comment: + +```yaml +- uses: actions/checkout@<40-hex> # v5.0.0 +- uses: Swatinem/rust-cache@<40-hex> # v2.8.0 +- uses: dtolnay/rust-toolchain@<40-hex> # stable as of YYYY-MM-DD +``` + +`dtolnay/rust-toolchain@stable` is a moving branch reference. Pin it to a SHA +and keep `with: toolchain: "1.94"` so the actual toolchain remains explicit and +reviewable. The comment must record what the ref meant when pinned, because +this action has no semver tags. + +Do not change `with:` inputs while pinning unless the pinned revision requires +it; behavior changes belong to a separate plan. + +### Documentation and static guards + +- A short comment at the top of each mutated workflow stating the pin policy + and that Dependabot maintains the SHAs through the version comments. +- Verify `.github/dependabot.yml`'s `github-actions` entry still reports + updates after pinning (Dependabot updates SHA pins when the comment carries a + version). If it does not, add the configuration it needs — do not remove + pinning. + +## 7. Ordered work packages + +### Work package A — Advisory job + +Intent: run M001's script on every push and pull request. + +Required changes: the `advisory-gate` job in `ci.yml`; pinned checkout; pinned +tool installer with exact versions. + +Acceptance evidence: a green run on a branch; a red run on a branch with one +`deny.toml` ignore entry removed (recorded, not committed). + +### Work package B — Action pinning + +Intent: replace mutable refs with immutable commits. + +Required changes: the five unique mutable refs across +`ci.yml`, `distribution-consumer-smoke.yml`, `release-binaries.yml`; version +comments on every pinned line. + +Acceptance evidence: `grep -rE "uses: [^ ]+@v[0-9]" .github/workflows/` returns +nothing; `grep -rE "uses: [^ ]+@(stable|master|main)$"` returns nothing; the +workflows still execute (CI run on the branch). + +### Work package C — Dependabot compatibility check + +Intent: keep pins current without manual toil. + +Required changes: none if the existing `github-actions` entry works; otherwise +the minimal config addition. + +Acceptance evidence: the next Dependabot run opens at least one +`github-actions` PR that updates a pinned SHA, or a recorded explanation of why +no update was available that week. + +## 8. Failure, cancellation, restart, and contention semantics + +- A missing tool on the runner is a CI failure with an install hint, not a + skipped job. Do not add `continue-on-error`. +- Network failure fetching the advisory database must fail the job; a stale + database silently passing is worse than a visible outage. +- Concurrency cancellation is inherited and safe: the gate is read-only. +- The job must not write to the repository or to caches that another job reads. + +## 9. Compatibility and migration + +- Workflow-only change; no crate, protocol, or CLI effect. +- Pinned SHAs must be updated deliberately when the upstream action releases; + Dependabot does this through PR review, which is the intended control. +- No release identity or publication change. + +## 10. Required tests + +### Focused unit tests + +- None; the deliverable is workflow configuration. + +### Integration tests + +- `scripts/check-advisories.sh` runs green in the new job. +- A deliberately unsuppressed branch produces a red job (manual evidence). +- A pinned-action workflow completes a full run on at least one platform. + +### Security and negative tests + +- Confirm the job cannot be bypassed by a pull request that edits + `deny.toml`: the gate consumes the PR's file, so a PR that adds an + unjustified suppression still passes the tool — the control is review of the + suppression block, not the tool. Record this honestly; do not claim the gate + detects policy abuse. + +## 11. Required verification commands + +```bash +# local reproduction of the job +bash scripts/check-advisories.sh + +# pinning proof +grep -rE "uses: [^ ]+@v[0-9]" .github/workflows/ || echo "no mutable tags" +grep -rE "uses: [^ ]+@(stable|master|main)$" .github/workflows/ || echo "no mutable branches" + +# workflow sanity +gh workflow view CI # or the repository UI +``` + +Do not claim a CI run that did not happen; record the run URL or run id in the +closure record. + +## 12. Documentation updates + +- Workflow header comments (pin policy, tool versions, authorization). +- `plans/subsystems/security-assurance-roadmap.md` milestone status at closure. +- No `SECURITY.md` change beyond M001's mirror; the gate is described in + § Supply Chain already. + +## 13. Acceptance criteria + +- Every push and pull request to `main` runs the advisory job; it fails on an + unexpected finding and passes on the committed policy. +- No mutable action reference remains in `.github/workflows/`. +- The job's tool versions are exact and recorded. +- Least-privilege permissions are unchanged or narrower. +- `scripts/check.sh` and the existing jobs are untouched in behavior. + +## 14. Stop conditions + +Stop and report rather than improvise when: + +- ADR-0003 is not accepted or M001 is not closed; +- the required tool installer cannot be SHA-pinned (then use the `cargo + install` fallback rather than an unpinned action); +- pinning an action requires a behavior change to keep working; +- the advisory job cannot be made deterministic on the runner (e.g. flaky + advisory-database fetch) — do not hide it with retries that mask failure; +- the change would require a repository secret or a broader token scope. + +## 15. Closure evidence required + +- The workflow diff and the pinned-ref proof commands. +- A green CI run id and a red run id from the deliberately unsuppressed branch. +- The exact tool versions used. +- A statement that no source, dependency, or release behavior changed. +- The Dependabot verification result (PR or recorded absence). + +## 16. Handoff notes + +- `gh` may be unavailable in the agent environment; if so, record the missing + run evidence as blocked rather than asserting a pass. +- Do not add `continue-on-error`, `if: always()`, or retry loops to the + advisory step. +- Keep the job out of `linux-correctness`; that job's 35-minute budget and + network-free correctness signal are deliberate. +- Version comments (`# vX.Y.Z`) are load-bearing for Dependabot; do not strip + them. +- `actions/checkout` is already SHA-pinned in `link-check.yml`; reuse that SHA + there rather than re-resolving it, and keep the two files consistent. diff --git a/plans/implementation/security-assurance/003-security-claim-reconciliation.md b/plans/implementation/security-assurance/003-security-claim-reconciliation.md new file mode 100644 index 00000000..09dacb15 --- /dev/null +++ b/plans/implementation/security-assurance/003-security-claim-reconciliation.md @@ -0,0 +1,348 @@ +# Security Assurance Milestone 003 — Security claim reconciliation + +Status: closed + +Repository baseline: `0f3bc98` (`chore/prune-comments-and-plans`) + +Source roadmap: + +- [`plans/subsystems/security-assurance-roadmap.md` § Milestone 003](../../subsystems/security-assurance-roadmap.md#milestone-003--security-claim-reconciliation) + +Long-term requirements: + +- [`plans/000-long-term-specification.md#6-sync-invariants`](../../000-long-term-specification.md#6-sync-invariants) +- [`plans/000-long-term-specification.md#8-transport-and-runtime-policy`](../../000-long-term-specification.md#8-transport-and-runtime-policy) +- [`plans/000-long-term-specification.md#10-verification-and-evidence-rules`](../../000-long-term-specification.md#10-verification-and-evidence-rules) +- [`plans/001-terminology-and-domain-model.md#5-sync-and-execution-terms`](../../001-terminology-and-domain-model.md#5-sync-and-execution-terms) + +Applicable ADRs: none. This milestone changes documentation only; it does not +change a contract. ADR-0002 supplies the payload-version wording that § Sync +Encryption must use once M005/M006 land. + +Primary class: polish + +--- + +## 1. Objective + +Make every published statement about confidentiality, integrity, transport, +and support status **match the implementation**, so a deployer can decide +whether to trust a sync server from the documentation alone. + +The deliverable is documentation and one narrow regression guard. No runtime +behavior changes. + +## 2. Why this milestone is ready + +- The contradiction is fully evidenced in the current tree (§ 3) and is not + awaiting a code change: `architecture/encryption.md` already states the + correct guarantee, so the target wording exists and is implementable today. +- The milestone has no hard dependency. It can land before M001 (different + sections of `SECURITY.md`), but the two must not edit the same lines + concurrently — coordinate if both are active. +- The stale support table and the archived-audit link are factual defects that + do not depend on any decision. + +## 3. Current implementation evidence + +### 3.1 The false confidentiality claim + +`SECURITY.md:154-160` states: + +> "Snippet content is encrypted client-side … So a compromised server cannot +> read snippet content, but it can see snippet identifiers, timestamps, and +> deletion state." + +The same document, 12 lines later (`SECURITY.md:171-174`), states that clients +send the API key as a bearer token in gRPC metadata. The API key is the Argon2id +input (`src/encryption.rs:244-272`), so a server that observes the token can +derive the same key. The two statements cannot both be true. + +`architecture/encryption.md:15-21` already states the correct guarantee: + +> "anything that can observe the bearer token (the server process itself, a +> TLS-terminating proxy, a request log) can re-derive the same Argon2id key … +> the protection this design actually provides is **transport confidentiality +> and at-rest obfuscation of snippet bodies**, not server-blindness." + +`.skills/encryption-module.md` independently says the same. So the accurate +wording exists; `SECURITY.md` and `docs/THREAT_MODEL.md` are the outliers. + +### 3.2 The false integrity claim + +`docs/THREAT_MODEL.md:223` (T3 residual risk) acknowledges that an observing +server can re-derive the key and decrypt, then concludes: + +> "It cannot forge content: the GCM tag rejects it." + +A party holding the key can produce valid ciphertext for any plaintext. The tag +rejects forgery only by parties **without** the key. The sentence must state +which party the guarantee is against. + +`docs/THREAT_MODEL.md:129` (Boundary 6) calls the content "end-to-end +encrypted", which reads as server-blindness even though the following +sentences are accurate about metadata. "End-to-end" needs one qualifying clause +or replacement. + +### 3.3 Supporting inaccuracies in the same surface + +- **Supported versions.** `SECURITY.md:5-10` lists `1.3.x`, `1.2.x`, `1.1.x`; + `Cargo.toml:3` is `1.4.1`. The current release is outside the stated support + window. +- **Audit reference.** `SECURITY.md:223-226` calls + `docs/archive/SECURITY_AUDIT.md` "detailed audit findings and the methodology"; + that file opens with "ARCHIVED — historical snapshot. Do not treat as a + current contract" and names stale paths (`src/auto_sync/spawn.rs`, + `src/config.rs`). +- **TLS semantics.** `SECURITY.md:183-203` says "Enable TLS in production" and + "use a reverse proxy", and `snip-sync/src/startup.rs:275-291` confirms + `TLS_ENABLED=true` is an assertion that a proxy terminates TLS — + `snip-sync/src/main.rs:304` builds the Tonic server with no TLS config. A + reader can reasonably conclude the server terminates TLS itself. +- **Health disclosure.** `snip-sync/src/http.rs:87-96` returns the exact + version unauthenticated; not documented as intentional. +- **Self-update integrity.** `SECURITY.md:144-150` says checksums are verified; + it does not state that there is no signature, so a compromised release + channel defeats the check (`src/update.rs:572-624`). + +### 3.4 What is already correct and must not be weakened + +- `architecture/encryption.md` trust-boundary note. +- `.skills/encryption-module.md` security-properties section. +- `SECURITY.md` § Snippet Execution / Non-Execution Guarantee (execution + boundary is accurate). +- The credential-storage section (keychain-only, refusal to downgrade) is + accurate. + +## 4. Invariants that must not regress + +- The accurate trust-boundary statement in `architecture/encryption.md` stays + the deep-dive source; `SECURITY.md` links to it rather than duplicating a + weaker version. +- No document may claim a compromised server cannot read content while the + bearer-token design remains. +- No document may claim the GCM tag prevents forgery by a key holder. +- Operational guidance stays actionable: the "use TLS / use a proxy" advice is + correct and must remain, only clarified. +- No security control is removed or relaxed by a wording change. +- The archived audit stays archived; it must not be edited into a current + contract. + +## 5. Scope + +### In scope + +- `SECURITY.md`: § Supported Versions, § Encryption, § Sync Encryption, + § Advisory Exceptions (coordinate with M001), § Server Deployment, + § Security Audit, § Known Limitations. +- `docs/THREAT_MODEL.md`: Boundary 6, T3 mitigations/residual risk, T4 wording + if needed, and a version-disclosure note. +- `README.md`: only if it repeats a claim that § 3 identifies. +- `tests/architecture.rs`: one narrow documentation guard (or a dedicated + `tests/security_claims.rs` if the architecture test's scope is code-only). + +### Explicitly out of scope + +- Any code, protocol, or configuration change. +- Adding release signing or attestation. +- Changing `TLS_ENABLED` behavior or removing `/health` version output. +- Rewriting the archived audit or deleting history. +- `CHANGELOG.md` (user-facing release notes are written at release time). +- `docs/USER_GUIDE.md` unless it repeats a false claim (it does not today). + +## 6. Required production changes + +None. This milestone changes documentation and one test file. + +### Documentation and static guards + +**`SECURITY.md` § Sync Encryption** — replace the guarantee with three +explicit statements: + +1. **What is encrypted:** `description`, `command`, `tags`; `output` never + leaves the device; routing metadata (`id`, timestamps, `device_id`, + `deleted`) is plaintext by design. +2. **What the server can do:** it stores ciphertext and cannot read content + *unless* it observes the bearer API key, which current clients send on every + request; a compromised server or TLS-terminating proxy that observes it can + derive the key and decrypt. The guarantee is transport confidentiality plus + at-rest obfuscation, not server-blindness. +3. **What the tag proves:** content integrity for parties without the key; + tampering by a key-blind party fails. It does not prevent a key holder from + forging, and it does not bind ciphertext to a snippet id until payload + version 2 (ADR-0002) is enabled. + +**`docs/THREAT_MODEL.md` Boundary 6** — replace "end-to-end encrypted" with +"content is encrypted in transit and at rest, but the server receives the +bearer key and is therefore not blind", linking the encryption deep dive. + +**`docs/THREAT_MODEL.md` T3** — keep the metadata paragraph; replace the final +forgery sentence with the key-holder distinction. Add the payload-binding +limitation with a link to ADR-0002, marked as "closing in M005/M006" rather +than as a current guarantee. + +**`SECURITY.md` § Supported Versions** — propose `1.4.x` (full support) and +`1.3.x` (security fixes only), `< 1.3` unsupported; confirm the window with the +maintainer during review. The table must never omit the version in +`Cargo.toml`. + +**`SECURITY.md` § Security Audit** — remove the "detailed audit findings" +framing. State that the archived audit is a historical snapshot, that the +current posture is this document plus the threat model, and link the archive +with its archive banner acknowledged. If a current audit summary is desired, +it belongs in a new document, not in the frozen archive. + +**`SECURITY.md` § Server Deployment** — add one sentence: the server does not +terminate TLS; `TLS_ENABLED=true` asserts that a reverse proxy does, and binding +a non-loopback address without a proxy serves plaintext. + +**`SECURITY.md` § Known Limitations** — add: `/health` discloses the exact +server version by design; the updater verifies a same-origin SHA-256 sidecar +but no signature, so release-channel compromise is out of scope. + +**Guard** — extend `tests/architecture.rs` (preferred; no new target) with a +documentation-claims check that: + +- reads `SECURITY.md` and `docs/THREAT_MODEL.md` via `include_str!`; +- fails if either contains the exact contradicted sentences + (`"cannot read snippet content"`, `"It cannot forge content"`); +- fails if `SECURITY.md` does not contain `"not server-blindness"` (the + required clarification); +- fails if the supported-versions table does not contain the major-minor of + `CARGO_PKG_VERSION`. + +Keep the assertions narrow and comment why each string is load-bearing. This +guard is intentionally about the two historical defects, not general prose +linting. + +## 7. Ordered work packages + +### Work package A — Confidentiality and integrity wording + +Intent: remove both false guarantees and state the real boundary once. + +Required changes: `SECURITY.md` § Sync Encryption; `THREAT_MODEL.md` +Boundary 6 and T3; cross-links to `architecture/encryption.md`. + +Acceptance evidence: no remaining "cannot read"/"cannot forge" claim; the +three-part statement is present; the deep dive is linked, not duplicated. + +### Work package B — Support status and audit reference + +Intent: stop telling users an unsupported release is supported and stop +presenting a frozen snapshot as current findings. + +Required changes: § Supported Versions, § Security Audit. + +Acceptance evidence: table includes `1.4.x`; the audit section labels the +archive historical. + +### Work package C — Operational clarifications + +Intent: make TLS assertion, health disclosure, and update integrity +unambiguous. + +Required changes: § Server Deployment, § Known Limitations. + +Acceptance evidence: each statement matches `startup.rs`, `main.rs`, `http.rs`, +and `update.rs` behavior. + +### Work package D — Regression guard + +Intent: prevent the two specific claims from returning. + +Required changes: the narrow assertions in `tests/architecture.rs`. + +Acceptance evidence: `cargo test --test architecture` passes; deliberately +reintroducing a false sentence fails it (recorded, not committed). + +## 8. Failure, cancellation, restart, and contention semantics + +- Not applicable to runtime behavior. +- Concurrent-edit hazard: M001 edits `SECURITY.md` § Advisory Exceptions. If + both milestones run in parallel, rebase rather than overwrite; the sections + are disjoint. + +## 9. Compatibility and migration + +- No user-visible behavior change; documentation only. +- No version bump. +- The guard adds a test target only if `tests/architecture.rs` is unsuitable; + prefer reusing it to avoid expanding the 55-target test list. + +## 10. Required tests + +### Focused unit tests + +- The documentation-claims guard passes on the corrected docs. + +### Integration tests + +- `cargo test --test architecture` (and `bash scripts/check.sh` for the + authoritative gate). + +### Security and negative tests + +- Temporarily reintroduce each forbidden sentence and confirm the guard fails; + revert. Record the transcript. + +### Migration and compatibility tests + +- None. + +## 11. Required verification commands + +```bash +cargo test --test architecture +bash scripts/check.sh +``` + +Do not claim a documentation change was verified by compilation alone. + +## 12. Documentation updates + +- `SECURITY.md` (five sections). +- `docs/THREAT_MODEL.md` (Boundary 6, T3, version disclosure). +- `tests/architecture.rs` (guard). +- No change to `architecture/encryption.md`; it is the reference. + +## 13. Acceptance criteria + +- No published document states that a compromised server cannot read snippet + content or cannot forge it. +- The bearer-key consequence is stated wherever confidentiality is claimed. +- The GCM guarantee is scoped to parties without the key. +- The payload-identity limitation is stated with the ADR-0002/M005–M006 plan. +- Supported versions include the current release. +- The archived audit is labelled historical. +- TLS assertion, `/health`, and checksum-only update semantics are explicit. +- The guard fails if either historical sentence returns. + +## 14. Stop conditions + +Stop and report rather than improvise when: + +- the maintainer wants to preserve a server-blindness claim as product + positioning (that is a product decision, not a docs edit — do not silently + soften the analysis); +- a wording change would require changing the threat model's risk rating + (record the proposed rating change instead of editing it unilaterally); +- a claim cannot be verified against code (state it as unverified rather than + asserting it). + +## 15. Closure evidence required + +- The final text of each changed section (or a diff). +- Guard pass and the deliberately failing transcript. +- A statement that no runtime behavior or contract changed. +- The maintainer-confirmed support window. + +## 16. Handoff notes + +- `architecture/encryption.md` is the source of truth for the crypto + description; copy its meaning, not its line numbers. +- Do not reference `src/` line numbers in user-facing docs; they rot. Cite + modules and contracts instead. +- If M001 is in flight, coordinate on `SECURITY.md`; § Advisory Exceptions is + M001's, the rest is this milestone's. +- Keep the wording direct. The current defect is euphemism, not missing detail. diff --git a/plans/implementation/security-assurance/004-server-abuse-resistance-and-local-file-hygiene.md b/plans/implementation/security-assurance/004-server-abuse-resistance-and-local-file-hygiene.md new file mode 100644 index 00000000..a0e6a64c --- /dev/null +++ b/plans/implementation/security-assurance/004-server-abuse-resistance-and-local-file-hygiene.md @@ -0,0 +1,377 @@ +# Security Assurance Milestone 004 — Server abuse resistance and local file hygiene + +Status: closed + +Repository baseline: `0f3bc98` (`chore/prune-comments-and-plans`) + +Source roadmap: + +- [`plans/subsystems/security-assurance-roadmap.md` § Milestone 004](../../subsystems/security-assurance-roadmap.md#milestone-004--server-abuse-resistance-and-local-file-hygiene) + +Long-term requirements: + +- [`plans/000-long-term-specification.md#4-crate-and-module-ownership`](../../000-long-term-specification.md#4-crate-and-module-ownership) +- [`plans/000-long-term-specification.md#8-transport-and-runtime-policy`](../../000-long-term-specification.md#8-transport-and-runtime-policy) +- [`plans/000-long-term-specification.md#10-verification-and-evidence-rules`](../../000-long-term-specification.md#10-verification-and-evidence-rules) +- [`plans/001-terminology-and-domain-model.md#7-server-terms`](../../001-terminology-and-domain-model.md#7-server-terms) + +Applicable ADRs: none. The change stays inside the existing server lifecycle +and auth contracts; it adds budgets and file modes, not a protocol. + +Primary class: invariant + +--- + +## 1. Objective + +Bound the work a caller can impose on the two server surfaces that check a +credential or create an account, and make server-owned data readable only by +the service account on Unix — without changing the gRPC wire contract, the +`snip-proto` version, or the sync semantics. + +## 2. Why this milestone is ready + +- `snip-sync` already owns a bounded, process-local rate limiter with eviction + (`snip-sync/src/rate_limiter.rs`), used by every authenticated gRPC path. The + change reuses that primitive instead of inventing one. +- The two unbounded surfaces are precisely identified: metrics basic auth + (`snip-sync/src/http.rs:146-199`) and unauthenticated registration + (`snip-sync/src/lib.rs:1050-1122`). +- The file-mode gap is a contrast inside one crate: the config file is + chmodded (`snip-sync/src/bootstrap.rs:54-60`), the database is not + (`snip-sync/src/db.rs:329-344`). +- No proto change is required; the limiter and file modes are process-local. + +## 3. Current implementation evidence + +### 3.1 Metrics authentication has no budget + +`snip-sync/src/http.rs:146-199` decodes `Authorization: Basic`, compares with +`subtle::ConstantTimeEq` and a length check (`:169-175`), and on failure +increments `snip_sync_auth_failures_total` (`:181`). There is no limiter and no +lockout: guesses are bounded only by connection handling. The endpoint exists +only when both `metrics_username` and `metrics_password` are configured; +otherwise it returns `404` (`:150-156`). + +The HTTP leaf receives only `RequestHead` +(`eggserve_server::service_fn_head`), which carries no peer address, so a +per-IP budget is not available in the current handler shape. A **global** +failure budget is therefore the correct bounded design; it cannot lock out a +legitimate scraper because successful requests do not consume it. + +### 3.2 Registration is bounded only per peer + +`snip-sync/src/lib.rs:1050-1122`: `Register` authenticates nothing, inserts one +`users` row plus one default `libraries` row per call (`db.create_user`, +`snip-sync/src/db.rs:487-522`), and is limited only by +`register:` (`lib.rs:1064-1082`). An attacker with many addresses grows +the database without a global ceiling. + +### 3.3 The database ignores the private-file policy + +`snip-sync/src/db.rs:329-344` creates the parent directory with +`create_dir_all` and lets SQLite create `snippets.db`, `-wal`, and `-shm` +under the process umask. Only the config file is restricted +(`snip-sync/src/bootstrap.rs:54-60`, mode `0o600`). Contents are ciphertext, but +metadata and Argon2id hashes are exposed to any local reader. + +### 3.4 The shared limiter is per service, not per process + +`AppState` is `{ config, metrics, db }` (`snip-sync/src/lib.rs:627-631`); +`SnipSyncService` owns the `Arc` (`:633-638`), created once in +`snip-sync/src/main.rs:169` and passed only to the gRPC service (`:226`). The +HTTP service receives `AppState` (`:218`, `:268`). + +### 3.5 Tests that must not regress + +`tests/snip_sync_lifetime.rs` locks the HTTP wire behavior (status codes, +`Allow`, `Vary`, security headers), and `snip-sync/src/lib.rs` tests lock the +auth status codes. A new `429` must be added deliberately, not accidentally: +the failure budget is configurable and test server configs must raise it +unless a test is specifically exercising the budget. + +## 4. Invariants that must not regress + +- `snip-proto` and the gRPC message contract are unchanged. +- Existing auth semantics are unchanged below the budget: wrong password is + `401`, missing header is `401`, valid credentials are `200`. +- The metrics endpoint stays `404` when unconfigured; enabling it still + requires both credentials. +- Successful metrics requests never consume the failure budget; an attacker + cannot deny metrics to the operator by burning the budget. +- Registration still creates exactly one user + default library per successful + call; a rejected call creates no rows. +- The per-peer registration budget remains; the new global budget is additive. +- File-mode changes are Unix-only and never change data content. + +## 5. Scope + +### In scope + +- `snip-sync/src/http.rs`, `snip-sync/src/lib.rs`, `snip-sync/src/main.rs`, + `snip-sync/src/db.rs`, `snip-sync/src/bootstrap.rs`. +- `snip-sync/config.toml` (two new documented keys). +- `snip-sync` version bump required by the public interface change. +- Focused tests and the serial lifetime target. + +### Explicitly out of scope + +- Per-IP metrics budgets (no peer address in the leaf; would require changing + the service shape or the EggServe API). +- Persistent rate-limit state across restarts (the module documents + process-local windows as intentional). +- Removing `/health` version output. +- Changing registration to require an invite or admin approval. +- Windows ACL enforcement (documented as out of scope). +- Changing gRPC auth, Argon2 parameters, or library scoping. + +## 6. Required production changes + +### Runtime and concurrency + +Share one `Arc` between the gRPC service and the HTTP state: + +- add `rate_limiter: Arc` to `AppState` and construct both from + the instance created in `main.rs:169` (or pass it to `http::service`; prefer + the `AppState` field so the service signature stays stable); +- keep distinct key namespaces: peer addresses for gRPC, `metrics-auth` and + `register-global` for the new budgets. The limiter's `MAX_ENTRIES` bound and + eviction already cover the added keys. + +### Security and authorization + +**Metrics failure budget.** In `metrics_response`, compute `valid` first. If +valid, serve. If invalid: + +1. `record_auth_failure()` as today; +2. `allow("metrics-auth", config.metrics_auth_failures_per_minute, 60s)`; +3. if the budget is exhausted, return `429` with the existing plain-text body + and `Retry-After: 60`; otherwise return `401` with the existing + `WWW-Authenticate` challenge. + +Document the 12th-and-later behavior and the fact that the budget is global. +A `429` must not carry `WWW-Authenticate` (that would invite more attempts). + +**Registration global budget.** Before `create_user`: + +- keep the existing `register:` check; +- add `allow("register-global", config.register_per_minute, 60s)`; +- on exhaustion return `Status::resource_exhausted` with a distinct message and + record the rate-limit metric; no rows are written. + +**Configuration.** Add to `[server.rate_limit]`: + +```toml +register_per_minute = 10 +metrics_auth_failures_per_minute = 10 +``` + +Environment overrides `REGISTER_PER_MINUTE` and +`METRICS_AUTH_FAILURES_PER_MINUTE`; both parsed and validated `> 0` in +`Config::validate` alongside the existing checks (`snip-sync/src/lib.rs:595-620` +pattern). Zero is a hard configuration error, not "unlimited": a zero budget +would make registration impossible and is almost certainly a mistake. + +### Storage and migrations + +**Private server data (Unix).** + +- When creating the database parent directory, create it `0o700` and, if it + already exists, tighten it to `0o700` when possible; a failure to tighten an + existing directory logs a warning naming the path and the observed mode + (mirror the config-file permission warning in `snip-sync/src/lib.rs:349-370`). +- After the pool connects, `chmod 0o600` the database file and any existing + `-wal`/`-shm` siblings; a failure logs a warning. +- Do not fail startup on a permission failure for a pre-existing path: a + read-only or administrator-managed deployment may legitimately be unable to + chmod. Newly created directories must be created with the mode at creation, + not chmodded afterwards, to avoid a window. + +### Frontend or operator surface + +`snip-sync/config.toml` documents both new keys, their defaults, their +environment overrides, and the behavior change: a public deployment that +registers more than ten devices per minute must raise the key. + +### Versioning + +The public `AppState` and `Config` gain fields. `snip-sync` is pre-1.0; +take the semver-appropriate **minor** bump (0.1.8 → 0.2.0) and record it in +the closure evidence. `snip-proto` and `snip-it` are unchanged. No publish is +part of this milestone; the version bump only prepares the release. + +## 7. Ordered work packages + +### Work package A — Share the limiter + +Intent: one bounded structure for both listeners. + +Required changes: `AppState` field, `main.rs` wiring, gRPC service construction +reuses the same `Arc`. + +Acceptance evidence: a unit test constructing both services with one limiter +observes a key written by one path and read by the other. + +### Work package B — Metrics failure budget + +Intent: cap password guesses without giving an attacker a denial switch. + +Required changes: the failure-only budget, `429` + `Retry-After`, config key, +validation, and the no-lockout property test. + +Acceptance evidence: 10 failures → `401`; 11th → `429`; a success after the +budget is exhausted still returns `200` (because successes do not consult it). + +### Work package C — Registration global budget + +Intent: bound account creation independently of the caller's address. + +Required changes: the global check, config key, validation, typed status, +metric increment. + +Acceptance evidence: with a low configured ceiling, N+1 registrations from +distinct peer addresses are rejected after the ceiling; no partial rows exist +for rejected calls. + +### Work package D — Private database paths + +Intent: make the data directory and files owner-only on Unix. + +Required changes: the creation/chmod helper, calls from `Database::connect` +(and `snip-sync init` bootstrap if it creates the directory), warning path. + +Acceptance evidence: `#[cfg(unix)]` tests assert `0o700` on the directory and +`0o600` on the database; a pre-existing `0o755` directory is tightened or +warned with its mode named. + +## 8. Failure, cancellation, restart, and contention semantics + +- Limiter windows are process-local and reset on restart; this is documented + and unchanged. A restart must not leave a permanent lockout. +- Concurrent requests race on the async limiter mutex; the bounded map and + eviction are unchanged, and the added keys cannot exceed `MAX_ENTRIES`. +- A rejected registration returns before `begin`; no transaction is opened, so + no rollback path is added. +- A chmod failure is a warning, not a startup abort; a newly created directory + that cannot be created `0o700` is a hard error (creation mode is part of the + creation call). +- `Retry-After` is advisory; clients may retry earlier and receive `429`. + +## 9. Compatibility and migration + +- Two new optional config keys; absent keys take the defaults. Existing + `config.toml` files keep loading. +- Behavior change: more than ten registrations per minute globally now fail; + more than ten failed metrics authentications per minute now return `429`. + Both are documented in `config.toml` and must appear in `CHANGELOG.md` at + release time. +- No proto, storage-schema, or gRPC-status change for authenticated callers. +- `snip-sync` minor version bump; `snip-it` unaffected. + +## 10. Required tests + +### Focused unit tests + +- `RateLimiter` key isolation: `metrics-auth` exhaustion does not affect + `register-global` or a peer-address key. +- Config validation rejects zero for both new keys and accepts defaults when + absent. + +### Integration tests + +- `tests/snip_sync_lifetime.rs`: unchanged behavior for the first N failures; + new `429` case added with a low configured ceiling; `Retry-After` present; + no `WWW-Authenticate` on `429`. +- Registration: a low global ceiling rejects the N+1th call with + `resource_exhausted` and leaves the user count unchanged. + +### Restart and recovery tests + +- Restarting the service clears the budget (documented process-local + behavior); no persisted state is created. + +### Contention and cancellation tests + +- Concurrent registration attempts at the ceiling produce at most the + configured number of successful inserts. + +### Security and negative tests + +- Successful metrics auth after exhaustion still returns `200`. +- A wrong password never returns `200`, and the constant-time comparison is + unchanged. +- Unix permission test for the directory and database; skip on non-Unix. + +### Migration and compatibility tests + +- An existing config without the new keys loads with defaults. +- Existing lifetime wire-parity cases still pass unchanged. + +## 11. Required verification commands + +```bash +cargo test -p snip-sync --lib +cargo test --test snip_sync_lifetime --features test-helpers -- --test-threads=1 +cargo test --workspace --lib +bash scripts/check.sh +bash scripts/ci/test-production-seams.sh +``` + +`snip_sync_lifetime` and any concurrency target stay serial. + +## 12. Documentation updates + +- `snip-sync/config.toml` (two keys, defaults, overrides, behavior change). +- `SECURITY.md` § Server Deployment (registration and metrics budgets; + private data directory) — coordinate with M003, which edits the same section. +- `CHANGELOG.md` at release time, not in this milestone. +- `architecture/server.md` if it enumerates config keys or auth surfaces. + +## 13. Acceptance criteria + +- Metrics authentication is bounded by a documented, configurable failure + budget; a valid request is never blocked by that budget. +- Registration has a global budget distinct from the per-peer budget; rejected + calls write no rows. +- On Unix, the server's database directory is `0o700` and its files `0o600` + when created; an existing broader path is tightened or warned with its mode. +- New config keys are validated, documented, and optional. +- `snip-proto` is unchanged; `snip-sync` takes a minor bump. + +## 14. Stop conditions + +Stop and report rather than improvise when: + +- sharing the limiter requires changing the EggServe service shape (then split + the milestone rather than widening it); +- a permission change would break a documented multi-user deployment (record + the conflict; do not silently drop the restriction); +- the lifetime parity tests cannot accommodate a `429` without weakening their + assertions (stop for an explicit wire-contract decision); +- the registration ceiling needs product input on the default (propose 10/min + and record the assumption rather than choosing silently). + +## 15. Closure evidence required + +- The limiter-sharing diff and the isolation test. +- Status-code transcripts for `401` → `429` and the success-after-exhaustion + case. +- Registration ceiling transcript with row counts before/after. +- Unix mode assertions (`stat` output or test output). +- Config-validation evidence and the final defaults. +- The version bump and a statement that `snip-proto` is unchanged. + +## 16. Handoff notes + +- `snip-sync/src/lib.rs` is large; keep changes localized to the service + methods and the config struct. HTTP policy stays in `http.rs`. +- The HTTP leaf has no peer address today; do not invent one from + `X-Forwarded-For` without the trusted-proxy config used by gRPC. +- Tests construct `AppState`/`Config` literally; adding fields breaks every + literal. Use `..Default::default()` where possible or update all constructors + in the same commit — this is the main mechanical hazard. +- `tests/snip_sync_lifetime.rs` is wire-parity sensitive; read it before + changing status codes, `Allow`, `Vary`, or headers. +- `cargo test --workspace --all-features -- --test-threads=1` is the full + serial suite; do not run it concurrently with a `cargo build` that replaces + `target/debug/snp`. diff --git a/plans/implementation/security-assurance/005-encryption-payload-v2-read-support.md b/plans/implementation/security-assurance/005-encryption-payload-v2-read-support.md new file mode 100644 index 00000000..3e3113f5 --- /dev/null +++ b/plans/implementation/security-assurance/005-encryption-payload-v2-read-support.md @@ -0,0 +1,329 @@ +# Security Assurance Milestone 005 — Encryption payload v2 read support + +Status: closed + +Repository baseline: `0f3bc98` (`chore/prune-comments-and-plans`) + +Source roadmap: + +- [`plans/subsystems/security-assurance-roadmap.md` § Milestone 005](../../subsystems/security-assurance-roadmap.md#milestone-005--encryption-payload-v2-read-support) + +Long-term requirements: + +- [`plans/000-long-term-specification.md#6-sync-invariants`](../../000-long-term-specification.md#6-sync-invariants) +- [`plans/000-long-term-specification.md#10-verification-and-evidence-rules`](../../000-long-term-specification.md#10-verification-and-evidence-rules) +- [`plans/001-terminology-and-domain-model.md#synced-fields`](../../001-terminology-and-domain-model.md#synced-fields) + +Applicable ADRs: + +- [`plans/adrs/ADR-0002-encryption-payload-identity-binding.md`](../../adrs/ADR-0002-encryption-payload-identity-binding.md) + (must be accepted before handoff) + +Primary class: infrastructure + +> This milestone delivers **no user-visible capability**. It must not be +> described as closing the substitution finding; that is M006. + +--- + +## 1. Objective + +Teach the client to **read** payload version 2, where the AES-256-GCM tag is +verified against associated data derived from the snippet id, while it keeps +**writing** version 1 so no existing device loses the ability to decrypt. + +## 2. Why this milestone is ready + +- ADR-0002 fixes the AAD byte construction and the two-phase rollout. +- The payload already carries a version byte and a magic prefix + (`src/encryption.rs:139-149`), so no wire or proto change is needed. +- `from_base64` already branches on the magic and rejects unknown versions + (`src/encryption.rs:182-228`); the change extends an existing dispatch rather + than restructuring it. +- The derived-key cache key already includes the version + (`src/encryption.rs:252`), so a second version does not disturb cache + semantics. +- M006 (writes) is registered and blocked on this milestone plus a release + precondition; the rollout is explicit. + +## 3. Current implementation evidence + +- `PAYLOAD_VERSION: u8 = 1`; `PAYLOAD_VERSION_LEGACY: u8 = 0` + (`src/encryption.rs:145-149`). +- `EncryptedPayload::from_base64` accepts only `PAYLOAD_VERSION` when the magic + is present and errors with `Unsupported payload version {version}` + (`src/encryption.rs:188-194`). Without the magic it parses a legacy payload as + version 0 (`:211-227`). +- `argon2_params_for_version` maps versions 0 and 1 to the same parameters and + returns `None` for anything else (`src/encryption.rs:235-242`). +- `encrypt_with_salt` seals with `cipher.encrypt(&nonce, plaintext.as_bytes())` + — no AAD — and writes `version: PAYLOAD_VERSION` + (`src/encryption.rs:316-342`). +- `decrypt` parses, derives, and seals with `cipher.decrypt(&nonce, ciphertext)` + — no AAD (`src/encryption.rs:344-369`). +- `decrypt_snippet` calls `encryption::decrypt(api_key, &snippet.command)` with + no identity input (`src/sync.rs:1622-1637`; the same decrypt path is reached + from the pull loop at `src/sync.rs:919-926`). +- `encrypt_snippet` covers only `description`, `command`, `tags` + (`src/sync.rs:333-338`); `id` is a plaintext proto field. +- The batch path shares one salt across the batch and relies on the key cache + (`src/sync.rs:1578-1593`); AAD does not change that cost. +- Existing tests cover roundtrip, wrong key, tampered ciphertext/nonce/salt, + and invalid base64 (`src/encryption.rs:371-560`). + +## 4. Invariants that must not regress + +- Version 1 payloads decrypt exactly as today, indefinitely; no stored payload + is rewritten. +- Argon2id parameters, salt size, nonce size, and payload layout are unchanged. +- No per-snippet KDF cost increase: the batch-shared salt and cache still hit. +- The client merge order, `updated_at` semantics, and snippet-id determinism + are untouched. +- `decrypt` without identity input must fail loudly on v2 rather than guessing + or skipping AAD. +- Unknown versions remain hard errors; no "try both" fallback. +- `snip-proto` and `snip-sync` are unchanged. + +## 5. Scope + +### In scope + +- `src/encryption.rs`: version 2 parsing, AAD construction, dispatch, the + identity-aware decrypt entry point, and the explicit error from the + id-less entry point. +- `src/sync.rs`: pass the snippet id into the decrypt path. +- Tests, including a `test-support`-gated v2 fixture writer for integration + tests. +- `architecture/encryption.md` payload-format section. + +### Explicitly out of scope + +- Writing v2 (M006). +- Library-id or device-id binding (deferred by ADR-0002). +- Any proto, server, storage, or merge change. +- Key-cache redesign. +- Version bumps (release-time decision; no public API change is intended). + +## 6. Required production changes + +### Core/domain + +Add to `src/encryption.rs`: + +```rust +const PAYLOAD_VERSION_V2: u8 = 2; + +fn payload_aad(snippet_id: &str) -> Vec { + let mut aad = Vec::with_capacity(13 + snippet_id.len()); + aad.extend_from_slice(b"snip-payload-v2"); + aad.push(0); + aad.extend_from_slice(&(snippet_id.len() as u32).to_le_bytes()); + aad.extend_from_slice(snippet_id.as_bytes()); + aad +} +``` + +The domain tag and the length prefix are part of the contract: the tag +separates this use from any future AAD use, and the length prefix removes +concatenation ambiguity. ADR-0002 is normative if this snippet and the ADR ever +disagree. + +### Protocol and DTOs + +- `from_base64` accepts `PAYLOAD_VERSION` and `PAYLOAD_VERSION_V2`; anything + else stays `InvalidData`. +- `argon2_params_for_version` returns the current parameters for 0, 1, and 2. +- Add `pub(crate) fn decrypt_for_snippet(api_key: &str, data: &str, snippet_id: + &str) -> CryptoResult`: + - parse the payload; + - version 2 → pass `Some(payload_aad(snippet_id))` to a shared decrypt core; + - version 0/1 → pass no AAD; + - return the same typed errors as today. +- Keep `pub fn decrypt` as the identity-less entry point: version 2 returns + `CryptoError::InvalidData("payload version 2 requires snippet identity")`. + This is deliberate: silently decrypting without AAD would void the binding. + +Refactor the shared sealing/opening body so v1 and v2 use one code path with an +`Option<&[u8]>` AAD, rather than duplicating the cipher setup. + +### Runtime and concurrency + +No change. The key cache remains keyed by `(hashed api key, base64 salt, +version)`; v1 and v2 of the same salt derive the same key bytes but are cached +separately. That is acceptable and documented; do not "optimize" the key to drop +the version without re-checking KDF-parameter versioning. + +### Security and authorization + +No authorization change. The AAD is public and derived only from the id. A +wrong id must fail as `DecryptionFailed` (tag mismatch), identical to a wrong +key, so the error is not an oracle. + +### Documentation and static guards + +- `architecture/encryption.md`: document version 2, the AAD bytes, the + read/write phase split, and the fact that v1 remains readable. +- `src/encryption.rs` module docs: state the two-version read contract. + +## 7. Ordered work packages + +### Work package A — Version 2 parsing and parameters + +Intent: accept the version without changing decryption behavior for v1. + +Required changes: constant, `from_base64`, `argon2_params_for_version`. + +Acceptance evidence: unit test that a v2 header parses and a v3 header is +rejected; existing v1 tests unchanged. + +### Work package B — AAD decrypt core + +Intent: verify the tag against the id when, and only when, the payload says v2. + +Required changes: AAD helper, shared open function with optional AAD, +`decrypt_for_snippet`, the explicit error in `decrypt`. + +Acceptance evidence: v2 roundtrip via a fixture; wrong id fails; v1 still +decrypts through both entry points. + +### Work package C — Sync integration + +Intent: the pull path supplies the id. + +Required changes: `decrypt_snippet` uses `decrypt_for_snippet(api_key, +&proto.command, &proto.id)`. + +Acceptance evidence: a pulled library containing one v1 and one v2 row lands +both with their original ids; a substituted v2 row is skipped and counted in +`server_decrypt_failed_count`. + +### Work package D — Test fixture + +Intent: make v2 payloads constructible in integration tests without a +production writer. + +Required changes: a `#[cfg(any(test, feature = "test-support"))]` helper that +seals a v2 payload with a supplied id and salt. It must be absent from +production builds and must reuse the production cipher/AAD code, not a copy. + +Acceptance evidence: `strings`/`nm` or a cfg review shows the helper is gated; +integration tests compile with `--features test-support`. + +## 8. Failure, cancellation, restart, and contention semantics + +- A v2 payload with a missing or empty id cannot be decrypted; the sync path + already requires an id (`snippet.id.is_empty()` is rejected on push), and a + server row always carries one. If a malformed row arrives with an empty id, + decryption fails as `DecryptionFailed` and the snippet is skipped — no panic. +- Cancellation, restart, and concurrency semantics are unchanged; the + operation is a pure function over the payload. +- A failed v2 decrypt must follow the existing skip-and-count path + (`src/sync.rs:919-926`), not abort the whole sync. + +## 9. Compatibility and migration + +- **Old client, new payload:** not produced in this milestone; M006 owns that + compatibility decision. +- **New client, old payload:** v1 decrypts unchanged. +- **Downgrade:** a future M006 build's v2 writes are unreadable by this build; + that is why M006 is a separate, gated milestone. +- No storage migration; the server remains oblivious to the version byte. + +## 10. Required tests + +### Focused unit tests + +- v2 roundtrip with the correct id. +- v2 with a different id fails with `DecryptionFailed`. +- v2 with a truncated/oversized AAD input still fails cleanly (no panic). +- `decrypt` on v2 returns the explicit identity error, not a tag error. +- Unknown version 3 rejected. +- Existing v1 roundtrip, wrong-key, and tamper tests still pass. + +### Integration tests + +- Mixed v1/v2 pull in `tests/sync_integration.rs` (with `test-support`). +- A substituted payload (v2 sealed for id A, delivered as id B) is skipped and + counted; the rest of the library syncs. +- v2 snippet keeps its id through decrypt → save → load (identity guard). + +### Restart and recovery tests + +- None specific; an interrupted sync already re-delivers idempotently. + +### Contention and cancellation tests + +- None specific; decrypt is pure and the batch loop is unchanged. + +### Security and negative tests + +- The wrong-id failure is indistinguishable from a wrong-key failure in kind. +- The test-only v2 writer is absent from a production build (cfg review). + +### Migration and compatibility tests + +- A library containing only v1 payloads syncs exactly as before. + +## 11. Required verification commands + +```bash +cargo test --workspace --lib +cargo test --test sync_integration --features test-support +cargo test --test sync_multibatch --features test-support -- --test-threads=1 +bash scripts/check.sh +bash scripts/ci/test-production-seams.sh +``` + +## 12. Documentation updates + +- `architecture/encryption.md` (payload versions, AAD, phase split). +- `src/encryption.rs` module doc (read contract). +- No `SECURITY.md` change here; M003 owns the claim wording and should be + coordinated so it does not describe v2 as already written. + +## 13. Acceptance criteria + +- A v2 payload decrypts only with the id it was sealed for. +- Version 1 decrypts unchanged through both entry points. +- `decrypt` without an id fails loudly on v2. +- No proto, server, storage, KDF-parameter, or merge-order change. +- The v2 writer exists only under test/test-support. +- The sync pull path supplies the id and preserves it. + +## 14. Stop conditions + +Stop and report rather than improvise when: + +- ADR-0002 is not accepted; +- the AAD construction in this plan and the ADR disagree (the ADR wins; stop + and reconcile); +- a v2 payload can be produced by any production path (that is M006, and + shipping it here would break old devices); +- the id supplied by the pull path is not the id the writer used (investigate + identity stability before proceeding); +- making `decrypt` reject v2 breaks an existing caller that cannot supply an id + (enumerate callers first; do not add a silent default). + +## 15. Closure evidence required + +- The encryption diff and the AAD byte layout as implemented. +- Unit transcript: correct id, wrong id, v1 unaffected, unknown version. +- Mixed-pull integration transcript with counters. +- Confirmation that no production v2 writer exists (`grep` on the cfg gates). +- Statement that `snip-proto`, `snip-sync`, merge order, and KDF parameters are + unchanged. + +## 16. Handoff notes + +- `src/encryption.rs` is heavily unit-tested; follow the existing test naming + and keep the tamper tests. +- Do not change `ARGON2_*` constants. ADR-0002 and the module doc both state + that a parameter change requires a new version. +- `decrypt` is used by tests and by `decrypt_snippet`; enumerate every caller + before changing its behavior. +- The `test-support` helper must live behind + `#[cfg(any(test, feature = "test-support"))]`; `scripts/ci/test-production-seams.sh` + will not catch this one (it checks runtime seams, not symbols), so review the + cfg gate explicitly. +- Integration targets need `--features test-support`; follow `scripts/check.sh` + flags rather than inventing them. diff --git a/plans/implementation/security-assurance/006-enable-v2-payload-writes.md b/plans/implementation/security-assurance/006-enable-v2-payload-writes.md new file mode 100644 index 00000000..a474a96b --- /dev/null +++ b/plans/implementation/security-assurance/006-enable-v2-payload-writes.md @@ -0,0 +1,296 @@ +# Security Assurance Milestone 006 — Enable v2 payload writes + +Status: blocked + +Repository baseline: to be re-baselined at handoff; this plan is written against +`0f3bc98` and M005's implemented shape. + +Source roadmap: + +- [`plans/subsystems/security-assurance-roadmap.md` § Milestone 006](../../subsystems/security-assurance-roadmap.md#milestone-006--enable-v2-payload-writes) + +Long-term requirements: + +- [`plans/000-long-term-specification.md#6-sync-invariants`](../../000-long-term-specification.md#6-sync-invariants) +- [`plans/000-long-term-specification.md#9-distribution-and-release-invariants`](../../000-long-term-specification.md#9-distribution-and-release-invariants) +- [`plans/000-long-term-specification.md#10-verification-and-evidence-rules`](../../000-long-term-specification.md#10-verification-and-evidence-rules) + +Applicable ADRs: + +- [`plans/adrs/ADR-0002-encryption-payload-identity-binding.md`](../../adrs/ADR-0002-encryption-payload-identity-binding.md) + (must be accepted; phase 2 is the decision recorded there) + +Primary class: invariant + +--- + +## 1. Objective + +Switch the client's write path to payload version 2 so every **new** sealed +payload is cryptographically bound to its snippet id, while version 1 payloads +remain readable. + +## 2. Why this milestone is ready + +It is **not** ready today. It is registered so the work is not lost, and it is +blocked on two named conditions: + +1. **Hard — satisfied:** M005 is closed + (`plans/closure/security-assurance/005-status.md`). Version 2 parsing, the + AAD, and the identity-aware decrypt path exist and are tested; + `decrypt_for_snippet` supplies the row id and `seal_v2_for_test` is the only + v2 writer (test-only, absent from the production binary). +2. **Operational — outstanding:** one published `snp` release that reads + version 2 is available, and the minimum supported client version that + includes it is stated in `SECURITY.md` (M003 owns the wording; this milestone + consumes it). + +Do not start until the operational condition is recorded in the release history. +M005 being closed is necessary but not sufficient: shipping the write switch +before a v2-reading release exists would strand every older device. + +## 3. Current implementation evidence + +- The write path always emits `PAYLOAD_VERSION` (1) with no AAD + (`src/encryption.rs:316-342`). +- `encrypt_snippet` and `encrypt_snippet_with_salt` seal a JSON object of + `description`, `command`, `tags`; the id is not passed to the cipher + (`src/sync.rs:1516-1545`). +- The batch path encrypts per snippet with a shared salt + (`src/sync.rs:1580-1593`), so the id is available at the call site + (`s.id`). +- After M005, `from_base64` accepts 1 and 2, `decrypt_for_snippet` verifies the + AAD, and `decrypt` rejects v2. +- A v1-only reader (any client built before M005) cannot read a v2 payload; it + counts the row as `server_decrypt_failed_count` and skips it + (`src/sync.rs:919-926`). + +## 4. Invariants that must not regress + +- Version 1 payloads remain readable forever; no stored payload is rewritten or + migrated. +- No proto, server, storage, merge-order, or KDF-parameter change. +- A snippet's id never changes as a consequence of encryption or decryption; + the AAD input must be the same id the server stores. +- The batch salt optimization and key cache still apply; per-snippet Argon2id + cost must not return. +- `output` stays local-only; the encrypted field set is unchanged. +- No silent fallback: if a v2 seal fails, the snippet is reported as an + encryption failure, not downgraded to v1. + +## 5. Scope + +### In scope + +- The seal path in `src/encryption.rs` and the id threading in + `src/sync.rs`. +- Tests proving v2 writes, v1 reads, and the downgrade failure mode. +- `CHANGELOG.md` and the minimum-client-version statement. +- Closure of the audit finding L8 in the closure record. + +### Explicitly out of scope + +- Library-id or device-id binding (new ADR required). +- Any change to the server or proto. +- Re-encrypting existing v1 payloads in place. +- A configuration flag to choose the payload version (the phase gate is a + release fact, not a runtime switch). +- Removing v1 support. + +## 6. Required production changes + +### Core/domain + +- `encrypt_with_salt` seals with `Some(payload_aad(snippet_id))` and writes + `version: PAYLOAD_VERSION_V2`. +- Thread the snippet id into the seal call. The current internal helper takes a + JSON-producing closure with no identity input; change that private signature + to pass the id (or capture it at the `encrypt_snippet_impl` call site from + `snippet.id`). `encrypt_snippets_with` already receives `&Snippet`, so the + batch path needs no new plumbing beyond the inner call. +- `encrypt_snippet_with_salt` passes `snippet.id`. +- Keep `decrypt`'s v2 rejection: a v1-only code path must fail loudly, never + decrypt without AAD. + +### Security and authorization + +- The seal must fail if the snippet id is empty. An empty id would produce a + valid payload bound to nothing; the push validation already rejects empty + ids, but the seal should not depend on a remote check. +- No new secret, no new log line containing the id beyond existing diagnostics. + +### Documentation and static guards + +- `architecture/encryption.md`: flip the write phase, state the version + support matrix (read 0/1/2, write 2), and record the downgrade behavior. +- `SECURITY.md` § Sync Encryption: state that new payloads are id-bound; keep + the bearer-key limitation from M003 intact. +- `CHANGELOG.md`: user-visible note that devices must run a version that reads + payload v2 before others write it. + +## 7. Ordered work packages + +### Work package A — Precondition audit + +Intent: prove the fleet can read before anything writes. + +Required changes: none in code. Record the published version that contains +M005, the minimum supported client version, and where it is documented. + +Acceptance evidence: the release tag/version and the `SECURITY.md` line. + +### Work package B — Seal with AAD + +Intent: new payloads are v2. + +Required changes: id threading, AAD, version constant in the payload. + +Acceptance evidence: a sealed payload's decoded header reports version 2; it +decrypts only with its id. + +### Work package C — Downgrade behavior + +Intent: make the mixed-fleet consequence explicit and tested. + +Required changes: a test that the identity-less `decrypt` rejects a v2 payload, +mirroring an old reader; documentation of the skipped-row behavior. + +Acceptance evidence: test transcript and the documented minimum version. + +### Work package D — Release note and closure evidence + +Intent: operators learn the upgrade order before the release ships. + +Required changes: `CHANGELOG.md`, `SECURITY.md` version statement (with M003), +and the closure record's L8 disposition. + +Acceptance evidence: the note names the upgrade requirement and the payload +version. + +## 8. Failure, cancellation, restart, and contention semantics + +- A seal failure is an encryption failure for that snippet only; the batch + reports the id in `encrypt_failed_ids` and continues, exactly as today. +- No fallback to v1 on failure: a silent downgrade would hide a broken AAD + path and reintroduce the finding. +- Restart, cancellation, and contention are unchanged; encryption is a pure + function plus the existing key cache. +- A rolled-back deployment (older binary) skips v2 rows until re-upgraded; + this is the documented, accepted cost of the switch, not a data-loss bug. + +## 9. Compatibility and migration + +- Read support: versions 0, 1, 2. +- Write support: version 2 only, after this milestone. +- Old clients cannot read new payloads; the minimum-client-version statement is + the compatibility contract. +- No migration of stored data. A user who downgrades loses read access to rows + written by newer devices until they upgrade again; the rows are not lost. +- `snip-proto` unchanged; no republish of the proto crate. +- `snip-it` takes a minor version bump for the payload-format change at release + time. + +## 10. Required tests + +### Focused unit tests + +- A sealed payload reports version 2. +- It decrypts with `decrypt_for_snippet` and the same id. +- It fails with a different id. +- `decrypt` (no identity) rejects it with the explicit error. +- v1 fixtures still decrypt. +- Empty-id seal is rejected. + +### Integration tests + +- Push then pull through a real server (test helpers): the round-trip preserves + content and id, and the stored bytes are v2. +- A library with pre-existing v1 rows and newly written v2 rows syncs and + decrypts both. + +### Restart and recovery tests + +- An interrupted push leaves no partially sealed payload; the existing batch + failure accounting is unchanged. + +### Contention and cancellation tests + +- None specific beyond the existing batch tests. + +### Security and negative tests + +- Cross-id substitution of a v2 payload fails and is counted as a decrypt + failure. +- A tampered ciphertext still fails the tag check. +- The bearer-key limitation remains documented and unchanged (v2 does not + claim server-blindness). + +### Migration and compatibility tests + +- A v1-only reader path (the identity-less decrypt) rejects v2, proving the + documented downgrade behavior. + +## 11. Required verification commands + +```bash +cargo test --workspace --lib +cargo test --test sync_integration --features test-support +cargo test --test sync_multibatch --features test-support -- --test-threads=1 +bash scripts/check.sh +bash scripts/ci/test-production-seams.sh +``` + +## 12. Documentation updates + +- `architecture/encryption.md` (write phase, support matrix, downgrade). +- `SECURITY.md` § Sync Encryption (id binding; bearer limitation preserved). +- `CHANGELOG.md` (upgrade order). +- `docs/THREAT_MODEL.md` T3 residual risk: the "no identity binding" limitation + is now closed for new payloads; old payloads remain unbound until rewritten, + which they never are by design. + +## 13. Acceptance criteria + +- New payloads are version 2 and decrypt only with their snippet id. +- Version 1 payloads still decrypt; no data was rewritten. +- The minimum client version that reads v2 is documented and matches a + published release. +- The downgrade behavior is documented and tested. +- Audit finding L8 is closed for new payloads, with the old-payload caveat + stated. +- No proto, server, merge, or KDF change. + +## 14. Stop conditions + +Stop and report rather than improvise when: + +- M005 is not closed, or no published release reads v2; +- the minimum supported client version cannot be stated (then the fleet + precondition is unmet — do not ship the write switch); +- the snippet id can change between seal and store (investigate identity + stability; do not add a fallback that decrypts without AAD); +- a caller seals without an id (make it an error, do not generate one); +- a downgrade would lose data rather than defer access (reassess the rollout). + +## 15. Closure evidence required + +- The seal-path diff and a decoded v2 header. +- Unit and integration transcripts listed in § 10. +- The published v2-reading version and the `SECURITY.md` statement. +- The downgrade transcript. +- The L8 disposition: closed for new payloads; v1 rows remain unbound by + design; bearer-key limitation unchanged. + +## 16. Handoff notes + +- This plan is deliberately blocked. Do not begin it to "finish the finding"; + the release precondition is the safety property. +- The id passed to the seal must be the exact id the server stores. If the + persistence layer normalizes ids on load, prove the value is stable before + switching writes, or the first sync after upgrade will strand rows. +- Keep `decrypt` strict. A convenience "decrypt without id" that guesses is the + exact failure this milestone exists to prevent. +- `src/sync.rs`'s batch error accounting is load-bearing; do not collapse a + seal failure into a skip. +- Coordinate with M003 on `SECURITY.md`; do not describe v2 as enabled before + the release that contains it. diff --git a/plans/registry.md b/plans/registry.md index 7ff98cb8..2d9e5caa 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -43,6 +43,7 @@ Planning-convention migration: pre-convention plans 000–020 were promoted to | Locking protocol and ordering convergence | active | `plans/subsystems/locking-convergence-roadmap.md` | M001 closed; M002–M003 blocked | M002 design conflicts with the no-new-crates rule; M003 depends on M002 | | Snippet CRUD surface | active | `plans/subsystems/snippet-crud-surface-roadmap.md` | M001–M002 closed; M003 blocked | Refresh the M003 handoff against M002's field-update primitive | | Sync cursor protocol | closed | `plans/subsystems/sync-cursor-protocol-roadmap.md` | M001 condition discharged by M002; M002 closed | None | +| Security assurance | active | `plans/subsystems/security-assurance-roadmap.md` | M001–M005 closed (M002 conditionally); M006 blocked | M002 needs CI run evidence; M006 needs a published client that reads payload v2 | ## Open implementation plans @@ -51,6 +52,14 @@ Planning-convention migration: pre-convention plans 000–020 were promoted to | `plans/implementation/locking-convergence/002-kernel-lock-protocol-convergence.md` | blocked | Revise the new-crate proposal to comply with the no-new-crates rule | | `plans/implementation/locking-convergence/003-lock-ordering-contract-and-static-guard.md` | blocked | Hard dependency on M002; reconcile the draft's soft-dependency claim | | `plans/implementation/snippet-crud-surface/003-non-interactive-field-update.md` | blocked | Refresh stale implementation evidence against M002's closed field-update primitive | +| `plans/implementation/security-assurance/002-ci-advisory-gates-and-action-pinning.md` | conditionally closed | CI run evidence (green job, red unsuppressed branch) must be recorded from GitHub Actions | +| `plans/implementation/security-assurance/006-enable-v2-payload-writes.md` | blocked | One published client release that reads payload v2, plus the minimum-client-version statement | + +The security-assurance plan set responds to the 2026-11-17 security audit; the +audit's evidence and residual-risk dispositions remain in +`plans/subsystems/security-assurance-roadmap.md` § 4 and the closure records. +M001, M003, M004, and M005 are closed and therefore no longer listed above; +their evidence is in `plans/closure/security-assurance/`. Register new work here only after dependency and handoff review per `plans/003-planning-process.md` §10. diff --git a/plans/subsystems/security-assurance-roadmap.md b/plans/subsystems/security-assurance-roadmap.md new file mode 100644 index 00000000..47beeab2 --- /dev/null +++ b/plans/subsystems/security-assurance-roadmap.md @@ -0,0 +1,455 @@ +# Security Assurance Roadmap + +Status: active + +Long-term references: + +- `plans/000-long-term-specification.md#6-sync-invariants` +- `plans/000-long-term-specification.md#9-distribution-and-release-invariants` +- `plans/000-long-term-specification.md#10-verification-and-evidence-rules` +- `plans/001-terminology-and-domain-model.md#5-sync-and-execution-terms` +- `plans/001-terminology-and-domain-model.md#8-distribution-and-update-terms` +- `plans/002-long-term-roadmap.md#cross-phase-execution-rules` +- `plans/003-planning-process.md` + +Related ADRs: + +- `plans/adrs/ADR-0002-encryption-payload-identity-binding.md` (proposed) +- `plans/adrs/ADR-0003-advisory-remediation-and-suppression-policy.md` (proposed) + +## 1. Purpose and ownership boundary + +This subsystem owns the **verifiable security posture** of the products as +shipped: + +- dependency advisories, license policy, and the gate that proves both; +- the accuracy of the published security claims (what the encryption and + transport actually guarantee); +- local-file privacy for server-owned data; +- abuse bounds on unauthenticated and credential-bearing server surfaces; +- authenticated binding of encrypted payloads to snippet identity. + +It consumes the sync invariants, the published-crate rules, the release +workflow, and the existing `snip-sync` lifecycle/HTTP contracts as fixed +inputs. It MUST NOT own: + +- sync merge semantics or the cursor protocol + (`plans/subsystems/sync-cursor-protocol-roadmap.md`); +- server runtime selection or wire parity + (`plans/subsystems/server-lifecycle-http-roadmap.md`); +- release artifact construction, installer trust, or publication + (`plans/subsystems/distribution-release-roadmap.md`) — except the one CI job + this roadmap explicitly authorizes below; +- MCP behavior or snippet CRUD capability. + +The audit that created this workstream (2026-11-17) is the evidence baseline. +Findings it classified as accepted or by design are not reopened here; § 3 +lists them so their absence from the milestones is a decision, not an +oversight. + +## 2. Work classification + +### Invariants + +- No new-advisory regression is possible to merge silently: the advisory and + license gate runs in CI and fails on unexpected findings. +- Every suppressed advisory is scoped by ID, justified, dated, and removable + by a named upstream condition. +- Published claims about confidentiality and integrity match what the code + and protocol actually provide. +- Server-owned private data is readable only by the service account on Unix. +- Unauthenticated and credential-guessing surfaces are bounded + independently of the caller's key or address. +- A sealed payload only authenticates for the snippet identity it was sealed + for. + +### Capabilities + +- Operators can read a current, truthful security posture without reading + source code. +- Operators of a password-protected `/metrics` endpoint get a bounded + authentication surface. +- Operators of a public registration endpoint get a bounded account-creation + rate. + +### Infrastructure + +- CI advisory job, pinning of third-party actions, suppression check script, + payload version dispatch, private-path helper. + +### Polish + +- Documentation corrections, table/link refresh, wording that distinguishes + transport confidentiality from server-blindness. + +## 3. Non-goals + +- No vendored or system SQLite; no `[patch.crates-io]` or git dependency for a + published crate (see ADR-0003). +- No global advisory-lint relaxation (`unmaintained = "workspace"` is + prohibited). +- No release signing, attestation, or key-management workstream. Checksum-only + update integrity remains documented residual risk. +- No server-side TLS termination. `TLS_ENABLED` stays an assertion about a + reverse proxy; only its documentation is in scope. +- No removal of the `/health` version field: it is intentional fleet + diagnostics and a wire-contract change is not justified by the disclosure. +- No change to `snip-proto`, the client merge order, `updated_at` semantics, + Argon2id parameters, or snippet-id determinism. +- No keychain account scoping per server URL (informational finding; would + change credential migration). +- No shell-quoting change for snippet variables (by design; the user supplies + the command and its values). +- No new security tooling beyond `cargo audit` and `cargo deny`. +- No reopening of the closed roadmaps' milestone content. Their contracts are + inputs. + +## 4. Current state + +The 2026-11-17 audit established, with commands and file evidence: + +- `cargo audit`: one vulnerability (`RUSTSEC-2026-0459`, `libsqlite3-sys + 0.37.0`, CVSS 6.8, patched `>=0.39.0`) and three unmaintained warnings + (`RUSTSEC-2026-0370/0371/0372`, no fix published). +- `cargo deny check`: `advisories FAILED`, `licenses FAILED` (only + `webpki-roots` `CDLA-Permissive-2.0`), `bans ok`, `sources ok`. +- The vulnerable bundled SQLite is in the **server** binary only + (`snip-sync/Cargo.toml:41`); the `snp` client's `sqlx` edge is a + dev-dependency. +- No CI workflow runs either tool; `deny.toml` carries `ignore = []`. +- `SECURITY.md` § Sync Encryption states "a compromised server cannot read + snippet content" while the same document states the API key is sent as a + bearer token on every request; `docs/THREAT_MODEL.md` T3 concludes "It + cannot forge content" after acknowledging the key exposure. + `architecture/encryption.md` is accurate and already says "not + server-blindness". +- `snip-sync` metrics basic auth uses a constant-time compare but no rate + limiter (`snip-sync/src/http.rs:146-199`); gRPC has a bounded limiter. +- Unauthenticated `Register` creates a user plus a default library per call, + bounded only by the per-peer budget (`snip-sync/src/lib.rs:1050-1122`). +- The server database directory and file are created under the process umask; + only the config file is chmodded (`snip-sync/src/bootstrap.rs:54-60` versus + `snip-sync/src/db.rs:329-344`). +- `WEBPKI` license and the three unmaintained crates are the only license and + advisory findings; `bans` and `sources` are clean. +- Encryption payloads carry no AAD (`src/encryption.rs:316-342`), and the + payload version byte rejects anything but `1`. + +## 5. Target architecture + +- **One deterministic gate.** A small, documented contract: `cargo audit` for + vulnerabilities, `cargo deny check` for the full policy, both green locally + and in CI. The suppression list is the only place a known finding is + allowed to exist, and it is mirrored in `SECURITY.md`. +- **Truthful documentation.** One authoritative statement of what is + confidential (content at rest/in transit), what the server learns (routing + metadata and, when it observes the bearer token, the ability to decrypt), + and what the GCM tag does and does not authenticate. +- **Bounded server surfaces.** Every unauthenticated or credential-checking + path has an explicit budget independent of the attacker's key choice; the + private database directory is owner-only on Unix. +- **Versioned payload integrity.** Observe-Both-Reads: version 2 payloads + bind to the snippet id via AAD, version 1 remains readable, and the write + switch is a separately gated milestone with a fleet-readiness precondition. + +## 6. Dependency graph + +```text +M001 Advisory posture and license policy + | + +-- hard --> M002 CI advisory gates and action pinning + +M003 Security claim reconciliation (independent) + +M004 Server abuse resistance and file hygiene (independent) + +M005 Encryption payload v2 read support + | + +-- hard --> M006 Enable v2 payload writes + | + `-- operational --> published release that reads v2 +``` + +Classification: + +- M001 → M002: **hard**. The gate must be green before it can be blocking. +- M005 → M006: **hard**. Writes need the read path. +- M006 → published release: **operational**. The fleet precondition is a + release fact, not a code dependency. +- M003 and M004: **soft** with respect to M001 (shared documentation edits); + they may land in any order. + +## 7. Milestones + +### Milestone 001 — Advisory posture and license policy + +Class: infrastructure + +Objective: make the advisory and license gate deterministic and green using +scoped, documented, review-dated exceptions, without changing dependency +sources. + +Dependencies: ADR-0003 accepted. + +Deliverable boundary: `deny.toml`, `SECURITY.md` § Advisory Exceptions, and a +local check script. No CI wiring (M002). No dependency upgrade beyond what the +working tree already carries. + +User or operator value: the shipped server's known vulnerability is a named, +justified, removable exception instead of an untracked finding; the published +license policy matches the graph. + +Exit conditions: `cargo audit` and `cargo deny check` exit 0; every exception +has ID/scope/why/added/review-by/remove-when; every exception appears in both +files; a negative check proves an unsuppressed advisory still fails; no +dependency-source change. + +Deferred work: removing the suppressions (owned by upstream releases). + +### Milestone 002 — CI advisory gates and action pinning + +Class: infrastructure + +Objective: run the gate in CI as a blocking job and pin third-party actions by +commit SHA. + +Dependencies: M001 (hard). **Roadmap authorization:** this milestone +explicitly authorizes the additional CI hardening that `plans/README.md` +permits only under a roadmap revision. + +Deliverable boundary: `.github/workflows/ci.yml` (new job), +`.github/workflows/*.yml` (SHA pins), `.github/dependabot.yml` (verify +`github-actions` updates still apply). No new service, no new secret, no +release-flow change. + +User or operator value: a regression in the dependency graph fails a pull +request instead of surviving to a release. + +Exit conditions: the advisory job runs on every push/PR; it fails on an +unexpected finding and passes on the committed policy; every third-party +action is SHA-pinned with a version comment; workflow permissions stay +`contents: read`. + +Deferred work: nightly advisory refresh (not required; the weekly run already +covers it). + +### Milestone 003 — Security claim reconciliation + +Class: polish + +Objective: make every published confidentiality/integrity claim match the +implementation and the threat model. + +Dependencies: none (soft: shared edits with M001's `SECURITY.md` section). + +Deliverable boundary: `SECURITY.md`, `docs/THREAT_MODEL.md`, and any +`README.md`/`architecture/encryption.md` cross-reference needed for +consistency. No code. + +User or operator value: a deployer can decide whether to trust a third-party +server from the documentation alone; a user learns why "the server cannot +read my snippets" is false once the same server receives the key. + +Exit conditions: no document claims a compromised server cannot read or forge +content; the bearer-token consequence is stated wherever confidentiality is +claimed; TLS assertion semantics, `/health` disclosure, and checksum-only +updates are stated; supported versions and the audit reference are current. + +Deferred work: none. + +### Milestone 004 — Server abuse resistance and local file hygiene + +Class: invariant + +Objective: bound the metrics authentication surface and account creation, and +make server-owned data owner-only on Unix. + +Dependencies: none. + +Deliverable boundary: `snip-sync/src/http.rs`, `snip-sync/src/lib.rs`, +`snip-sync/src/db.rs`, `snip-sync/config.toml`, and the `snip-sync` version +bump required by the public `AppState`/service interface change. No proto +change. + +User or operator value: brute-forcing `/metrics` is rate-limited; a +many-address registration flood is capped; other local users cannot read the +database, its WAL, or its shared-memory file. + +Exit conditions: metrics authentication is budgeted by a documented limit; +registration has a global budget distinct from the per-peer budget; the data +directory is `0o700` and database files `0o600` on Unix, with a warning when +an existing broader mode is found; tests cover each; the new configuration is +validated and defaulted without breaking existing configs. + +Deferred work: per-IP metrics budgets (the HTTP leaf exposes no peer address +in its current handler shape). + +### Milestone 005 — Encryption payload v2 read support + +Class: infrastructure + +Objective: accept and correctly decrypt version-2 payloads whose AAD binds +the ciphertext to the snippet id, while continuing to write version 1. + +Dependencies: ADR-0002 accepted. + +Deliverable boundary: `src/encryption.rs` and the decrypt call site in +`src/sync.rs`, plus tests. No write-path change, no proto change, no server +change. + +User or operator value: none directly — this is the prerequisite that lets a +later release stop a key-blind store from substituting ciphertexts between +snippet ids. It MUST NOT be described as a closed capability. + +Exit conditions: v2 decrypts with the correct id and fails with a different +id; v1 keeps decrypting; unknown versions are still rejected; `decrypt` +without an id fails loudly on v2; a mixed v1/v2 pull integration test passes; +id stability across save/load is proven. + +Deferred work: writing v2 (M006). + +### Milestone 006 — Enable v2 payload writes + +Class: invariant + +Objective: switch the write path to version 2 so new payloads are bound to +their snippet identity. + +Dependencies: M005 (hard); one published `snp` release that reads v2 and a +stated minimum supported client version (operational). + +Deliverable boundary: `src/encryption.rs` write path, the encrypt call site, +`CHANGELOG.md`, and the compatibility statement. No proto or server change. + +User or operator value: a party that can move stored ciphertexts but cannot +use the API key can no longer make one snippet's content appear under another +snippet's description. + +Exit conditions: new payloads are v2; v1 still decrypts; the minimum-client +version is published; a downgrade test documents the skipped-snippet behavior; +the audit finding L8 is explicitly closed in the closure record. + +Deferred work: binding `library_id`/`device_id` (new ADR required). + +## 8. Cross-cutting requirements + +### Storage and migration + +- No schema change anywhere. The server treats payload version 2 as opaque + bytes in the existing `command` column. +- The only storage-adjacent change is Unix file modes for the server database + directory and files (M004). No data rewrite. + +### Protocol and compatibility + +- `snip-proto` stays at its current version across all six milestones. +- The encryption payload version is a client-internal format, not a proto + field; v1 remains readable indefinitely. +- `snip-sync`'s public `AppState`/service signature changes in M004, so the + crate takes a semver-appropriate bump; `snip-it` is unaffected by that bump + unless a publish ordering change is required. + +### Security and authorization + +- Suppressions never change authorization behavior. +- The metrics budget must not create an oracle: a limited request and a wrong + password should not be distinguishable beyond the documented status codes. +- Registration caps must not let an attacker exhaust a legitimate caller's + budget by shared-key design; the global budget is deliberately separate from + the per-peer budget. +- AAD is public data; no secret is introduced or logged. + +### Concurrency, cancellation, and recovery + +- The rate limiter is the existing async, bounded, process-local structure; + no new lock ordering. +- A capped registration returns a typed resource-exhausted status and leaves no + partial user row. +- File-mode changes happen at startup before serving; a failure to restrict an + existing path is a warning, not a crash. + +### Observability and audit + +- Rate-limit rejections increment the existing rate-limit counter and the + appropriate auth-failure counter; no new cardinality source. +- The advisory gate's failure output must name the advisory ID so a reviewer + can act without rerunning locally. + +### Performance and resource use + +- The advisory job should not materially lengthen CI; its own job keeps it off + the 35-minute correctness path. +- The metrics budget is one hash-map entry per process, not per request key. +- AAD adds no KDF work; the batch salt and key cache remain effective. + +### Documentation and operations + +- `SECURITY.md` is the operator contract; `docs/THREAT_MODEL.md` is the + analysis; `architecture/encryption.md` is the implementation deep dive. A + fact is stated once and linked. +- Every new configuration key is documented in `snip-sync/config.toml` with its + default and its environment override. + +## 9. Verification strategy + +- Narrow first: unit tests in the touched modules, then the focused + integration targets (`sync_integration`, `snip_sync_lifetime`). +- Authoritative gate: `bash scripts/check.sh` and + `bash scripts/ci/test-production-seams.sh`. +- Advisory evidence: `cargo audit` and `cargo deny check`, plus the negative + check that an unsuppressed finding still fails. +- CI evidence: the new job's first green run on `main` and a red run on a + deliberately unsuppressed branch (recorded in the closure record, not + committed). +- Unix file modes: `#[cfg(unix)]` tests asserting `0o700`/`0o600`; Windows + ACL behavior is out of scope and must be stated as such. +- Fleet compatibility: v1 and v2 payloads in one pulled library; a v1-only + reader's behavior recorded before M006 is enabled. + +## 10. Risks and decision points + +- **ADR-0003 acceptance** decides whether the gate goes green via scoped + exceptions (recommended) or waits for an upstream release. Until accepted, + M001/M002 stay proposed. +- **ADR-0002 acceptance** and the two-phase rollout. A single-phase switch + would break older devices' decryption; the roadmap rejects that shape. +- **Upstream timing.** If `sqlx` releases a compatible bound during M001, the + SQLite exception is dropped and the milestone shrinks; do not implement the + suppression first and the upgrade later. +- **CI runtime.** If the advisory job exceeds the repository's tolerance, + move it to a scheduled + PR-path-filtered job rather than dropping it. +- **Suppression creep.** Every added ID must carry a fresh analysis; a + copy-pasted justification is a review failure. +- **Doc drift.** M003's guard is narrow on purpose; it prevents the two + specific false sentences from returning, not all future wording changes. +- **Scope pressure.** Release signing, server TLS termination, and + keychain-slot scoping are deliberately outside this roadmap; they need their + own decision records. + +## 11. Completion definition + +The roadmap closes when all six milestones have accepted closure records and: + +- `cargo audit` and `cargo deny check` pass both locally and in CI, and a new + advisory fails the gate; +- every active suppression is scoped, justified, dated, mirrored in + `SECURITY.md`, and has a removal condition; +- no published document claims a compromised server is blind to content or + unable to forge it; +- `/metrics` authentication and registration are bounded, with tests; +- server-owned Unix data is owner-only, with tests; +- v2 payloads are bound to snippet identity, v1 is still readable, and the + minimum-client-version statement is published; +- the audit's remaining findings are either closed or recorded as accepted + residual risk in the closure record. + +## 12. Milestone status + +| Milestone | Status | Implementation plan | Closure record | Blockers | +|---|---|---|---|---| +| 1 — Advisory posture and license policy | closed | `plans/implementation/security-assurance/001-advisory-posture-and-license-policy.md` | `plans/closure/security-assurance/001-status.md` | None | +| 2 — CI advisory gates and action pinning | conditionally closed | `plans/implementation/security-assurance/002-ci-advisory-gates-and-action-pinning.md` | `plans/closure/security-assurance/002-status.md` | CI run evidence from GitHub Actions | +| 3 — Security claim reconciliation | closed | `plans/implementation/security-assurance/003-security-claim-reconciliation.md` | `plans/closure/security-assurance/003-status.md` | None | +| 4 — Server abuse resistance and file hygiene | closed | `plans/implementation/security-assurance/004-server-abuse-resistance-and-local-file-hygiene.md` | `plans/closure/security-assurance/004-status.md` | None | +| 5 — Encryption payload v2 read support | closed | `plans/implementation/security-assurance/005-encryption-payload-v2-read-support.md` | `plans/closure/security-assurance/005-status.md` | None | +| 6 — Enable v2 payload writes | blocked | `plans/implementation/security-assurance/006-enable-v2-payload-writes.md` | — | M005 closed; one published `snp` release that reads payload v2 | diff --git a/scripts/check-advisories.sh b/scripts/check-advisories.sh new file mode 100755 index 00000000..100a2f8d --- /dev/null +++ b/scripts/check-advisories.sh @@ -0,0 +1,214 @@ +#!/usr/bin/env bash +# scripts/check-advisories.sh — deterministic dependency advisory and license gate. +# +# Proves three things, in order: +# 1. `cargo audit` and `cargo deny check` are both green on this tree. +# 2. The suppression list has exactly one meaning in three places: the +# normative `deny.toml`, the `cargo audit` mirror `.cargo/audit.toml`, +# and the human mirror in `SECURITY.md` § Advisory Exceptions. +# 3. The gate still fails on an unsuppressed advisory (`--self-test`). +# +# Policy: plans/adrs/ADR-0003-advisory-remediation-and-suppression-policy.md. +# +# This is intentionally *not* part of `scripts/check.sh`: that run must stay +# free of network access and of tool-installation requirements. CI calls this +# script from its own job (`.github/workflows/ci.yml`, `advisory-gate`). +# +# Usage: +# scripts/check-advisories.sh # full gate +# scripts/check-advisories.sh --self-test # also prove an unsuppressed ID fails +# scripts/check-advisories.sh --help +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +cd "$REPO_ROOT" + +DENY_CONFIG="deny.toml" +AUDIT_CONFIG=".cargo/audit.toml" +SECURITY_DOC="SECURITY.md" +SELF_TEST=0 + +usage() { + sed -n '2,20p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' +} + +for arg in "$@"; do + case "$arg" in + --self-test) SELF_TEST=1 ;; + -h|--help) usage; exit 0 ;; + *) + echo "FAIL: unknown argument: $arg" >&2 + echo "Try: scripts/check-advisories.sh --help" >&2 + exit 2 + ;; + esac +done + +fail() { + echo "FAIL: $*" >&2 + exit 1 +} + +# --- 1. Tool availability --------------------------------------------------- +# A missing tool is an environment failure, never a silent pass. +if ! command -v cargo-audit >/dev/null 2>&1; then + echo "FAIL: cargo-audit is not installed." >&2 + echo " Install: cargo install cargo-audit --locked --version 0.23.0" >&2 + exit 1 +fi + +if ! command -v cargo-deny >/dev/null 2>&1; then + echo "FAIL: cargo-deny is not installed." >&2 + echo " Install: cargo install cargo-deny --locked" >&2 + exit 1 +fi + +for config in "$DENY_CONFIG" "$AUDIT_CONFIG" "$SECURITY_DOC"; do + [ -f "$config" ] || fail "required file is missing: $config" +done + +# --- 2. Advisory and license tools ----------------------------------------- +echo "=== cargo audit ===" +if ! cargo audit; then + fail "cargo audit reported an unsuppressed finding (see output above)" +fi + +echo "=== cargo deny check ===" +if ! cargo deny check; then + fail "cargo deny check failed (see output above)" +fi + +# --- 3. Mirror consistency -------------------------------------------------- +# Extract the quoted advisory IDs from a TOML file, ignoring comment lines so +# that a rationale block naming an ID is not mistaken for a live suppression. +toml_ignore_ids() { + local file="$1" + sed 's/#.*$//' "$file" \ + | grep -oE '"RUSTSEC-[0-9]{4}-[0-9]{4}"' \ + | tr -d '"' \ + | sort -u +} + +# The SECURITY.md marker is the machine-readable half of the human mirror. +marker_ids() { + local file="$1" + sed -n 's/.*.*/\1/p' "$file" \ + | tr ' ' '\n' \ + | grep -E '^RUSTSEC-[0-9]{4}-[0-9]{4}$' \ + | sort -u +} + +DENY_IDS="$(toml_ignore_ids "$DENY_CONFIG")" +AUDIT_IDS="$(toml_ignore_ids "$AUDIT_CONFIG")" +DOC_IDS="$(marker_ids "$SECURITY_DOC")" + +echo "=== Suppression mirror ===" +echo "deny.toml: ${DENY_IDS:-}" +echo ".cargo/audit.toml: ${AUDIT_IDS:-}" +echo "SECURITY.md: ${DOC_IDS:-}" + +if [ "$DENY_IDS" != "$AUDIT_IDS" ]; then + fail "$DENY_CONFIG and $AUDIT_CONFIG suppress different advisory sets" +fi + +if [ "$DENY_IDS" != "$DOC_IDS" ]; then + fail "$DENY_CONFIG and $SECURITY_DOC suppress different advisory sets (check the advisory-ignore-ids marker)" +fi + +if [ -z "$DENY_IDS" ]; then + echo "No active advisory suppressions." +else + # Every entry must carry the six-field block from ADR-0003. Counting the + # rationale blocks is enough to catch a copy-pasted or truncated entry. + for id in $DENY_IDS; do + count="$(grep -c "ID:[[:space:]]*$id" "$DENY_CONFIG" || true)" + if [ "$count" -lt 1 ]; then + fail "$id has no 'ID: $id' rationale block in $DENY_CONFIG" + fi + # The rationale block is the run of comment lines immediately above the + # entry, so a field cannot be borrowed from a neighbouring block. + if ! awk -v id="$id" ' + function check_block( f, missing) { + missing = "" + for (f = 1; f <= nfields; f++) { + if (block !~ fields[f]) { missing = missing " " fields[f] } + } + if (missing != "") { + printf "missing:%s\n", missing > "/dev/stderr" + bad = 1 + } + } + BEGIN { + nfields = split("Scope:|Why:|Added:|Review by:|Remove when:", fields, "|") + bad = 0 + nblock = 0 + } + /^[[:space:]]*#/ { + block = (nblock == 0) ? $0 : block "\n" $0 + nblock++ + next + } + { + if ($0 ~ "\"" id "\",") { check_block() } + block = "" + nblock = 0 + } + END { exit(bad ? 1 : 0) } + ' "$DENY_CONFIG"; then + fail "$id has an incomplete rationale block in $DENY_CONFIG" + fi + done + + # A suppression entry must be a bare advisory ID: no crate names, versions, + # or wildcards are permitted by ADR-0003. + IGNORE_BODY="$(awk ' + /^ignore[[:space:]]*=[[:space:]]*\[/ { in_array = 1 } + in_array { print } + in_array && /\]/ { in_array = 0 } + ' "$DENY_CONFIG" | sed 's/#.*$//')" + + BAD_ENTRY="$(printf '%s\n' "$IGNORE_BODY" \ + | grep -oE '"[^"]*"' \ + | grep -vE '^"RUSTSEC-[0-9]{4}-[0-9]{4}"$' || true)" + if [ -n "$BAD_ENTRY" ]; then + fail "$DENY_CONFIG suppresses a non-ID entry: $BAD_ENTRY" + fi +fi + +# --- 4. Negative proof ------------------------------------------------------ +if [ "$SELF_TEST" -eq 1 ]; then + echo "=== Self-test: an unsuppressed advisory must fail ===" + FIRST_ID="$(printf '%s\n' "$DENY_IDS" | head -n 1)" + if [ -z "$FIRST_ID" ]; then + fail "--self-test needs at least one suppression to remove" + fi + + TMP_DIR="$(mktemp -d)" + trap 'rm -rf "$TMP_DIR"' EXIT + + awk -v id="$FIRST_ID" ' + $0 == " \"" id "\"," { next } + { print } + ' "$DENY_CONFIG" > "$TMP_DIR/deny.toml" + + if grep -q "\"$FIRST_ID\"," "$TMP_DIR/deny.toml"; then + fail "could not construct the unsuppressed test config for $FIRST_ID" + fi + + echo "Removed $FIRST_ID from a temporary copy; expecting a non-zero exit." + # `--config` is a global flag in cargo-deny: it must precede the subcommand. + if SELF_TEST_OUTPUT="$(cargo deny --config "$TMP_DIR/deny.toml" check advisories 2>&1)"; then + fail "self-test failed: the gate passed with $FIRST_ID unsuppressed" + fi + # Fail for the right reason: the output must name the advisory we removed. + # Without this, a bad invocation (wrong flag position, broken config path) + # would look like a successful negative proof. + if ! printf '%s\n' "$SELF_TEST_OUTPUT" | grep -q "$FIRST_ID"; then + printf '%s\n' "$SELF_TEST_OUTPUT" >&2 + fail "self-test failed for the wrong reason: output does not name $FIRST_ID" + fi + echo "Self-test passed: the gate still catches an unsuppressed advisory." +fi + +echo "=== Advisory and license gate: PASS ===" diff --git a/snip-sync/Cargo.toml b/snip-sync/Cargo.toml index 6dfef164..c2cbc490 100644 --- a/snip-sync/Cargo.toml +++ b/snip-sync/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "snip-sync" -version = "0.1.8" +version = "0.2.0" edition = "2024" rust-version = "1.94" description = "gRPC sync server for snp snippet manager" @@ -38,9 +38,9 @@ test-helpers = [] tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal"] } eggserve-server = { version = "=0.5.0", default-features = false } eggserve-primitives = { version = "=0.2.3", default-features = false } -sqlx = { version = "0.9", features = ["sqlite", "runtime-tokio", "chrono"] } +sqlx = { version = "0.9", features = ["sqlite", "runtime-tokio"] } uuid = { version = "1", features = ["v4"] } -chrono = { version = "0.4", features = ["serde"] } +time = ">=0.3.36, <0.4" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } serde = { version = "1", features = ["derive"] } diff --git a/snip-sync/config.toml b/snip-sync/config.toml index 712e62bc..cac1ae88 100644 --- a/snip-sync/config.toml +++ b/snip-sync/config.toml @@ -51,10 +51,21 @@ grpc_max_message_size = 4194304 [server.rate_limit] # Number of requests allowed per minute per API key requests_per_minute = 120 +# Global ceiling on account creation per minute, across all caller addresses. +# Registration is unauthenticated; this bounds total table growth when a caller +# rotates addresses. Raise it for a deployment that legitimately registers more +# than ten devices per minute. Zero is rejected as a configuration error. +# Environment override: REGISTER_PER_MINUTE +register_per_minute = 10 +# Global ceiling on FAILED /metrics authentications per minute. Correct +# credentials never consume it, so an operator's own scrape is never throttled. +# Once exhausted, further failed attempts get 429 with Retry-After: 60. +# Environment override: METRICS_AUTH_FAILURES_PER_MINUTE +metrics_auth_failures_per_minute = 10 # Accept forwarded client IPs only when the immediate peer is listed here. # trusted_proxies = ["127.0.0.1"] -# Persist rate-limit counters across restarts. -# persist = false +# Rate-limit counters are process-local and reset on restart; no state is +# persisted. [server.metrics] # Basic auth credentials for metrics endpoint diff --git a/snip-sync/src/db.rs b/snip-sync/src/db.rs index 39aa4935..7724682a 100644 --- a/snip-sync/src/db.rs +++ b/snip-sync/src/db.rs @@ -3,14 +3,14 @@ use argon2::{ password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash}, }; use base64::Engine; -use chrono::Utc; use sha2::{Digest, Sha256}; use sqlx::AssertSqlSafe; use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions}; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; use thiserror::Error; +use time::OffsetDateTime; use uuid::Uuid; const ARGON2_MEMORY_KIB: u32 = 1 << 14; // 16 MiB — OWASP minimum for Argon2id @@ -313,6 +313,104 @@ async fn bump_library_sequence( Ok(sequence) } +/// Create (or tighten) the directory that holds the SQLite database so that it +/// is reachable only by the service account on Unix. +/// +/// A newly created directory is created *with* `0o700` as part of the creation +/// call, so there is no window in which it exists with a broader mode. A +/// pre-existing directory may predate this policy: it is tightened when +/// possible, and a failure is a warning naming the observed mode rather than a +/// startup abort, because a read-only or administrator-managed deployment can +/// legitimately refuse the change. +#[cfg(unix)] +fn prepare_data_directory(path: &Path) -> std::io::Result<()> { + use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; + + let existed = path.exists(); + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(path)?; + + if existed { + let mode = std::fs::metadata(path)?.permissions().mode() & 0o777; + if mode & 0o077 != 0 { + match std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)) { + Ok(()) => tracing::info!( + "Tightened server data directory {} from mode {:#05o} to 0o700", + path.display(), + mode + ), + Err(error) => tracing::warn!( + "Server data directory {} is accessible to other local users \ + (mode {:#05o}) and could not be tightened to 0o700: {}", + path.display(), + mode, + error + ), + } + } + } + Ok(()) +} + +#[cfg(not(unix))] +fn prepare_data_directory(path: &Path) -> std::io::Result<()> { + // Windows ACL enforcement is out of scope; the directory is still created. + std::fs::create_dir_all(path) +} + +/// Restrict the database file and its WAL/shared-memory siblings to `0o600`. +/// +/// The siblings are created by SQLite on first write, so this runs after the +/// schema has been touched. Contents are ciphertext, but metadata and Argon2id +/// hashes are readable by any local user who can open the file. +#[cfg(unix)] +fn restrict_database_files(filename: &Path) { + use std::os::unix::fs::PermissionsExt; + + let mut targets = vec![filename.to_path_buf()]; + for suffix in ["-wal", "-shm"] { + let mut sibling = filename.as_os_str().to_owned(); + sibling.push(suffix); + targets.push(PathBuf::from(sibling)); + } + + for target in targets { + let mode = match std::fs::metadata(&target) { + Ok(metadata) => metadata.permissions().mode() & 0o777, + // A missing `-wal`/`-shm` is normal: SQLite may not have created it + // yet, or may have removed it on a clean checkpoint. + Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, + Err(error) => { + tracing::debug!( + "Unable to inspect database file {}: {}", + target.display(), + error + ); + continue; + } + }; + if mode & 0o077 == 0 { + continue; + } + if let Err(error) = + std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o600)) + { + tracing::warn!( + "Database file {} is accessible to other local users (mode {:#05o}) \ + and could not be tightened to 0o600: {}", + target.display(), + mode, + error + ); + } + } +} + +#[cfg(not(unix))] +fn restrict_database_files(_filename: &Path) {} + impl Database { pub async fn connect(url: &str, max_connections: u32) -> DbResult { // The public configuration uses a SQLite file path for convenience, @@ -328,12 +426,12 @@ impl Database { .create_if_missing(true) .busy_timeout(Duration::from_secs(5)); - let filename = options.get_filename(); + let filename = options.get_filename().to_path_buf(); if filename != Path::new(":memory:") && let Some(parent) = filename.parent() && !parent.as_os_str().is_empty() { - std::fs::create_dir_all(parent).map_err(|e| { + prepare_data_directory(parent).map_err(|e| { DbError::Internal(format!( "Failed to create database directory {}: {}", parent.display(), @@ -472,6 +570,9 @@ impl Database { let db = Self { pool }; db.migrate_snippet_sequence().await?; + // Runs after the schema writes so SQLite has created `-wal`/`-shm`. + restrict_database_files(&filename); + Ok(db) } @@ -486,7 +587,7 @@ impl Database { pub async fn create_user(&self, api_key: &str) -> DbResult { let user_id = Uuid::new_v4().to_string(); - let now = Utc::now().timestamp(); + let now = OffsetDateTime::now_utc().unix_timestamp(); let api_key_hash = hash_api_key(api_key)?; let api_key_prefix = compute_api_key_prefix(api_key); @@ -560,7 +661,7 @@ impl Database { } let lib_id = Uuid::new_v4().to_string(); - let now = Utc::now().timestamp(); + let now = OffsetDateTime::now_utc().unix_timestamp(); let result = sqlx::query( "INSERT OR IGNORE INTO libraries (id, user_id, name, created_at) VALUES (?, ?, ?, ?)", @@ -623,7 +724,7 @@ impl Database { } pub async fn delete_library(&self, user_id: &str, library_id: &str) -> DbResult<()> { - let now = Utc::now().timestamp(); + let now = OffsetDateTime::now_utc().unix_timestamp(); let mut tx = self.pool.begin().await?; let result = sqlx::query( @@ -1136,6 +1237,76 @@ mod tests { assert!(path.exists()); } + /// The server's data directory holds ciphertext, but also metadata and + /// Argon2id hashes. On Unix no other local user may traverse or read it. + #[cfg(unix)] + #[tokio::test] + async fn data_directory_is_created_owner_only() { + use std::os::unix::fs::PermissionsExt; + + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("server-data"); + let path = dir.join("snippets.db"); + + let _db = Database::connect(path.to_str().unwrap(), 1).await.unwrap(); + + let mode = std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777; + assert_eq!( + mode, 0o700, + "the data directory must be created owner-only, got {mode:#05o}" + ); + } + + /// A database file that already exists with a broader mode is tightened in + /// place; the contents are never rewritten by the permission change. + #[cfg(unix)] + #[tokio::test] + async fn database_file_is_restricted_to_owner_only() { + use std::os::unix::fs::PermissionsExt; + + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("server-data"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("snippets.db"); + // Simulate a pre-existing world-readable database. + std::fs::write(&path, b"").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + + let _db = Database::connect(path.to_str().unwrap(), 1).await.unwrap(); + + let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!( + mode & 0o077, + 0, + "the database file must not be group/world accessible, got {mode:#05o}" + ); + } + + /// A pre-existing broader directory is tightened rather than abandoned. + #[cfg(unix)] + #[tokio::test] + async fn preexisting_broad_directory_is_tightened() { + use std::os::unix::fs::PermissionsExt; + + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("server-data"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap(); + let path = dir.join("snippets.db"); + + let _db = Database::connect(path.to_str().unwrap(), 1).await.unwrap(); + + let mode = std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o700, "an existing broad mode must be tightened"); + } + + /// The in-memory database has no filesystem path and must not trip the + /// permission helpers. + #[tokio::test] + async fn memory_database_skips_file_permission_handling() { + let _db = setup_db().await; + } + #[tokio::test] async fn test_create_and_verify_user() { let db = setup_db().await; @@ -1502,7 +1673,7 @@ mod tests { let db = setup_db().await; let user_id = db.create_user("key").await.unwrap(); let library_id = db.create_library(&user_id, "future-delete").await.unwrap(); - let future_timestamp = Utc::now().timestamp() + 100; + let future_timestamp = OffsetDateTime::now_utc().unix_timestamp() + 100; let snippet = Snippet { id: "future-snippet".to_string(), @@ -1691,7 +1862,7 @@ mod tests { async fn test_migrate_plaintext_api_keys() { let db = setup_db().await; let user_id = Uuid::new_v4().to_string(); - let now = Utc::now().timestamp(); + let now = OffsetDateTime::now_utc().unix_timestamp(); // Insert a plaintext API key directly (simulating old schema) sqlx::query("INSERT INTO users (id, api_key, created_at, updated_at) VALUES (?, ?, ?, ?)") diff --git a/snip-sync/src/http.rs b/snip-sync/src/http.rs index 881bb4ed..e6c8bfbc 100644 --- a/snip-sync/src/http.rs +++ b/snip-sync/src/http.rs @@ -21,6 +21,15 @@ use crate::AppState; use eggserve_primitives::{HeaderBlock, RequestHead, Response, ResponseBody, StatusCode}; +use std::time::Duration; + +/// Window for the `/metrics` authentication failure budget. One minute matches +/// the gRPC limiter's window so operators have one mental model. +const METRICS_AUTH_WINDOW: Duration = Duration::from_secs(60); + +/// `Retry-After` value advertised with `429`. The budget window is one minute, +/// so this is the maximum time a client must wait for a fresh window. +const METRICS_AUTH_RETRY_AFTER_SECS: &str = "60"; /// Historical CORS cache-key token: the only `Vary` value the pre-migration /// server ever emitted. Allow-all responses omit `Vary` entirely. @@ -96,7 +105,7 @@ async fn handle_request( (status, Some((body, "application/json"))) } ("GET" | "HEAD", "/metrics") => { - let (status, body, content_type) = metrics_response(&state, request_headers); + let (status, body, content_type) = metrics_response(&state, request_headers).await; (status, Some((body, content_type))) } (_, "/health" | "/metrics") => (405, None), @@ -124,6 +133,12 @@ async fn handle_request( "Basic realm=\"metrics\", charset=\"UTF-8\"".to_owned(), )); } + // RFC 9110 §15.5.30: a 429 MAY advertise how long to wait. Deliberately no + // `WWW-Authenticate` here — challenging a throttled caller would invite + // exactly the retry the budget exists to bound. + if status == 429 { + response_headers.push(("retry-after", METRICS_AUTH_RETRY_AFTER_SECS.to_owned())); + } if let Some(origin) = get_header(request_headers, "origin") && origin_allowed(&cors, &origin) { @@ -143,7 +158,7 @@ async fn handle_request( Ok(make_response(status, body, content_type, response_headers)) } -fn metrics_response( +async fn metrics_response( state: &AppState, request_headers: &HeaderBlock, ) -> (u16, Vec, &'static str) { @@ -179,6 +194,29 @@ fn metrics_response( // (`SnippetSyncService::record_auth_failure`). Without it the metric // could never observe HTTP brute force. state.metrics.auth_failures.inc(); + + // Bound password guessing. The budget is global and failure-only: + // correct credentials never reach this branch, so an attacker cannot + // lock the operator out of their own scrape by burning it. The leaf's + // `RequestHead` carries no peer address, so a per-caller budget is not + // available here; a global failure budget is the bounded design that + // the current handler shape supports. + let within_budget = state + .rate_limiter + .allow( + "metrics-auth", + state.config.metrics_auth_failures_per_minute as usize, + METRICS_AUTH_WINDOW, + ) + .await; + if !within_budget { + state.metrics.rate_limit_hits.inc(); + return ( + 429, + b"Too many failed authentication attempts".to_vec(), + "text/plain; charset=utf-8", + ); + } return ( 401, b"Authentication required".to_vec(), diff --git a/snip-sync/src/lib.rs b/snip-sync/src/lib.rs index 50c4e8a8..66f266c1 100644 --- a/snip-sync/src/lib.rs +++ b/snip-sync/src/lib.rs @@ -121,6 +121,14 @@ pub const DEFAULT_MAX_API_KEY_LENGTH: usize = 512; pub const DEFAULT_MAX_SYNC_SNIPPETS: usize = 10000; pub const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 30; pub const DEFAULT_RATE_LIMIT_PER_MINUTE: u32 = 120; +/// Global ceiling on successful account creations per minute, independent of +/// the caller's address. The per-peer `register:` budget alone lets an +/// attacker with many addresses grow the user table without bound. +pub const DEFAULT_REGISTER_PER_MINUTE: u32 = 10; +/// Global ceiling on **failed** `/metrics` authentications per minute. Correct +/// credentials never consume it, so an attacker cannot deny the operator their +/// own scrape by burning the budget. +pub const DEFAULT_METRICS_AUTH_FAILURES_PER_MINUTE: u32 = 10; /// Multiplier applied to the per-peer budget for requests that have **not** /// yet authenticated. The pre-authentication budget only has to bound the cost /// of an API-key lookup, so it is generous by design: an unauthenticated @@ -229,6 +237,10 @@ pub struct LimitsConfig { #[derive(Deserialize, Default)] pub struct RateLimitConfig { pub requests_per_minute: Option, + /// Global per-minute ceiling on account creation (all peers combined). + pub register_per_minute: Option, + /// Global per-minute ceiling on failed `/metrics` authentications. + pub metrics_auth_failures_per_minute: Option, pub trusted_proxies: Option>, } @@ -263,6 +275,10 @@ pub struct Config { pub request_timeout_secs: u64, pub grpc_max_message_size: u32, pub rate_limit_per_minute: u32, + /// Global per-minute ceiling on account creation, across all peers. + pub register_per_minute: u32, + /// Global per-minute ceiling on failed `/metrics` authentications. + pub metrics_auth_failures_per_minute: u32, pub trusted_proxies: Vec, pub metrics_username: Option, pub metrics_password: Option, @@ -485,6 +501,18 @@ impl Config { .as_ref() .and_then(|r| r.requests_per_minute)) .unwrap_or(DEFAULT_RATE_LIMIT_PER_MINUTE), + register_per_minute: parse_env(env, "REGISTER_PER_MINUTE")? + .or(server + .rate_limit + .as_ref() + .and_then(|r| r.register_per_minute)) + .unwrap_or(DEFAULT_REGISTER_PER_MINUTE), + metrics_auth_failures_per_minute: parse_env(env, "METRICS_AUTH_FAILURES_PER_MINUTE")? + .or(server + .rate_limit + .as_ref() + .and_then(|r| r.metrics_auth_failures_per_minute)) + .unwrap_or(DEFAULT_METRICS_AUTH_FAILURES_PER_MINUTE), trusted_proxies: env("TRUSTED_PROXIES") .map(|v| { v.split(',') @@ -613,6 +641,24 @@ impl Config { reason: "must be nonzero".into(), }); } + // Zero is a hard error, not "unlimited": a zero registration budget + // makes account creation impossible, and a zero metrics-failure budget + // makes the second failed scrape return 429 forever. Both are almost + // certainly operator mistakes. + if self.register_per_minute == 0 { + return Err(ConfigLoadError::InvalidRange { + name: "REGISTER_PER_MINUTE", + value: self.register_per_minute.to_string(), + reason: "must be nonzero".into(), + }); + } + if self.metrics_auth_failures_per_minute == 0 { + return Err(ConfigLoadError::InvalidRange { + name: "METRICS_AUTH_FAILURES_PER_MINUTE", + value: self.metrics_auth_failures_per_minute.to_string(), + reason: "must be nonzero".into(), + }); + } Ok(()) } @@ -628,6 +674,10 @@ pub struct AppState { pub config: Config, pub metrics: Metrics, pub db: Arc, + /// The same process-local limiter the gRPC service uses. Sharing it keeps + /// one bounded structure (and one `MAX_ENTRIES` budget) for both listeners + /// instead of inventing a second one for the HTTP leaf. + pub rate_limiter: Arc, } pub struct SnipSyncService { @@ -986,7 +1036,7 @@ impl SnipSyncService { // Sample server time once to avoid micro-boundary disagreement // between consecutive timestamp checks. - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let tolerance = 300; // 5 minutes if snippet.updated_at > now + tolerance { @@ -1081,6 +1131,32 @@ impl SnippetSync for SnipSyncService { )); } + // Per-peer budgets do not bound a caller that rotates addresses, and + // every registration inserts a user plus a default library. The global + // budget is deliberately a separate key so a legitimate caller is not + // charged for an attacker's traffic on another address: it caps total + // account creation, not per-caller fairness. + if !self + .rate_limiter + .allow( + "register-global", + self.config.register_per_minute as usize, + Duration::from_secs(60), + ) + .await + { + self.record_rate_limit(); + self.record_request_duration("register", start); + self.record_request_finished("register", false); + tracing::warn!( + request_id = %request_id, + "Rejected registration: global per-minute ceiling reached" + ); + return Err(Status::resource_exhausted( + "Registration is temporarily unavailable: global account-creation limit reached", + )); + } + let _req = request.into_inner(); let api_key = uuid::Uuid::new_v4().to_string(); @@ -2128,6 +2204,8 @@ mod tests { request_timeout_secs: 30, grpc_max_message_size: 4 * 1024 * 1024, rate_limit_per_minute, + register_per_minute: DEFAULT_REGISTER_PER_MINUTE, + metrics_auth_failures_per_minute: DEFAULT_METRICS_AUTH_FAILURES_PER_MINUTE, trusted_proxies: vec![], metrics_username: None, metrics_password: None, @@ -2346,7 +2424,7 @@ mod tests { #[tokio::test] async fn test_validate_snippet_future_timestamp() { let service = setup_test_service().await; - let future = chrono::Utc::now().timestamp() + 600; + let future = time::OffsetDateTime::now_utc().unix_timestamp() + 600; let snippet = ProtoSnippet { id: "test-id".to_string(), description: "test".to_string(), @@ -2389,7 +2467,7 @@ mod tests { #[tokio::test] async fn test_validate_snippet_clock_skew_reports_magnitude() { let service = setup_test_service().await; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let snippet = ProtoSnippet { id: "skew-id".to_string(), description: "test".to_string(), @@ -2417,7 +2495,7 @@ mod tests { #[tokio::test] async fn test_validate_snippet_created_ahead_reports_skew() { let service = setup_test_service().await; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let snippet = ProtoSnippet { id: "skew-created".to_string(), description: "test".to_string(), @@ -2461,7 +2539,7 @@ mod tests { #[tokio::test] async fn test_validate_snippet_valid() { let service = setup_test_service().await; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let snippet = ProtoSnippet { id: "test-id".to_string(), description: "test".to_string(), @@ -2559,8 +2637,8 @@ mod tests { description: "git status".to_string(), command: "git status".to_string(), tags: vec![], - created_at: chrono::Utc::now().timestamp(), - updated_at: chrono::Utc::now().timestamp(), + created_at: time::OffsetDateTime::now_utc().unix_timestamp(), + updated_at: time::OffsetDateTime::now_utc().unix_timestamp(), device_id: "device-1".to_string(), deleted: false, encrypted: false, @@ -2620,8 +2698,8 @@ mod tests { description: "git status".to_string(), command: "git status".to_string(), tags: vec![], - created_at: chrono::Utc::now().timestamp(), - updated_at: chrono::Utc::now().timestamp(), + created_at: time::OffsetDateTime::now_utc().unix_timestamp(), + updated_at: time::OffsetDateTime::now_utc().unix_timestamp(), device_id: "device-1".to_string(), deleted: false, encrypted: false, @@ -2659,7 +2737,7 @@ mod tests { .into_inner() .library_id; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let newer = ProtoSnippet { id: "snippet-1".to_string(), description: "newer".to_string(), @@ -2854,8 +2932,8 @@ mod tests { description: "Test snippet".to_string(), command: "echo hello".to_string(), tags: vec!["test".to_string()], - created_at: chrono::Utc::now().timestamp(), - updated_at: chrono::Utc::now().timestamp(), + created_at: time::OffsetDateTime::now_utc().unix_timestamp(), + updated_at: time::OffsetDateTime::now_utc().unix_timestamp(), device_id: "device-1".to_string(), deleted: false, encrypted: false, @@ -3422,6 +3500,121 @@ mod tests { } } + #[test] + fn config_validate_rejects_zero_register_per_minute() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write(&path, "[server.rate_limit]\nregister_per_minute = 0\n").unwrap(); + let err = Config::load_from(&path, &|_| None).unwrap_err(); + match err { + ConfigLoadError::InvalidRange { name, .. } => assert_eq!(name, "REGISTER_PER_MINUTE"), + other => panic!("expected InvalidRange, got: {other}"), + } + } + + #[test] + fn config_validate_rejects_zero_metrics_auth_failures_per_minute() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write( + &path, + "[server.rate_limit]\nmetrics_auth_failures_per_minute = 0\n", + ) + .unwrap(); + let err = Config::load_from(&path, &|_| None).unwrap_err(); + match err { + ConfigLoadError::InvalidRange { name, .. } => { + assert_eq!(name, "METRICS_AUTH_FAILURES_PER_MINUTE") + } + other => panic!("expected InvalidRange, got: {other}"), + } + } + + #[test] + fn config_defaults_new_rate_limit_keys_when_absent() { + // An existing config that predates the keys must keep loading, and the + // defaults must be documented values rather than zero. + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write(&path, "[server.rate_limit]\nrequests_per_minute = 60\n").unwrap(); + let config = Config::load_from(&path, &|_| None).unwrap(); + assert_eq!(config.rate_limit_per_minute, 60); + assert_eq!(config.register_per_minute, DEFAULT_REGISTER_PER_MINUTE); + assert_eq!( + config.metrics_auth_failures_per_minute, + DEFAULT_METRICS_AUTH_FAILURES_PER_MINUTE + ); + } + + #[test] + fn config_reads_new_rate_limit_keys_from_file_and_env() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write( + &path, + "[server.rate_limit]\nregister_per_minute = 3\nmetrics_auth_failures_per_minute = 4\n", + ) + .unwrap(); + let config = Config::load_from(&path, &|_| None).unwrap(); + assert_eq!(config.register_per_minute, 3); + assert_eq!(config.metrics_auth_failures_per_minute, 4); + + // Environment overrides win over the file. + let env = |name: &str| match name { + "REGISTER_PER_MINUTE" => Some("7".to_string()), + "METRICS_AUTH_FAILURES_PER_MINUTE" => Some("8".to_string()), + _ => None, + }; + let config = Config::load_from(&path, &env).unwrap(); + assert_eq!(config.register_per_minute, 7); + assert_eq!(config.metrics_auth_failures_per_minute, 8); + } + + #[tokio::test] + async fn register_global_budget_rejects_without_writing_rows() { + let mut service = setup_test_service().await; + service.config.register_per_minute = 2; + + let count_users = |db: Arc| async move { + let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users") + .fetch_one(db.pool()) + .await + .expect("counting users must succeed"); + count + }; + + for attempt in 1..=2 { + let response = service + .register(Request::new(RegisterRequest { + device_id: String::new(), + })) + .await + .unwrap_or_else(|status| { + panic!("registration {attempt} should succeed, got {status:?}") + }); + assert!(response.get_ref().success); + } + assert_eq!(count_users(service.db.clone()).await, 2); + + let rejection = service + .register(Request::new(RegisterRequest { + device_id: String::new(), + })) + .await + .expect_err("the third registration must exceed the global budget"); + assert_eq!(rejection.code(), tonic::Code::ResourceExhausted); + assert!( + rejection.message().contains("global"), + "the rejection must be distinguishable from the per-peer budget: {}", + rejection.message() + ); + assert_eq!( + count_users(service.db.clone()).await, + 2, + "a rejected registration must not insert a user row" + ); + } + #[test] fn config_load_rejects_malformed_numeric_env() { let dir = tempfile::tempdir().unwrap(); diff --git a/snip-sync/src/main.rs b/snip-sync/src/main.rs index dd2939f8..d52a89e3 100644 --- a/snip-sync/src/main.rs +++ b/snip-sync/src/main.rs @@ -219,6 +219,9 @@ async fn serve_inner(config: snip_sync::Config) -> Result<(), Box path.clone(), None => config_dir.join("backups").join(×tamp), @@ -74,7 +78,9 @@ pub fn run( let generation_before = read_library_generation(&config_dir)?; let mut manifest = BackupManifest { schema: 1, - created_at_unix_ms: chrono::Utc::now().timestamp_millis(), + created_at_unix_ms: (time::OffsetDateTime::now_utc() + .unix_timestamp_nanos() + .div_euclid(1_000_000)) as i64, snip_it_version: crate::diagnostics::version().to_string(), layout: "directory".to_string(), files: Vec::new(), diff --git a/src/commands/edit_cmd.rs b/src/commands/edit_cmd.rs index a90631c6..1ca63be2 100644 --- a/src/commands/edit_cmd.rs +++ b/src/commands/edit_cmd.rs @@ -213,7 +213,7 @@ pub fn run_edit_output( let snippet = &mut snippets.snippets[idx]; snippet.output = new_output.clone().unwrap_or_default(); - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); snippet.updated_at = snippet.updated_at.max(now).saturating_add(1); desc = snippet.description.clone(); is_empty = snippet.output.is_empty(); @@ -283,7 +283,7 @@ pub fn run_edit_output_by_id( let snippet = &mut snippets.snippets[idx]; snippet.output = new_output.clone().unwrap_or_default(); - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); snippet.updated_at = snippet.updated_at.max(now).saturating_add(1); desc = snippet.description.clone(); is_empty = snippet.output.is_empty(); diff --git a/src/commands/import_cmd.rs b/src/commands/import_cmd.rs index cb149598..235e177c 100644 --- a/src/commands/import_cmd.rs +++ b/src/commands/import_cmd.rs @@ -145,7 +145,7 @@ fn convert_entry( snippet.id = uuid::Uuid::new_v4().to_string(); // Ensure timestamps are set - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); if snippet.created_at == 0 { snippet.created_at = now; } diff --git a/src/commands/library_cmd.rs b/src/commands/library_cmd.rs index 6f9eea33..c3476c5f 100644 --- a/src/commands/library_cmd.rs +++ b/src/commands/library_cmd.rs @@ -90,8 +90,14 @@ pub fn run_show(name: Option) -> SnipResult<()> { if let Some(ts) = lib.last_sync { println!( " Last sync: {}", - chrono::DateTime::from_timestamp(ts, 0) - .map(|dt| dt.format("%Y-%m-%d %H:%M").to_string()) + time::OffsetDateTime::from_unix_timestamp(ts) + .ok() + .and_then(|dt| { + dt.format(&time::macros::format_description!( + "[year]-[month]-[day] [hour]:[minute]" + )) + .ok() + }) .unwrap_or_else(|| "unknown".to_string()) ); } diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 0854ce68..790a6c9e 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -788,7 +788,7 @@ pub fn update_snippet_fields( Some("The snippet already matches the requested state"), )); } - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); target.updated_at = target.updated_at.max(now).saturating_add(1); updated = Some(target.clone()); Ok(()) @@ -934,7 +934,7 @@ pub fn delete_snippet( }; let target = &mut current.snippets[index]; target.deleted = true; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); target.updated_at = target.updated_at.max(now).saturating_add(1); deleted = Some(target.clone()); Ok(()) @@ -1036,7 +1036,7 @@ fn mark_snippet_deleted( })?; snippet.deleted = true; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); snippet.updated_at = snippet.updated_at.max(now).saturating_add(1); Ok(snippet.clone()) } diff --git a/src/commands/repair_cmd.rs b/src/commands/repair_cmd.rs index 3c8b9187..71caff24 100644 --- a/src/commands/repair_cmd.rs +++ b/src/commands/repair_cmd.rs @@ -960,13 +960,21 @@ fn create_repair_backup() -> SnipResult { fs::create_dir_all(&backup_root) .map_err(|e| SnipError::io_error("create backup directory", backup_root.clone(), e))?; - let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S"); + let timestamp = time::OffsetDateTime::now_utc() + .format(&time::macros::format_description!( + "[year][month][day]_[hour][minute][second]" + )) + .map_err(|e| { + SnipError::runtime_error("format repair backup timestamp", Some(&e.to_string())) + })?; let backup_dir = backup_root.join(format!("repair-{timestamp}-{}", uuid::Uuid::new_v4())); let staging_dir = backup_dir.with_extension(format!("staging.{}", uuid::Uuid::new_v4())); let mut manifest = BackupManifest { schema: 1, - created_at_unix_ms: chrono::Utc::now().timestamp_millis(), + created_at_unix_ms: (time::OffsetDateTime::now_utc() + .unix_timestamp_nanos() + .div_euclid(1_000_000)) as i64, snip_it_version: crate::diagnostics::version().to_string(), layout: "directory".to_string(), files: Vec::new(), diff --git a/src/commands/restore_cmd.rs b/src/commands/restore_cmd.rs index 883b9731..f2da3e90 100644 --- a/src/commands/restore_cmd.rs +++ b/src/commands/restore_cmd.rs @@ -758,7 +758,13 @@ fn create_pre_restore_backup(config_dir: &Path) -> SnipResult> { return Ok(None); } - let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S").to_string(); + let timestamp = time::OffsetDateTime::now_utc() + .format(&time::macros::format_description!( + "[year][month][day]_[hour][minute][second]" + )) + .map_err(|e| { + SnipError::runtime_error("format restore backup timestamp", Some(&e.to_string())) + })?; // The UUID suffix keeps two restores in the same second from resolving to // the same directory: the second restore's snapshot would otherwise // overwrite the first restore's pre-restore state. diff --git a/src/commands/status_cmd.rs b/src/commands/status_cmd.rs index 3360428d..13ba1b09 100644 --- a/src/commands/status_cmd.rs +++ b/src/commands/status_cmd.rs @@ -1,7 +1,7 @@ use crate::error::SnipResult; use crate::status_snapshot::{TopLevelSyncState, capture_snapshot}; -use chrono::{Local, TimeZone, Utc}; use std::io::{self, Write}; +use time::{OffsetDateTime, UtcOffset}; /// Canonical Clap arguments for `snp status` and `snp data status`. /// @@ -53,10 +53,7 @@ pub fn run(json: bool, sync_only: bool) -> SnipResult<()> { } if snapshot.attempt.last_attempt_at_unix_ms > 0 { - let dt = Utc - .timestamp_millis_opt(snapshot.attempt.last_attempt_at_unix_ms as i64) - .single() - .map(|dt: chrono::DateTime| dt.with_timezone(&Local)); + let dt = local_datetime(snapshot.attempt.last_attempt_at_unix_ms); if let Some(local_dt) = dt { let class = if snapshot.attempt.last_failure_class.is_empty() { "unknown".to_string() @@ -73,10 +70,7 @@ pub fn run(json: bool, sync_only: bool) -> SnipResult<()> { .map(|d| d.as_millis() as u64) .unwrap_or(0); if snapshot.attempt.next_attempt_at_unix_ms > now_ms { - let dt = Utc - .timestamp_millis_opt(snapshot.attempt.next_attempt_at_unix_ms as i64) - .single() - .map(|dt: chrono::DateTime| dt.with_timezone(&Local)); + let dt = local_datetime(snapshot.attempt.next_attempt_at_unix_ms); if let Some(local_dt) = dt { out.push_str(&format!("Next retry: {local_dt}\n")); } @@ -122,10 +116,7 @@ fn format_action(top: &TopLevelSyncState) -> Option { TopLevelSyncState::PendingRetryBackoff { next_attempt_at_unix_ms, } => { - let dt = Utc - .timestamp_millis_opt(*next_attempt_at_unix_ms as i64) - .single() - .map(|dt: chrono::DateTime| dt.with_timezone(&Local)); + let dt = local_datetime(*next_attempt_at_unix_ms); dt.map(|local_dt| format!("Action: retry eligible at {local_dt}")) } TopLevelSyncState::CorruptOrInaccessible => { @@ -134,3 +125,9 @@ fn format_action(top: &TopLevelSyncState) -> Option { _ => None, } } + +fn local_datetime(unix_ms: u64) -> Option { + let utc = OffsetDateTime::from_unix_timestamp_nanos(i128::from(unix_ms) * 1_000_000).ok()?; + let offset = UtcOffset::local_offset_at(utc).ok()?; + Some(utc.to_offset(offset)) +} diff --git a/src/encryption.rs b/src/encryption.rs index a5540825..c9dee35a 100644 --- a/src/encryption.rs +++ b/src/encryption.rs @@ -12,6 +12,28 @@ //! - **Key Derivation**: Argon2id from API key + random salt //! - **Nonce**: Random 12-byte nonce per encryption (stored with ciphertext) //! +//! # Payload version contract +//! +//! Three layouts are readable, and only version 1 is written: +//! +//! | Version | Layout | Identity binding | +//! |---------|--------|------------------| +//! | 0 | legacy: `salt ‖ nonce ‖ ciphertext` | none | +//! | 1 | `magic ‖ 1 ‖ salt ‖ nonce ‖ ciphertext` | none | +//! | 2 | same header, version `2` | AAD over the snippet id | +//! +//! Version 2 authenticates the snippet id as associated data, so a ciphertext +//! sealed for one snippet fails the tag check under a different id. It is read +//! but never written by this build: switching the write path is a separate, +//! release-gated step (see +//! `plans/subsystems/security-assurance-roadmap.md` M006), because a client +//! that only understands version 1 would skip every version-2 payload. +//! +//! [`decrypt`] therefore rejects version 2 explicitly: it cannot supply the +//! identity the tag was computed over, and silently decrypting without AAD +//! would void the binding. Callers that hold the snippet id use +//! [`decrypt_for_snippet`]. +//! //! # Example //! //! ```text @@ -21,7 +43,7 @@ use aes_gcm::{ Aes256Gcm, Nonce, - aead::{Aead, Generate, KeyInit}, + aead::{Aead, Generate, KeyInit, Payload}, }; use argon2::Argon2; use base64::{Engine, engine::general_purpose::STANDARD as BASE64}; @@ -148,6 +170,30 @@ const PAYLOAD_VERSION: u8 = 1; /// Version of the pre-magic (unversioned) payload layout. const PAYLOAD_VERSION_LEGACY: u8 = 0; +/// Version whose tag is computed over associated data derived from the snippet +/// id. Read-only in this build; see the module-level payload version contract. +const PAYLOAD_VERSION_V2: u8 = 2; + +/// Domain separation tag for the version-2 associated data. +/// +/// The tag keeps this AAD from colliding with any future use of the same +/// primitive, and the length prefix removes concatenation ambiguity if a +/// second field is ever appended (`id="ab", x="c"` must not hash like +/// `id="a", x="bc"`). ADR-0002 is normative if this construction and the ADR +/// ever disagree. +const PAYLOAD_AAD_DOMAIN: &[u8] = b"snip-payload-v2\0"; + +/// Build the version-2 associated data for a snippet id. +/// +/// AAD is public data: it adds no key material and is never logged. +fn payload_aad(snippet_id: &str) -> Vec { + let mut aad = Vec::with_capacity(PAYLOAD_AAD_DOMAIN.len() + 4 + snippet_id.len()); + aad.extend_from_slice(PAYLOAD_AAD_DOMAIN); + aad.extend_from_slice(&(snippet_id.len() as u32).to_le_bytes()); + aad.extend_from_slice(snippet_id.as_bytes()); + aad +} + /// Encrypted data container with version, salt, nonce, and ciphertext. /// /// The salt and nonce are stored alongside the ciphertext to enable @@ -187,7 +233,7 @@ impl EncryptedPayload { let header = PAYLOAD_MAGIC.len() + 1; if combined.len() >= header && combined[..PAYLOAD_MAGIC.len()] == PAYLOAD_MAGIC { let version = combined[PAYLOAD_MAGIC.len()]; - if version != PAYLOAD_VERSION { + if version != PAYLOAD_VERSION && version != PAYLOAD_VERSION_V2 { return Err(CryptoError::InvalidData(format!( "Unsupported payload version {version}" ))); @@ -229,12 +275,12 @@ impl EncryptedPayload { /// Argon2id parameters for a payload version. /// -/// Version 0 (the legacy unversioned layout) and version 1 use the same -/// parameters. A parameter change must introduce a new version: changing -/// these in place would make every stored payload undecryptable. +/// Versions 0 (legacy unversioned), 1, and 2 use the same parameters; only the +/// associated data differs. A parameter change must introduce a new version: +/// changing these in place would make every stored payload undecryptable. fn argon2_params_for_version(version: u8) -> Option<(u32, u32, u32)> { match version { - PAYLOAD_VERSION_LEGACY | PAYLOAD_VERSION => { + PAYLOAD_VERSION_LEGACY | PAYLOAD_VERSION | PAYLOAD_VERSION_V2 => { Some((ARGON2_MEMORY_COST_KIB, ARGON2_TIME_COST, ARGON2_PARALLELISM)) } _ => None, @@ -318,7 +364,23 @@ pub fn encrypt_with_salt( plaintext: &str, salt: &[u8; SALT_SIZE], ) -> CryptoResult { - let mut key = derive_key(api_key, salt, PAYLOAD_VERSION)?; + // Version 1 carries no associated data, so the seal is byte-identical to + // what earlier builds produced. + seal_with_salt(api_key, plaintext, salt, PAYLOAD_VERSION, b"") +} + +/// The single sealing path shared by every payload version. +/// +/// `aad` is empty for versions 0 and 1. AES-GCM treats an empty AAD exactly as +/// "no AAD", so version-1 output stays byte-compatible. +fn seal_with_salt( + api_key: &str, + plaintext: &str, + salt: &[u8; SALT_SIZE], + version: u8, + aad: &[u8], +) -> CryptoResult { + let mut key = derive_key(api_key, salt, version)?; let cipher = Aes256Gcm::new_from_slice(key.as_slice()) .map_err(|e| CryptoError::EncryptionFailed(format!("Key init failed: {e}")))?; @@ -326,13 +388,19 @@ pub fn encrypt_with_salt( let nonce = Nonce::generate(); let ciphertext = cipher - .encrypt(&nonce, plaintext.as_bytes()) + .encrypt( + &nonce, + Payload { + msg: plaintext.as_bytes(), + aad, + }, + ) .map_err(|e| CryptoError::EncryptionFailed(format!("Encryption failed: {e}")))?; key.zeroize(); let payload = EncryptedPayload { - version: PAYLOAD_VERSION, + version, salt: salt.to_vec(), nonce: nonce.to_vec(), ciphertext, @@ -341,9 +409,59 @@ pub fn encrypt_with_salt( Ok(payload.to_base64()) } +/// Decrypt a payload that carries no snippet identity. +/// +/// Version 2 payloads are rejected here on purpose: their tag is computed over +/// the snippet id, and there is no safe value to supply from this entry point. +/// Use [`decrypt_for_snippet`] when the id is known. +/// +/// This entry point is compiled only for tests. No production caller can hold a +/// payload without its identity (the sync path always has the proto row's id), +/// so keeping it out of production builds turns "decrypt without the binding" +/// into a compile error rather than a runtime one. The runtime rejection is +/// still exercised by the unit tests, which is where the fail-loud contract is +/// pinned. +#[cfg(any(test, feature = "test-support"))] pub fn decrypt(api_key: &str, encrypted_data: &str) -> CryptoResult { let payload = EncryptedPayload::from_base64(encrypted_data)?; + let aad = associated_data(&payload, "")?; + open_payload(api_key, &payload, &aad) +} +/// Decrypt a payload, verifying the snippet identity for version 2. +/// +/// Version 0/1 payloads carry no identity binding and decrypt exactly as they +/// always did; `snippet_id` is ignored for them. +pub(crate) fn decrypt_for_snippet( + api_key: &str, + encrypted_data: &str, + snippet_id: &str, +) -> CryptoResult { + let payload = EncryptedPayload::from_base64(encrypted_data)?; + let aad = associated_data(&payload, snippet_id)?; + open_payload(api_key, &payload, &aad) +} + +/// The associated data a payload's tag was computed over. +fn associated_data(payload: &EncryptedPayload, snippet_id: &str) -> CryptoResult> { + match payload.version { + PAYLOAD_VERSION_V2 => { + if snippet_id.is_empty() { + // A version-2 payload sealed with an empty id would authenticate + // any id-less reader; the seal path rejects empty ids, so this + // is a malformed row rather than a valid binding. + return Err(CryptoError::InvalidData( + "payload version 2 requires snippet identity".to_string(), + )); + } + Ok(payload_aad(snippet_id)) + } + _ => Ok(Vec::new()), + } +} + +/// The single opening path shared by every payload version. +fn open_payload(api_key: &str, payload: &EncryptedPayload, aad: &[u8]) -> CryptoResult { let mut key = derive_key(api_key, &payload.salt, payload.version)?; let cipher = Aes256Gcm::new_from_slice(key.as_slice()) @@ -353,7 +471,15 @@ pub fn decrypt(api_key: &str, encrypted_data: &str) -> CryptoResult { .map_err(|_| CryptoError::InvalidData("Invalid nonce length".to_string()))?; let plaintext = cipher - .decrypt(&nonce, payload.ciphertext.as_ref()) + .decrypt( + &nonce, + Payload { + msg: payload.ciphertext.as_ref(), + aad, + }, + ) + // A wrong id and a wrong key both surface as a tag mismatch, so the + // error is not an oracle for which one was wrong. .map_err(|e| CryptoError::DecryptionFailed(format!("Decryption failed: {e}")))?; drop(std::mem::take(&mut key)); @@ -368,6 +494,33 @@ pub fn decrypt(api_key: &str, encrypted_data: &str) -> CryptoResult { .map_err(|e| CryptoError::DecryptionFailed(format!("UTF-8 conversion failed: {e}"))) } +/// Seal a version-2 payload bound to `snippet_id`. +/// +/// Test- and integration-only: no production path writes version 2 until the +/// release-gated write switch lands. It reuses the production cipher and AAD +/// construction rather than carrying a second implementation. +#[cfg(any(test, feature = "test-support"))] +#[doc(hidden)] +pub fn seal_v2_for_test( + api_key: &str, + plaintext: &str, + snippet_id: &str, + salt: &[u8; SALT_SIZE], +) -> CryptoResult { + if snippet_id.is_empty() { + return Err(CryptoError::InvalidData( + "payload version 2 requires snippet identity".to_string(), + )); + } + seal_with_salt( + api_key, + plaintext, + salt, + PAYLOAD_VERSION_V2, + &payload_aad(snippet_id), + ) +} + #[cfg(test)] mod tests { use super::*; @@ -530,8 +683,17 @@ mod tests { let api_key = "test-key"; let encrypted = encrypt(api_key, "sensitive data").unwrap(); let mut payload = EncryptedPayload::from_base64(&encrypted).unwrap(); - payload.version = PAYLOAD_VERSION + 1; + // One past the highest version this build understands. + payload.version = PAYLOAD_VERSION_V2 + 1; let future = payload.to_base64(); + let err = match EncryptedPayload::from_base64(&future) { + Ok(_) => panic!("parsing a future payload version must be rejected"), + Err(err) => err, + }; + assert!( + err.to_string().contains("Unsupported payload version"), + "unexpected error: {err}" + ); let err = decrypt(api_key, &future).unwrap_err(); assert!( err.to_string().contains("Unsupported payload version"), @@ -539,6 +701,134 @@ mod tests { ); } + #[test] + fn v2_roundtrip_with_the_correct_id() { + let api_key = "test-key"; + let plaintext = r#"{"description":"d","command":"echo hi","tags":[]}"#; + let salt = generate_salt(); + let sealed = seal_v2_for_test(api_key, plaintext, "snippet-a", &salt).unwrap(); + + let payload = EncryptedPayload::from_base64(&sealed).unwrap(); + assert_eq!(payload.version, PAYLOAD_VERSION_V2); + + assert_eq!( + decrypt_for_snippet(api_key, &sealed, "snippet-a").unwrap(), + plaintext + ); + } + + #[test] + fn v2_fails_with_a_different_id() { + let api_key = "test-key"; + let salt = generate_salt(); + let sealed = seal_v2_for_test(api_key, "secret", "snippet-a", &salt).unwrap(); + + let err = decrypt_for_snippet(api_key, &sealed, "snippet-b").unwrap_err(); + // A wrong id is a tag mismatch: the same class of error as a wrong key, + // so it does not reveal which of the two was wrong. + assert!( + matches!(err, CryptoError::DecryptionFailed(_)), + "expected a tag failure, got {err:?}" + ); + } + + #[test] + fn v2_without_identity_is_rejected_loudly() { + let api_key = "test-key"; + let salt = generate_salt(); + let sealed = seal_v2_for_test(api_key, "secret", "snippet-a", &salt).unwrap(); + + // The id-less entry point cannot authenticate the AAD, so it must + // refuse rather than decrypt without it. + let err = decrypt(api_key, &sealed).unwrap_err(); + assert!( + err.to_string().contains("requires snippet identity"), + "unexpected error: {err}" + ); + + // The same refusal applies to an empty id supplied through the + // identity-aware entry point. + let err = decrypt_for_snippet(api_key, &sealed, "").unwrap_err(); + assert!( + err.to_string().contains("requires snippet identity"), + "unexpected error: {err}" + ); + } + + #[test] + fn v2_seal_rejects_an_empty_id() { + let salt = generate_salt(); + let err = seal_v2_for_test("test-key", "secret", "", &salt).unwrap_err(); + assert!( + err.to_string().contains("requires snippet identity"), + "unexpected error: {err}" + ); + } + + #[test] + fn v1_payloads_still_decrypt_through_both_entry_points() { + let api_key = "test-key"; + let plaintext = "legacy content"; + let encrypted = encrypt_with_salt(api_key, plaintext, &generate_salt()).unwrap(); + + // Version 1 carries no identity binding, so the id is irrelevant and + // both entry points must succeed. + assert_eq!(decrypt(api_key, &encrypted).unwrap(), plaintext); + assert_eq!( + decrypt_for_snippet(api_key, &encrypted, "any-id").unwrap(), + plaintext + ); + } + + #[test] + fn legacy_unversioned_payloads_still_decrypt_through_both_entry_points() { + let api_key = "test-key"; + let plaintext = "ancient content"; + let encrypted = encrypt_with_salt(api_key, plaintext, &generate_salt()).unwrap(); + let payload = EncryptedPayload::from_base64(&encrypted).unwrap(); + + let mut legacy = Vec::new(); + legacy.extend_from_slice(&payload.salt); + legacy.extend_from_slice(&payload.nonce); + legacy.extend_from_slice(&payload.ciphertext); + let legacy_b64 = BASE64.encode(&legacy); + + assert_eq!(decrypt(api_key, &legacy_b64).unwrap(), plaintext); + assert_eq!( + decrypt_for_snippet(api_key, &legacy_b64, "any-id").unwrap(), + plaintext + ); + } + + #[test] + fn v2_tampered_ciphertext_still_fails_the_tag() { + let api_key = "test-key"; + let salt = generate_salt(); + let sealed = seal_v2_for_test(api_key, "secret", "snippet-a", &salt).unwrap(); + + let mut payload = EncryptedPayload::from_base64(&sealed).unwrap(); + payload.ciphertext[0] ^= 0xFF; + let tampered = payload.to_base64(); + + assert!( + decrypt_for_snippet(api_key, &tampered, "snippet-a").is_err(), + "a tampered v2 ciphertext must not decrypt" + ); + } + + #[test] + fn aad_construction_is_unambiguous() { + // The length prefix means two different id splits cannot collide. + let a = payload_aad("ab"); + let mut b = PAYLOAD_AAD_DOMAIN.to_vec(); + b.extend_from_slice(&1u32.to_le_bytes()); + b.extend_from_slice(b"a"); + b.extend_from_slice(b"b"); + assert_ne!(a, b, "concatenation must not be ambiguous"); + assert_eq!(a, payload_aad("ab"), "the construction is deterministic"); + assert_ne!(a, payload_aad("ac")); + } + #[test] fn test_ct_eq() { let a = b"hello world"; diff --git a/src/library/model.rs b/src/library/model.rs index e3a929b4..a08f149b 100644 --- a/src/library/model.rs +++ b/src/library/model.rs @@ -341,7 +341,7 @@ impl Snippet { Some("Snippet description cannot be empty"), )); } - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); Ok(Self { id: String::new(), description, diff --git a/src/library/persistence.rs b/src/library/persistence.rs index 5ca89270..fbcd3b68 100644 --- a/src/library/persistence.rs +++ b/src/library/persistence.rs @@ -398,7 +398,13 @@ pub fn backup_library(path: &Path) -> SnipResult> { // Clean up old backups (keep at most 10 per library) cleanup_old_backups(&backup_dir, path)?; - let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S_%f"); + let timestamp = time::OffsetDateTime::now_utc() + .format(&time::macros::format_description!( + "[year][month][day]_[hour][minute][second]_[subsecond digits:9]" + )) + .map_err(|e| { + SnipError::runtime_error("format library backup timestamp", Some(&e.to_string())) + })?; let file_stem = path.file_stem().ok_or_else(|| { SnipError::runtime_error( "backup path has no file stem", diff --git a/src/local_data.rs b/src/local_data.rs index a4a66776..979ed09e 100644 --- a/src/local_data.rs +++ b/src/local_data.rs @@ -134,7 +134,9 @@ pub fn acquire_local_data_lock(state_dir: &Path) -> SnipResult { let lock_path = state_dir.join("local-data.lock"); let nonce = uuid::Uuid::new_v4().to_string(); - let now_ms = chrono::Utc::now().timestamp_millis(); + let now_ms = (time::OffsetDateTime::now_utc() + .unix_timestamp_nanos() + .div_euclid(1_000_000)) as i64; let identity = ProcessIdentity::current(); let info = LocalDataLockInfo { diff --git a/src/sync.rs b/src/sync.rs index f8145dd1..eb5a0e4a 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -27,6 +27,15 @@ use snip_proto::{ use std::sync::atomic::{AtomicU32, Ordering}; use std::time::Duration; use tonic::Code; + +/// Test-only: seal a version-2 payload bound to a snippet id. +/// +/// Re-exported so integration tests can build a mixed-version library without +/// a production writer for version 2. Compiled out unless `test-support` is +/// enabled, and never part of the supported API. +#[cfg(any(test, feature = "test-support"))] +#[doc(hidden)] +pub use crate::encryption::seal_v2_for_test; use tonic::transport::{Channel, ClientTlsConfig, Endpoint, Uri}; use zeroize::Zeroizing; @@ -1267,7 +1276,7 @@ impl SyncClient { Ok(Library { id: response.library_id, name: name_str, - created_at: chrono::Utc::now().timestamp(), + created_at: time::OffsetDateTime::now_utc().unix_timestamp(), snippet_count: 0, }) } else { @@ -1619,6 +1628,11 @@ fn encrypt_snippets_with( } /// Decrypts a snippet's encrypted fields received from the sync server. +/// +/// The snippet id is passed into the cipher because payload version 2 +/// authenticates it as associated data: a ciphertext moved to a different row +/// fails the tag check instead of decrypting into the wrong snippet. Version 0 +/// and 1 payloads ignore it. pub fn decrypt_snippet( api_key: &str, snippet: &crate::proto::Snippet, @@ -1627,7 +1641,7 @@ pub fn decrypt_snippet( return Ok(snippet.clone()); } - let decrypted = encryption::decrypt(api_key, &snippet.command)?; + let decrypted = encryption::decrypt_for_snippet(api_key, &snippet.command, &snippet.id)?; let data: EncryptedSnippetData = serde_json::from_str(&decrypted).map_err(|e| { SnipError::sync_failure( @@ -2864,7 +2878,7 @@ mod tests { // Seed the server with some snippets via a normal sync. let mut setup_client = build_sync_client(&server_url, &api_key).await; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let seed_snippets: Vec = (0..5) .map(|i| crate::proto::Snippet { id: format!("remote-{i}"), @@ -3091,7 +3105,7 @@ mod tests { .expect("register should succeed"); let mut client = build_sync_client(&server_url, &api_key).await; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let local_snippets: Vec = (0..3) .map(|index| crate::proto::Snippet { id: format!("shared-{index}"), diff --git a/src/sync_commands.rs b/src/sync_commands.rs index 2c73c14f..26491afa 100644 --- a/src/sync_commands.rs +++ b/src/sync_commands.rs @@ -122,7 +122,9 @@ fn handle_library_not_found( .map(|lib| lib.library_id.clone()) .unwrap_or_default(), server_library_id: None, - created_at_unix_ms: chrono::Utc::now().timestamp_millis(), + created_at_unix_ms: (time::OffsetDateTime::now_utc() + .unix_timestamp_nanos() + .div_euclid(1_000_000)) as i64, phase: RecoveryPhase::Creating, }, Err(error) => { diff --git a/src/transaction.rs b/src/transaction.rs index 43323338..1abcec1d 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -962,7 +962,9 @@ pub fn acquire_transaction_lock(state_dir: &Path, operation: &str) -> SnipResult let lock_path = state_dir.join("transaction.lock"); let nonce = uuid::Uuid::new_v4().to_string(); - let now_ms = chrono::Utc::now().timestamp_millis(); + let now_ms = (time::OffsetDateTime::now_utc() + .unix_timestamp_nanos() + .div_euclid(1_000_000)) as i64; let identity = current_process_identity(); let info = TransactionLockInfo { @@ -1007,7 +1009,9 @@ pub fn begin_transaction( ) -> SnipResult { create_private_dir(state_dir)?; - let now_ms = chrono::Utc::now().timestamp_millis(); + let now_ms = (time::OffsetDateTime::now_utc() + .unix_timestamp_nanos() + .div_euclid(1_000_000)) as i64; let staged_files: Vec = affected_files .iter() diff --git a/src/usage.rs b/src/usage.rs index 3eded718..92b48721 100644 --- a/src/usage.rs +++ b/src/usage.rs @@ -81,7 +81,7 @@ impl UsageIndex { /// Unix timestamp. If no entry exists for `snippet_id` a new one /// is created. pub fn record_use(&mut self, snippet_id: &str) { - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); if let Some(entry) = self.entries.iter_mut().find(|e| e.id == snippet_id) { entry.use_count = entry.use_count.saturating_add(1); entry.last_used_at = Some(now); @@ -197,9 +197,9 @@ mod tests { #[test] fn record_use_sets_timestamp() { let mut idx = UsageIndex::default(); - let before = chrono::Utc::now().timestamp(); + let before = time::OffsetDateTime::now_utc().unix_timestamp(); idx.record_use("abc-123"); - let after = chrono::Utc::now().timestamp(); + let after = time::OffsetDateTime::now_utc().unix_timestamp(); let usage = idx.get_usage("abc-123"); assert!(usage.last_used_at.is_some()); diff --git a/tests/architecture.rs b/tests/architecture.rs index fd6cc645..3f5a63f5 100644 --- a/tests/architecture.rs +++ b/tests/architecture.rs @@ -910,3 +910,117 @@ fn diagnostic_modules_reject_free_form_code_string_fields() { violations.join("\n") ); } + +// --- Published security claims --------------------------------------------- +// +// `SECURITY.md` and `docs/THREAT_MODEL.md` are the operator-facing contract for +// what the sync encryption actually guarantees. Two sentences in them were +// false in opposite directions and are pinned here so they cannot come back: +// +// * "a compromised server cannot read snippet content" — the client sends the +// API key as a bearer token on every request, so a server (or a proxy, or a +// request log) that observes it can derive the same key. The protection is +// transport confidentiality and at-rest obfuscation, not server-blindness. +// * "It cannot forge content: the GCM tag rejects it" — a party that holds the +// key can seal any plaintext. The tag rejects forgery only by parties +// without the key. +// +// These are deliberately exact-string checks: the guard covers these two +// historical defects, not general prose quality. +const FORBIDDEN_SECURITY_CLAIMS: &[&str] = + &["cannot read snippet content", "It cannot forge content"]; + +/// The body of one level-two Markdown section, without its heading line. +fn markdown_section<'a>(text: &'a str, heading: &str) -> &'a str { + let Some(start) = text.find(heading) else { + return ""; + }; + let rest = &text[start + heading.len()..]; + match rest.find("\n## ") { + Some(end) => &rest[..end], + None => rest, + } +} + +/// The retracted claims that still appear in `text`. +fn forbidden_security_claims(text: &str) -> Vec<&'static str> { + FORBIDDEN_SECURITY_CLAIMS + .iter() + .copied() + .filter(|claim| text.contains(claim)) + .collect() +} + +#[test] +fn published_security_claims_match_the_implementation() { + let security = include_str!("../SECURITY.md"); + let threat_model = include_str!("../docs/THREAT_MODEL.md"); + + let mut violations = Vec::new(); + + for claim in forbidden_security_claims(security) { + violations.push(format!( + "SECURITY.md contains the retracted claim {claim:?}; the bearer key \ + lets the server derive the encryption key" + )); + } + for claim in forbidden_security_claims(threat_model) { + violations.push(format!( + "docs/THREAT_MODEL.md contains the retracted claim {claim:?}; a key \ + holder can forge valid ciphertext" + )); + } + + // Removing the false sentence is not enough: the correction is the point. + if !security.contains("not server-blindness") { + violations.push( + "SECURITY.md must state that the design provides transport \ + confidentiality, not server-blindness" + .to_string(), + ); + } + + // A support table that omits the shipped version tells users an unsupported + // release is supported (or vice versa). + let version = env!("CARGO_PKG_VERSION"); + let major_minor = version.split('.').take(2).collect::>().join("."); + let supported = markdown_section(security, "## Supported Versions"); + if supported.is_empty() { + violations.push("SECURITY.md has no '## Supported Versions' section".to_string()); + } else if !supported.contains(&format!("{major_minor}.x")) { + violations.push(format!( + "SECURITY.md § Supported Versions does not list {major_minor}.x, but \ + Cargo.toml is {version}" + )); + } + + assert!( + violations.is_empty(), + "published security claims do not match the implementation:\n{}", + violations.join("\n") + ); +} + +#[test] +fn forbidden_security_claim_detector_reports_the_retracted_sentences() { + // A guard that cannot fail proves nothing: exercise the detector against the + // exact sentences that were retracted, and against their corrected form. + let false_confidentiality = + "So a compromised server cannot read snippet content, but it can see ids."; + let false_integrity = "It cannot forge content: the GCM tag rejects it."; + + assert_eq!( + forbidden_security_claims(false_confidentiality), + vec!["cannot read snippet content"] + ); + assert_eq!( + forbidden_security_claims(false_integrity), + vec!["It cannot forge content"] + ); + + let corrected = "the guarantee is transport confidentiality, not server-blindness"; + assert!( + forbidden_security_claims(corrected).is_empty(), + "the corrected wording must not trip the detector" + ); +} diff --git a/tests/integration.rs b/tests/integration.rs index 17433f49..01d0d0f1 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -2740,7 +2740,7 @@ fn test_golden_corpus_sync_round_trip_preserves_command() { .expect("SyncClient::create should succeed"); // Push a multiline snippet with trailing newline - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let original_command = "if true; then\n echo yes\nelse\n echo no\nfi\n"; let snippet = snip_proto::Snippet { id: "sync-golden-1".to_string(), diff --git a/tests/snip_sync_lifetime.rs b/tests/snip_sync_lifetime.rs index c3435b01..d23a5c16 100644 --- a/tests/snip_sync_lifetime.rs +++ b/tests/snip_sync_lifetime.rs @@ -139,6 +139,24 @@ fn start_server_on_ports_with_http_config( http_port: u16, expose_metrics: bool, allow_all_origins: bool, +) -> (std::process::Child, SocketAddr) { + start_server_on_ports_with_http_config_and_budget( + tmp, + grpc_port, + http_port, + expose_metrics, + allow_all_origins, + None, + ) +} + +fn start_server_on_ports_with_http_config_and_budget( + tmp: &tempfile::TempDir, + grpc_port: u16, + http_port: u16, + expose_metrics: bool, + allow_all_origins: bool, + metrics_auth_failures_per_minute: Option, ) -> (std::process::Child, SocketAddr) { let config_dir = tmp.path().join("config"); let data_dir = tmp.path().join("data"); @@ -182,6 +200,9 @@ fn start_server_on_ports_with_http_config( command.env("METRICS_USERNAME", "user"); command.env("METRICS_PASSWORD", "pass"); } + if let Some(budget) = metrics_auth_failures_per_minute { + command.env("METRICS_AUTH_FAILURES_PER_MINUTE", budget.to_string()); + } let mut child = command.spawn().expect("failed to spawn snip-sync serve"); let _stderr = child.stderr.take().unwrap(); @@ -438,6 +459,73 @@ fn http_metrics_auth_and_cors_preflight_contract() { assert!(status.success(), "server should exit normally: {status:?}"); } +#[test] +fn http_metrics_auth_failures_are_rate_limited() { + let tmp = tempfile::tempdir().unwrap(); + let grpc_port = reserve_port(); + let http_port = reserve_port(); + let (mut child, http_addr) = start_server_on_ports_with_http_config_and_budget( + &tmp, + grpc_port, + http_port, + true, + false, + Some(2), + ); + + let unauthorized = "GET /metrics HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n"; + + // The first failures fit the budget and keep the ordinary 401 challenge. + for attempt in 1..=2 { + let response = http_response(http_addr, unauthorized); + assert!( + response.starts_with("HTTP/1.1 401"), + "attempt {attempt} should be 401: {response}" + ); + assert!( + response + .to_ascii_lowercase() + .contains("www-authenticate: basic realm=\"metrics\""), + "attempt {attempt} should still carry the challenge: {response}" + ); + } + + // The next failure exceeds the failure budget. + let throttled = http_response(http_addr, unauthorized); + assert!( + throttled.starts_with("HTTP/1.1 429"), + "the budget must throttle further guesses: {throttled}" + ); + assert!( + throttled.to_ascii_lowercase().contains("retry-after: 60"), + "a 429 must advertise the window: {throttled}" + ); + assert!( + !throttled.to_ascii_lowercase().contains("www-authenticate"), + "a throttled response must not invite another credential attempt: {throttled}" + ); + assert_security_headers_present(&throttled); + + // Correct credentials never consult the failure budget, so an attacker + // cannot deny the operator their own scrape. + let authorized = http_response( + http_addr, + "GET /metrics HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Basic dXNlcjpwYXNz\r\nConnection: close\r\n\r\n", + ); + assert!( + authorized.starts_with("HTTP/1.1 200"), + "a valid scrape must still succeed after the budget is exhausted: {authorized}" + ); + assert!( + authorized.contains("snip_sync_auth_failures_total"), + "{authorized}" + ); + + stop_server(&mut child); + let status = wait_for_exit(&mut child, Duration::from_secs(15)); + assert!(status.success(), "server should exit normally: {status:?}"); +} + #[test] fn http_allow_all_cors_is_available_for_loopback_server() { let tmp = tempfile::tempdir().unwrap(); diff --git a/tests/sync_integration.rs b/tests/sync_integration.rs index 4e51b5db..39d1d743 100644 --- a/tests/sync_integration.rs +++ b/tests/sync_integration.rs @@ -30,7 +30,7 @@ async fn test_sync_client_sends_bearer_token_in_authorization_metadata() { // Send one snippet through the encrypted sync path. The server // side records the first authenticated request's `authorization` // header into `captured.1`; we assert it after the call completes. - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let snippet = Snippet { id: "integration-snippet-1".to_string(), description: "integration snippet".to_string(), @@ -80,7 +80,7 @@ async fn test_sync_client_round_trip_encrypts_and_decrypts_snippets() { let mut client = build_sync_client(&server_url, &api_key).await; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let original_command = "echo round-trip-works"; let snippet = Snippet { id: "rt-1".to_string(), @@ -129,7 +129,7 @@ async fn test_captured_authorization_metadata_is_first_wins() { let mut client = build_sync_client(&server_url, &api_key).await; // Issue two sync calls back-to-back. - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let make_snippet = |id: &str| Snippet { id: id.to_string(), description: "x".to_string(), @@ -179,7 +179,7 @@ async fn test_sync_accepts_encrypted_payload_near_command_length_limit() { // it will be substantially larger than 1024 bytes (JSON envelope + // AES-GCM tag + salt + nonce + base64 expansion). let plaintext_command = "x".repeat(snip_sync::DEFAULT_MAX_COMMAND_LENGTH); - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let snippet = Snippet { id: "near-limit".to_string(), description: "d".to_string(), @@ -358,7 +358,7 @@ async fn test_a_cursorless_request_bootstraps_the_sequence_watermark() { .create_library("bootstrap") .await .expect("library creation must succeed"); - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let make = |id: &str| Snippet { id: id.to_string(), description: format!("bootstrap {id}"), @@ -410,7 +410,7 @@ async fn test_a_bootstrapped_client_sends_a_non_zero_sequence_cursor() { .create_library("cursor-path") .await .expect("library creation must succeed"); - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let snippet = Snippet { id: "cursor-1".to_string(), description: "cursor snippet".to_string(), @@ -477,7 +477,7 @@ async fn test_a_timestamp_only_request_is_answered_with_no_sequence() { .create_library("timestamp-only") .await .expect("library creation must succeed"); - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let snippet = Snippet { id: "ts-1".to_string(), description: "timestamp snippet".to_string(), @@ -509,3 +509,183 @@ async fn test_a_timestamp_only_request_is_answered_with_no_sequence() { captured.2.abort(); } + +#[cfg(feature = "test-support")] +/// Push raw records through the generated client, bypassing `SyncClient`'s +/// encryption step. This is how an integration test seeds payloads in a +/// version the production write path does not emit. +async fn push_raw_snippets(server_url: &str, api_key: &str, snippets: Vec) { + use snip_proto::PushSnippetsRequest; + use snip_proto::snippet_sync_client::SnippetSyncClient; + + let mut client = SnippetSyncClient::connect(server_url.to_string()) + .await + .expect("raw gRPC client should connect to the loopback server"); + let mut request = tonic::Request::new(PushSnippetsRequest { + api_key: String::new(), + library_id: String::new(), + snippets, + }); + request.metadata_mut().insert( + "authorization", + format!("Bearer {api_key}") + .parse() + .expect("a bearer token is valid metadata"), + ); + let response = client + .push_snippets(request) + .await + .expect("raw push should succeed") + .into_inner(); + assert!(response.success, "raw push failed: {}", response.message); +} + +#[cfg(feature = "test-support")] +/// Build an encrypted proto snippet around an already-sealed payload. +fn sealed_snippet(id: &str, payload: String, now: i64, device_id: &str) -> Snippet { + Snippet { + id: id.to_string(), + description: String::new(), + command: payload, + tags: Vec::new(), + created_at: now, + updated_at: now, + device_id: device_id.to_string(), + deleted: false, + encrypted: true, + } +} + +#[cfg(feature = "test-support")] +/// A library holding one version-1 and one version-2 payload must sync with +/// both rows decrypted and their ids preserved. A version-2 payload moved to a +/// different row must fail its tag check and be skipped, leaving the rest of +/// the library intact. +#[tokio::test(flavor = "multi_thread")] +async fn mixed_v1_and_v2_payloads_sync_and_a_substituted_v2_row_is_skipped() { + let (api_key, device_id, captured) = boot_server_and_register().await; + let server_url = captured.0.clone(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); + + // Version 1: produced by the production write path. + let v1_plaintext = Snippet { + id: "v1-row".to_string(), + description: "version one".to_string(), + command: "echo v1".to_string(), + tags: vec!["v1".to_string()], + created_at: now, + updated_at: now, + device_id: device_id.clone(), + deleted: false, + encrypted: false, + }; + let v1 = snip_it::sync::encrypt_snippet(&api_key, &v1_plaintext) + .expect("v1 encryption should succeed"); + + // Version 2: sealed for its own id, which only a future writer produces. + let salt = [7u8; 16]; + let v2_json = serde_json::json!({ + "description": "version two", + "command": "echo v2", + "tags": ["v2"], + }) + .to_string(); + let v2_payload = + snip_it::sync::seal_v2_for_test(&api_key, &v2_json, "v2-row", &salt).expect("v2 seal"); + let v2 = sealed_snippet("v2-row", v2_payload, now, &device_id); + + // A version-2 payload sealed for `v2-row` but stored under another id: the + // key-blind substitution this binding exists to stop. + let substituted_payload = + snip_it::sync::seal_v2_for_test(&api_key, &v2_json, "v2-row", &salt).expect("v2 seal"); + let substituted = sealed_snippet("v2-substituted", substituted_payload, now, &device_id); + + push_raw_snippets(&server_url, &api_key, vec![v1, v2, substituted.clone()]).await; + + let mut client = build_sync_client(&server_url, &api_key).await; + let response = client + .sync_encrypted(vec![], 0, "") + .await + .expect("pull should succeed"); + + // The two authentic rows land with their ids and content preserved. + let v1_returned = response + .snippets + .iter() + .find(|s| s.id == "v1-row") + .expect("the version-1 row should sync"); + assert_eq!(v1_returned.command, "echo v1"); + assert_eq!(v1_returned.description, "version one"); + + let v2_returned = response + .snippets + .iter() + .find(|s| s.id == "v2-row") + .expect("the version-2 row should sync"); + assert_eq!( + v2_returned.command, "echo v2", + "the id-bound payload must decrypt under its own id" + ); + assert_eq!(v2_returned.description, "version two"); + + // The substituted row fails the tag check and is reported as skipped + // rather than silently accepted under the wrong id. + assert!( + response.skipped_ids.iter().any(|id| id == "v2-substituted"), + "a substituted v2 payload must be skipped, got skipped_ids={:?}", + response.skipped_ids + ); + assert!( + !response.snippets.iter().any(|s| s.id == "v2-substituted"), + "a substituted v2 payload must not appear as accepted content" + ); + assert!( + response.success, + "one bad row must not abort the rest of the library: {}", + response.message + ); + + captured.2.abort(); +} + +#[cfg(feature = "test-support")] +/// A library containing only version-1 payloads syncs exactly as before the +/// version-2 read path existed. +#[tokio::test(flavor = "multi_thread")] +async fn v1_only_library_still_syncs_unchanged() { + let (api_key, device_id, captured) = boot_server_and_register().await; + let server_url = captured.0.clone(); + let mut client = build_sync_client(&server_url, &api_key).await; + + let now = time::OffsetDateTime::now_utc().unix_timestamp(); + let snippet = Snippet { + id: "v1-only".to_string(), + description: "unchanged".to_string(), + command: "echo unchanged".to_string(), + tags: vec![], + created_at: now, + updated_at: now, + device_id, + deleted: false, + encrypted: false, + }; + + let response = client + .sync_encrypted(vec![snippet], 0, "") + .await + .expect("v1-only sync should succeed"); + assert!(response.success); + assert!( + response.skipped_ids.is_empty(), + "{:?}", + response.skipped_ids + ); + let returned = response + .snippets + .iter() + .find(|s| s.id == "v1-only") + .expect("the row should round-trip"); + assert_eq!(returned.command, "echo unchanged"); + + captured.2.abort(); +} diff --git a/tests/sync_multibatch.rs b/tests/sync_multibatch.rs index cc764ffa..1b17a75a 100644 --- a/tests/sync_multibatch.rs +++ b/tests/sync_multibatch.rs @@ -52,6 +52,8 @@ async fn build_file_service(db_path: &str) -> SnipSyncService { request_timeout_secs: 30, grpc_max_message_size: 4 * 1024 * 1024, rate_limit_per_minute: 120, + register_per_minute: snip_sync::DEFAULT_REGISTER_PER_MINUTE, + metrics_auth_failures_per_minute: snip_sync::DEFAULT_METRICS_AUTH_FAILURES_PER_MINUTE, trusted_proxies: vec![], metrics_username: None, metrics_password: None, @@ -86,7 +88,7 @@ async fn test_encrypted_sync_uploads_all_snippets_in_multiple_batches() { let mut client = build_sync_client(&server_url, &api_key).await; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let snippets: Vec = (0..MULTI_BATCH_COUNT) .map(|i| Snippet { id: format!("mb-{i:04}", i = i), @@ -174,7 +176,7 @@ async fn test_sync_convergence_after_partial_upload() { let mut client = build_sync_client(&server_url, &api_key).await; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let midpoint = MULTI_BATCH_COUNT / 2; let small_batch: Vec = (0..midpoint) @@ -263,7 +265,7 @@ async fn test_partial_failure_convergence() { let mut client = build_sync_client(&server_url, &api_key).await; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let snippets: Vec = (0..MULTI_BATCH_COUNT) .map(|i| Snippet { id: format!("pf-{i:04}", i = i), @@ -438,7 +440,7 @@ async fn test_zero_batch_pull_only_seeded_remote() { // Seed the server with some snippets via a normal sync. let mut setup_client = build_sync_client(&server_url, &api_key).await; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let seed_snippets: Vec = (0..10) .map(|i| Snippet { id: format!("seed-{i:02}"), @@ -499,7 +501,7 @@ async fn test_zero_batch_pagination() { // Seed 20 snippets via a normal sync (small enough to fit in one batch). let mut setup_client = build_sync_client(&server_url, &api_key).await; - let now = chrono::Utc::now().timestamp(); + let now = time::OffsetDateTime::now_utc().unix_timestamp(); let seed_snippets: Vec = (0..20) .map(|i| Snippet { id: format!("page-{i:02}"),