diff --git a/.github/workflows/npm.yml b/.github/workflows/npm.yml index 6368dd0..a8d13cd 100644 --- a/.github/workflows/npm.yml +++ b/.github/workflows/npm.yml @@ -33,10 +33,24 @@ jobs: RELEASE_TAG: ${{ github.event.release.tag_name || inputs.release_tag }} GH_TOKEN: ${{ github.token }} steps: + - name: Validate release tag + id: release + shell: bash + run: | + if [[ ! "$RELEASE_TAG" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$ ]]; then + echo "Invalid Cadder release tag: $RELEASE_TAG" >&2 + exit 1 + fi + echo "version=${RELEASE_TAG#v}" >> "$GITHUB_OUTPUT" - name: Check out repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.0.3 with: persist-credentials: false + ref: ${{ env.RELEASE_TAG }} + - name: Resolve release commit + id: source + shell: bash + run: echo "commit=$(git rev-parse HEAD^{commit})" >> "$GITHUB_OUTPUT" - name: Set up Node.js uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0 with: @@ -50,15 +64,6 @@ jobs: test "$(node --version)" = "v24.18.0" nub --version | grep -Fx "v0.7.5" test "$(npm --version)" = "12.0.2" - - name: Validate release tag - id: release - shell: bash - run: | - if [[ ! "$RELEASE_TAG" =~ ^v([0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?)$ ]]; then - echo "Invalid Cadder release tag: $RELEASE_TAG" >&2 - exit 1 - fi - echo "version=${BASH_REMATCH[1]}" >> "$GITHUB_OUTPUT" - name: Install package workspace working-directory: npm run: nub ci @@ -73,6 +78,9 @@ jobs: --assets "$RUNNER_TEMP/cadder-assets" --output "$RUNNER_TEMP/cadder-npm-stage" --version "${{ steps.release.outputs.version }}" + --source-ref "refs/tags/$RELEASE_TAG" + --source-digest "${{ steps.source.outputs.commit }}" + --signer-workflow "$GITHUB_REPOSITORY/.github/workflows/release.yml" - name: Pack deterministic npm tarballs run: >- node npm/scripts/pack-release.js diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ee5d221..70e0438 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,7 +15,7 @@ name: Release permissions: - "contents": "write" + "contents": "read" # This task will run whenever you push a git tag that looks like a version # like "1.0.0", "v0.1.0-prerelease.1", "my-app/0.1.0", "releases/v1.0.0", etc. @@ -50,11 +50,10 @@ jobs: runs-on: "ubuntu-22.04" outputs: val: ${{ steps.plan.outputs.manifest }} - tag: ${{ !github.event.pull_request && github.ref_name || '' }} - tag-flag: ${{ !github.event.pull_request && format('--tag={0}', github.ref_name) || '' }} + tag: ${{ steps.plan.outputs.tag }} publishing: ${{ !github.event.pull_request }} env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_TAG: ${{ !github.event.pull_request && github.ref_name || '' }} steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 with: @@ -64,7 +63,7 @@ jobs: # we specify bash to get pipefail; it guards against the `curl` command # failing. otherwise `sh` won't catch that `curl` returned non-0 shell: bash - run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.32.0/cargo-dist-installer.sh | sh" + run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.33.0/cargo-dist-installer.sh | sh" - name: Cache dist uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a with: @@ -76,10 +75,20 @@ jobs: # (PRs run on the *source* but secrets are usually on the *target* -- that's *good* # but also really annoying to build CI around when it needs secrets to work right.) - id: plan + shell: bash run: | - dist ${{ (!github.event.pull_request && format('host --steps=create --tag={0}', github.ref_name)) || 'plan' }} --output-format=json > plan-dist-manifest.json + if [[ -n "$RELEASE_TAG" ]]; then + if [[ ! "$RELEASE_TAG" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$ ]]; then + echo "Invalid Cadder release tag: $RELEASE_TAG" >&2 + exit 1 + fi + dist host --allow-dirty --steps=create --tag "$RELEASE_TAG" --output-format=json > plan-dist-manifest.json + else + dist plan --allow-dirty --output-format=json > plan-dist-manifest.json + fi echo "dist ran successfully" cat plan-dist-manifest.json + echo "tag=$RELEASE_TAG" >> "$GITHUB_OUTPUT" echo "manifest=$(jq -c "." plan-dist-manifest.json)" >> "$GITHUB_OUTPUT" - name: "Upload dist-manifest.json" uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a @@ -110,7 +119,7 @@ jobs: runs-on: ${{ matrix.runner }} container: ${{ matrix.container && matrix.container.image || null }} env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_TAG: ${{ needs.plan.outputs.tag }} BUILD_MANIFEST_NAME: target/distrib/${{ join(matrix.targets, '-') }}-dist-manifest.json steps: - name: enable windows longpaths @@ -144,9 +153,12 @@ jobs: run: | ${{ matrix.packages_install }} - name: Build artifacts + shell: bash run: | # Actually do builds and make zips and whatnot - dist build ${{ needs.plan.outputs.tag-flag }} --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json + tag_args=() + if [[ -n "$RELEASE_TAG" ]]; then tag_args=(--tag "$RELEASE_TAG"); fi + dist build --allow-dirty "${tag_args[@]}" --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json echo "dist ran successfully" - id: cargo-dist name: Post-build @@ -176,7 +188,7 @@ jobs: - build-local-artifacts runs-on: "ubuntu-22.04" env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_TAG: ${{ needs.plan.outputs.tag }} BUILD_MANIFEST_NAME: target/distrib/global-dist-manifest.json steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 @@ -199,7 +211,9 @@ jobs: - id: cargo-dist shell: bash run: | - dist build ${{ needs.plan.outputs.tag-flag }} --output-format=json "--artifacts=global" > dist-manifest.json + tag_args=() + if [[ -n "$RELEASE_TAG" ]]; then tag_args=(--tag "$RELEASE_TAG"); fi + dist build --allow-dirty "${tag_args[@]}" --output-format=json "--artifacts=global" > dist-manifest.json echo "dist ran successfully" # Parse out what we just built and upload it to scratch storage @@ -224,7 +238,7 @@ jobs: # Only run if we're "publishing", and only if plan, local and global didn't fail (skipped is fine) if: ${{ always() && needs.plan.result == 'success' && needs.plan.outputs.publishing == 'true' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') }} env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_TAG: ${{ needs.plan.outputs.tag }} runs-on: "ubuntu-22.04" outputs: val: ${{ steps.host.outputs.manifest }} @@ -250,7 +264,7 @@ jobs: - id: host shell: bash run: | - dist host ${{ needs.plan.outputs.tag-flag }} --steps=upload --steps=release --output-format=json > dist-manifest.json + dist host --allow-dirty --tag "$RELEASE_TAG" --steps=upload --steps=release --output-format=json > dist-manifest.json echo "artifacts uploaded and released successfully" cat dist-manifest.json echo "manifest=$(jq -c "." dist-manifest.json)" >> "$GITHUB_OUTPUT" @@ -323,8 +337,9 @@ jobs: ANNOUNCEMENT_TITLE: "${{ fromJson(needs.host.outputs.val).announcement_title }}" ANNOUNCEMENT_BODY: "${{ fromJson(needs.host.outputs.val).announcement_github_body }}" RELEASE_COMMIT: "${{ github.sha }}" + RELEASE_TAG: "${{ needs.plan.outputs.tag }}" run: | # Write and read notes from a file to avoid quoting breaking things echo "$ANNOUNCEMENT_BODY" > $RUNNER_TEMP/notes.txt - gh release create "${{ needs.plan.outputs.tag }}" --target "$RELEASE_COMMIT" $PRERELEASE_FLAG --title "$ANNOUNCEMENT_TITLE" --notes-file "$RUNNER_TEMP/notes.txt" artifacts/* + gh release create "$RELEASE_TAG" --target "$RELEASE_COMMIT" $PRERELEASE_FLAG --title "$ANNOUNCEMENT_TITLE" --notes-file "$RUNNER_TEMP/notes.txt" artifacts/* diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d1c9c9..056aaf6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 +## [1.0.1] - 2026-10-03 + +### Fixed + + +#### Keep managed development routes local and isolated + +Cadder now binds its shared HTTP and HTTPS listeners only to loopback, keeps every project behind its active host names, redacts the documented credential forms from retained logs, and renders diagnostic text without active terminal control sequences. + ## [1.0.0] - 2026-09-15 ### Added @@ -63,6 +72,7 @@ Profiles, autostart, history, export, continuous log tailing and watching, machi Cadder 1.0 does not ship installers, Homebrew or Scoop packages, crates.io packages, Authenticode signatures, or macOS notarization. -[Unreleased]: https://github.com/MrMaxie/cadder/compare/v1.0.0...HEAD +[Unreleased]: https://github.com/MrMaxie/cadder/compare/v1.0.1...HEAD +[1.0.1]: https://github.com/MrMaxie/cadder/compare/v1.0.0...v1.0.1 [1.0.0]: https://github.com/MrMaxie/cadder/compare/v0.8.0...v1.0.0 diff --git a/Cargo.lock b/Cargo.lock index b387262..4afedce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -250,12 +250,6 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" -[[package]] -name = "base64" -version = "0.23.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" - [[package]] name = "bindgen" version = "0.72.1" @@ -328,7 +322,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee04c4c84f1f811b017f2fbb7dd8815c976e7ca98593de9c1e2afad0f636bff4" dependencies = [ "async-stream", - "base64 0.22.1", + "base64", "bitflags 2.13.0", "bollard-buildkit-proto", "bollard-stubs", @@ -385,7 +379,7 @@ version = "1.52.1-rc.29.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f0a8ca8799131c1837d1282c3f81f31e76ceb0ce426e04a7fe1ccee3287c066" dependencies = [ - "base64 0.22.1", + "base64", "bollard-buildkit-proto", "bytes", "prost", @@ -436,7 +430,7 @@ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" [[package]] name = "cadder" -version = "1.0.0" +version = "1.0.1" dependencies = [ "anyhow", "cadder-api", @@ -461,7 +455,7 @@ dependencies = [ [[package]] name = "cadder-api" -version = "1.0.0" +version = "1.0.1" dependencies = [ "anyhow", "cadder-daemon", @@ -476,7 +470,7 @@ dependencies = [ [[package]] name = "cadder-client" -version = "1.0.0" +version = "1.0.1" dependencies = [ "cadder-api", "cadder-ipc", @@ -496,7 +490,7 @@ dependencies = [ [[package]] name = "cadder-daemon" -version = "1.0.0" +version = "1.0.1" dependencies = [ "anyhow", "backon", @@ -515,7 +509,7 @@ dependencies = [ "is_elevated", "libc", "process-wrap", - "reqwest", + "regex", "same-file", "semver", "serde", @@ -528,7 +522,6 @@ dependencies = [ "tokio-rusqlite", "tokio-util", "tracing-subscriber", - "which", "widestring", "windows", "windows-sys 0.61.2", @@ -536,7 +529,7 @@ dependencies = [ [[package]] name = "cadder-ipc" -version = "1.0.0" +version = "1.0.1" dependencies = [ "chrono", "idna", @@ -549,7 +542,7 @@ dependencies = [ [[package]] name = "cadder-shim" -version = "1.0.0" +version = "1.0.1" dependencies = [ "anyhow", "cadder-api", @@ -1001,7 +994,7 @@ version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29547a1dc60885a552306986316bc9701ba120c1a8db6769fa68691529ad373d" dependencies = [ - "base64 0.22.1", + "base64", "serde", "serde_json", ] @@ -1571,16 +1564,13 @@ version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ - "base64 0.22.1", "bytes", "futures-channel", "futures-util", "http", "http-body", "hyper", - "ipnet", "libc", - "percent-encoding", "pin-project-lite", "socket2", "tokio", @@ -1814,12 +1804,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "ipnet" -version = "2.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" - [[package]] name = "is_elevated" version = "0.1.2" @@ -2957,35 +2941,6 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" -[[package]] -name = "reqwest" -version = "0.13.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" -dependencies = [ - "base64 0.23.1", - "bytes", - "futures-core", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "sync_wrapper", - "tokio", - "tower", - "tower-http", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - [[package]] name = "ring" version = "0.17.14" @@ -3311,7 +3266,7 @@ version = "3.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c" dependencies = [ - "base64 0.22.1", + "base64", "bs58", "chrono", "hex", @@ -3557,9 +3512,6 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" -dependencies = [ - "futures-core", -] [[package]] name = "synstructure" @@ -3593,7 +3545,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.2", "once_cell", "rustix", "windows-sys 0.61.2", @@ -3640,7 +3592,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4676b37242ccbd1aabf56edb093a4827dc49086c0ffd764a5705899e0f35f8f7" dependencies = [ "anyhow", - "base64 0.22.1", + "base64", "bitflags 2.13.0", "fancy-regex", "filedescriptor", @@ -3936,7 +3888,7 @@ checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" dependencies = [ "async-trait", "axum", - "base64 0.22.1", + "base64", "bytes", "h2", "http", @@ -3987,24 +3939,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "tower-http" -version = "0.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" -dependencies = [ - "bitflags 2.13.0", - "bytes", - "futures-util", - "http", - "http-body", - "pin-project-lite", - "tower", - "tower-layer", - "tower-service", - "url", -] - [[package]] name = "tower-layer" version = "0.3.3" @@ -4158,7 +4092,7 @@ version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0" dependencies = [ - "base64 0.22.1", + "base64", "log", "percent-encoding", "rustls", @@ -4173,7 +4107,7 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c" dependencies = [ - "base64 0.22.1", + "base64", "http", "httparse", "log", @@ -4305,16 +4239,6 @@ dependencies = [ "wasm-bindgen-shared", ] -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54568702fabf5d4849ce2b90fadfa64168a097eaf4b351ce9df8b687a0086aaf" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - [[package]] name = "wasm-bindgen-macro" version = "0.2.123" @@ -4381,16 +4305,6 @@ dependencies = [ "semver", ] -[[package]] -name = "web-sys" -version = "0.3.100" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e0871acf327f283dc6da28a1696cdc64fb355ba9f935d052021fa77f35cce69" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - [[package]] name = "web-time" version = "1.1.0" @@ -4473,15 +4387,6 @@ dependencies = [ "wezterm-dynamic", ] -[[package]] -name = "which" -version = "8.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f3ef584124b911bcc3875c2f1472e80f24361ceb789bd1c62b3e9a3df9ff43c" -dependencies = [ - "libc", -] - [[package]] name = "widestring" version = "1.2.1" diff --git a/Cargo.toml b/Cargo.toml index 931aafc..af04461 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,7 +36,7 @@ members = [ resolver = "3" [workspace.package] -version = "1.0.0" +version = "1.0.1" edition = "2024" license = "Apache-2.0" repository = "https://github.com/MrMaxie/cadder" @@ -61,9 +61,9 @@ lto = "thin" [dependencies] anyhow = "=1.0.104" -cadder-api = { version = "1.0.0", path = "crates/cadder-api" } -cadder-daemon = { version = "1.0.0", path = "crates/cadder-daemon" } -cadder-ipc = { version = "1.0.0", path = "crates/cadder-ipc" } +cadder-api = { version = "1.0.1", path = "crates/cadder-api" } +cadder-daemon = { version = "1.0.1", path = "crates/cadder-daemon" } +cadder-ipc = { version = "1.0.1", path = "crates/cadder-ipc" } chrono = { version = "=0.4.45", features = ["serde"] } clap = { version = "=4.6.1", features = ["derive"] } color-eyre = "=0.6.5" @@ -85,7 +85,7 @@ wait-timeout = "=0.2.1" # Config for 'dist' [workspace.metadata.dist] # The preferred dist version to use in CI (Cargo.toml SemVer syntax) -cargo-dist-version = "0.32.0" +cargo-dist-version = "0.33.0" # CI backends to support ci = "github" # The installers to generate for each app diff --git a/crates/cadder-api/Cargo.toml b/crates/cadder-api/Cargo.toml index 415fbcb..b94155a 100644 --- a/crates/cadder-api/Cargo.toml +++ b/crates/cadder-api/Cargo.toml @@ -7,8 +7,8 @@ repository.workspace = true [dependencies] anyhow = "=1.0.104" -cadder-daemon = { version = "1.0.0", path = "../cadder-daemon" } -cadder-ipc = { version = "1.0.0", path = "../cadder-ipc" } +cadder-daemon = { version = "1.0.1", path = "../cadder-daemon" } +cadder-ipc = { version = "1.0.1", path = "../cadder-ipc" } chrono = { version = "=0.4.45", features = ["serde"] } serde = { version = "=1.0.229", features = ["derive"] } thiserror = "=2.0.17" diff --git a/crates/cadder-client/Cargo.toml b/crates/cadder-client/Cargo.toml index 26e4de3..11619d0 100644 --- a/crates/cadder-client/Cargo.toml +++ b/crates/cadder-client/Cargo.toml @@ -13,8 +13,8 @@ name = "cadder-client" path = "src/main.rs" [dependencies] -cadder-api = { version = "1.0.0", path = "../cadder-api" } -cadder-ipc = { version = "1.0.0", path = "../cadder-ipc" } +cadder-api = { version = "1.0.1", path = "../cadder-api" } +cadder-ipc = { version = "1.0.1", path = "../cadder-ipc" } clap = { version = "=4.6.1", features = ["derive"] } color-eyre = "=0.6.5" crossterm = { version = "=0.29.0", features = ["event-stream"] } diff --git a/crates/cadder-client/src/cli/output.rs b/crates/cadder-client/src/cli/output.rs index 1bcaedf..27a7948 100644 --- a/crates/cadder-client/src/cli/output.rs +++ b/crates/cadder-client/src/cli/output.rs @@ -230,7 +230,7 @@ pub(crate) fn diagnostics(diagnostics: &DiagnosticsView) { .operation .clone() .unwrap_or_else(|| "-".to_string()), - diagnostic.message.clone(), + terminal_safe(&diagnostic.message), ]); } println!("{table}"); @@ -254,7 +254,7 @@ pub(crate) fn diagnostics(diagnostics: &DiagnosticsView) { } else { diagnostic.source_config_paths.join(", ") }, - diagnostic.message.clone(), + terminal_safe(&diagnostic.message), ]); } println!("{table}"); @@ -281,7 +281,7 @@ pub(crate) fn logs(logs: &LogsView) { entry.sequence_number.to_string(), entry.timestamp_utc.to_rfc3339(), debug_label(entry.severity), - entry.raw_message.clone(), + terminal_safe(&entry.raw_message), ]); } println!("{table}"); @@ -357,6 +357,47 @@ fn table(header: [&str; N]) -> Table { table } +fn terminal_safe(input: &str) -> String { + let mut output = String::with_capacity(input.len()); + let mut chars = input.chars().peekable(); + while let Some(character) = chars.next() { + if character == '\u{1b}' { + match chars.peek().copied() { + Some('[') => { + chars.next(); + for sequence_character in chars.by_ref() { + if ('\u{40}'..='\u{7e}').contains(&sequence_character) { + break; + } + } + } + Some(']') => { + chars.next(); + while let Some(sequence_character) = chars.next() { + if sequence_character == '\u{7}' { + break; + } + if sequence_character == '\u{1b}' && chars.peek() == Some(&'\\') { + chars.next(); + break; + } + } + } + Some(_) => { + chars.next(); + } + None => {} + } + continue; + } + if character <= '\u{1f}' || ('\u{7f}'..='\u{9f}').contains(&character) { + continue; + } + output.push(character); + } + output +} + fn activation_label(state: ActivationState) -> &'static str { match state { ActivationState::Unknown => "unknown", @@ -644,6 +685,19 @@ mod tests { }); } + #[test] + fn terminal_safe_removes_ansi_and_control_sequences() { + assert_eq!( + terminal_safe("safe\u{1b}[31mred\u{1b}[0m\u{7}text\u{85}done"), + "saferedtextdone" + ); + assert_eq!( + terminal_safe("before\u{1b}]0;changed title\u{7}after"), + "beforeafter" + ); + assert_eq!(terminal_safe("ordinary Zażółć"), "ordinary Zażółć"); + } + #[test] fn state_labels_cover_every_activation_state() { assert_eq!(activation_label(ActivationState::Unknown), "unknown"); diff --git a/crates/cadder-daemon/Cargo.toml b/crates/cadder-daemon/Cargo.toml index 9667458..3686b4f 100644 --- a/crates/cadder-daemon/Cargo.toml +++ b/crates/cadder-daemon/Cargo.toml @@ -32,7 +32,7 @@ required-features = ["docker-e2e"] anyhow = "=1.0.104" backon = { version = "=1.6.0", default-features = false, features = ["std", "tokio-sleep"] } bytes = "=1.11.1" -cadder-ipc = { version = "1.0.0", path = "../cadder-ipc" } +cadder-ipc = { version = "1.0.1", path = "../cadder-ipc" } caddyfile-rs = "=0.1.0" chrono = { version = "=0.4.45", features = ["serde"] } clap = { version = "=4.6.1", features = ["derive"] } @@ -44,6 +44,7 @@ getrandom = "=0.4.2" hex = "=0.4.3" interprocess = { version = "=2.4.2", features = ["tokio"] } process-wrap = { version = "=9.1.0", default-features = false, features = ["tokio1", "process-group", "kill-on-drop", "job-object", "creation-flags"] } +regex = "=1.12.4" same-file = "=1.0.6" semver = "=1.0.28" serde = { version = "=1.0.229", features = ["derive"] } @@ -54,10 +55,8 @@ tokio = { version = "=1.52.3", features = ["full"] } tokio-rusqlite = { version = "=0.8.0", features = ["bundled"] } tokio-util = { version = "=0.7.18", features = ["codec", "rt"] } tracing-subscriber = "=0.3.23" -which = "=8.0.5" [dev-dependencies] -reqwest = { version = "=0.13.5", default-features = false } tempfile = "=3.27.0" testcontainers = "=0.27.3" diff --git a/crates/cadder-daemon/src/caddy/configuration.rs b/crates/cadder-daemon/src/caddy/configuration.rs index 41bc529..05be2f7 100644 --- a/crates/cadder-daemon/src/caddy/configuration.rs +++ b/crates/cadder-daemon/src/caddy/configuration.rs @@ -1,9 +1,12 @@ use super::*; +const MAX_CADDY_ADAPT_OUTPUT_BYTES: usize = 32 * 1024 * 1024; + #[derive(Debug, Clone)] pub struct CaddyConfigAdapter { resolver: RealCaddyResolver, command_timeout: Duration, + max_output_bytes: usize, } #[derive(Debug, Clone)] @@ -18,6 +21,7 @@ impl CaddyConfigAdapter { Self { resolver, command_timeout: Duration::from_secs(30), + max_output_bytes: MAX_CADDY_ADAPT_OUTPUT_BYTES, } } @@ -25,6 +29,20 @@ impl CaddyConfigAdapter { Self { resolver, command_timeout, + max_output_bytes: MAX_CADDY_ADAPT_OUTPUT_BYTES, + } + } + + #[cfg(test)] + pub(crate) fn with_command_limits( + resolver: RealCaddyResolver, + command_timeout: Duration, + max_output_bytes: usize, + ) -> Self { + Self { + resolver, + command_timeout, + max_output_bytes, } } @@ -48,7 +66,7 @@ impl CaddyConfigAdapter { routes: Vec::new(), diagnostics: vec![ConfigDiagnostic { code: "adapt-failed".to_string(), - message: error.to_string(), + message: format!("{error:#}"), domain_key: None, source_config_paths: Vec::new(), }], @@ -82,7 +100,7 @@ impl CaddyConfigAdapter { }) .await?; let output = child - .wait_for_output(self.command_timeout, "caddy adapt") + .wait_for_bounded_output(self.command_timeout, "caddy adapt", self.max_output_bytes) .await?; if !output.status.success() { @@ -466,20 +484,26 @@ pub(super) fn compose_config( } tls_subjects.extend(enabled_hosts.iter().cloned()); - if let Some(source_routes) = routes_by_registration.get(®istration.registration_id) { - for route in source_routes { - if let Some(filtered) = filter_route_hosts(route.clone(), &enabled_hosts) { - routes.push(filtered); - } - } - } else { - for host in enabled_hosts { - routes.push(json!({ - "match": [{ "host": [host] }], - "handle": [{ "handler": "static_response", "body": "Cadder route placeholder" }], - "terminal": true - })); - } + let registration_routes = + if let Some(source_routes) = routes_by_registration.get(®istration.registration_id) { + source_routes + .iter() + .filter_map(|route| filter_route_hosts(route.clone(), &enabled_hosts)) + .collect() + } else { + enabled_hosts + .iter() + .map(|host| { + json!({ + "match": [{ "host": [host] }], + "handle": [{ "handler": "static_response", "body": "Cadder route placeholder" }], + "terminal": true + }) + }) + .collect() + }; + if let Some(guarded) = guard_registration_routes(registration_routes, &enabled_hosts) { + routes.push(guarded); } } let tls_subjects = tls_subjects.into_iter().collect::>(); @@ -493,12 +517,12 @@ pub(super) fn compose_config( "apps": { "http": { "servers": { - "cadder_http": { - "listen": [":80"], + "cadder_http": { + "listen": ["127.0.0.1:80", "[::1]:80"], "routes": http_routes }, "cadder_https": { - "listen": [":443"], + "listen": ["127.0.0.1:443", "[::1]:443"], "tls_connection_policies": [{}], "routes": routes } @@ -516,6 +540,21 @@ pub(super) fn compose_config( }) } +fn guard_registration_routes( + routes: Vec, + enabled_hosts: &BTreeSet, +) -> Option { + if routes.is_empty() { + return None; + } + let hosts = enabled_hosts.iter().cloned().collect::>(); + Some(json!({ + "match": [{ "host": hosts }], + "handle": [{ "handler": "subroute", "routes": routes }], + "terminal": true + })) +} + pub(super) fn mock_route_for_domain(domain: &str) -> Value { mock_route_for_domain_and_upstream(domain, None) } diff --git a/crates/cadder-daemon/src/caddy/tests.rs b/crates/cadder-daemon/src/caddy/tests.rs index d47990a..47e1f08 100644 --- a/crates/cadder-daemon/src/caddy/tests.rs +++ b/crates/cadder-daemon/src/caddy/tests.rs @@ -648,6 +648,36 @@ async fn adapter_reports_adapt_timeout() { ); } +#[tokio::test] +async fn adapter_rejects_output_above_the_configured_stream_limit() { + let dir = tempdir("caddy-adapt-oversized-"); + let config_path = dir.path().join("Caddyfile"); + fs::write(&config_path, "app.localhost { respond ok }").unwrap(); + let oversized_caddy = install_test_process(dir.path(), "project-adapt-oversized"); + let adapter = CaddyConfigAdapter::with_command_limits( + RealCaddyResolver::with_executable_path( + Some(oversized_caddy.display().to_string()), + Some(dir.path().join(exe_name_for_test("cadderd"))), + ), + Duration::from_secs(5), + 1_024, + ); + let mut registration = registration("project", &[]); + registration.source_config_path = SourcePath::new( + config_path.display().to_string(), + Some(config_path.display().to_string()), + ); + + let prepared = adapter.prepare(registration).await; + + assert_eq!(prepared.diagnostics[0].code, "adapt-failed"); + assert!( + prepared.diagnostics[0] + .message + .contains("process output exceeded the 1024 byte stream limit") + ); +} + #[test] fn trusted_caddy_source_resolution_help_names_only_explicit_sources() { let resolver = RealCaddyResolver::with_test_sources( @@ -1027,7 +1057,7 @@ fn compose_config_uses_placeholder_route_when_adapted_routes_are_missing() { assert_eq!( config - .pointer("/apps/http/servers/cadder_https/routes/0/handle/0/body") + .pointer("/apps/http/servers/cadder_https/routes/0/handle/0/routes/0/handle/0/body") .and_then(Value::as_str), Some("Cadder route placeholder") ); @@ -1066,6 +1096,68 @@ fn compose_config_drops_routes_for_disabled_domains() { assert_eq!(tls_subjects, &[json!("app.localhost")]); } +#[test] +fn compose_config_binds_only_explicit_loopback_addresses() { + let config = compose_config( + &[registration("shim", &["app.localhost"])], + &BTreeMap::new(), + ); + + assert_eq!( + config.pointer("/apps/http/servers/cadder_http/listen"), + Some(&json!(["127.0.0.1:80", "[::1]:80"])) + ); + assert_eq!( + config.pointer("/apps/http/servers/cadder_https/listen"), + Some(&json!(["127.0.0.1:443", "[::1]:443"])) + ); +} + +#[test] +fn compose_config_guards_hostless_sibling_routes_with_registration_hosts() { + let routes_by_registration = BTreeMap::from([( + "shim".to_string(), + vec![json!({ + "handle": [{ + "handler": "subroute", + "routes": [ + { + "match": [{ "host": ["app.localhost"] }], + "handle": [{ "handler": "static_response", "body": "app" }] + }, + { + "handle": [{ "handler": "static_response", "body": "catch-all" }] + } + ] + }] + })], + )]); + + let config = compose_config( + &[registration("shim", &["app.localhost"])], + &routes_by_registration, + ); + + assert_eq!( + config.pointer("/apps/http/servers/cadder_https/routes/0/match/0/host"), + Some(&json!(["app.localhost"])) + ); + assert_eq!( + config + .pointer("/apps/http/servers/cadder_https/routes/0/handle/0/handler") + .and_then(Value::as_str), + Some("subroute") + ); + assert_eq!( + config + .pointer( + "/apps/http/servers/cadder_https/routes/0/handle/0/routes/0/handle/0/routes/1/handle/0/body", + ) + .and_then(Value::as_str), + Some("catch-all") + ); +} + #[test] fn finish_apply_state_updates_success_failure_and_idle() { let mut coordinator = coordinator_for_test(); diff --git a/crates/cadder-daemon/src/caddy_image.rs b/crates/cadder-daemon/src/caddy_image.rs index cb4b811..04b050f 100644 --- a/crates/cadder-daemon/src/caddy_image.rs +++ b/crates/cadder-daemon/src/caddy_image.rs @@ -14,7 +14,7 @@ use std::{ use tokio::process::Command; pub(crate) const CADDY_COMPATIBILITY_PROBE_REVISION: &str = "cadder-v1-probe-1"; -pub(crate) const MINIMUM_CADDY_VERSION: &str = "2.11.3"; +pub(crate) const MINIMUM_CADDY_VERSION: &str = "2.11.4"; const REQUIRED_CADDY_MODULES: &[&str] = &[ "http", diff --git a/crates/cadder-daemon/src/database.rs b/crates/cadder-daemon/src/database.rs index 32d3dd5..ceb5047 100644 --- a/crates/cadder-daemon/src/database.rs +++ b/crates/cadder-daemon/src/database.rs @@ -743,7 +743,10 @@ mod tests { .await .unwrap(); assert_eq!(result.entries.len(), 1); - assert_eq!(result.entries[0].raw_message, "reload failed [redacted]"); + assert_eq!( + result.entries[0].raw_message, + "reload failed token=[redacted]" + ); reopened.close().await.unwrap(); } diff --git a/crates/cadder-daemon/src/ipc/daemon_launch.rs b/crates/cadder-daemon/src/ipc/daemon_launch.rs index 7afcfdc..29f4be2 100644 --- a/crates/cadder-daemon/src/ipc/daemon_launch.rs +++ b/crates/cadder-daemon/src/ipc/daemon_launch.rs @@ -143,18 +143,14 @@ pub async fn ensure_daemon_running_with_options( return Ok(()); } - let daemon = options - .explicit_daemon - .or_else(|| sibling_binary("cadderd")) - .or_else(|| find_on_path("cadderd")) - .ok_or_else(|| { - daemon_launch_error( - LocalIpcErrorCode::DaemonNotFound, - "Cadder could not find the daemon executable; no daemon was started.", - "Install Cadder or provide a trusted cadderd path, then retry.", - None, - ) - })?; + let daemon = resolve_daemon_binary(options.explicit_daemon).ok_or_else(|| { + daemon_launch_error( + LocalIpcErrorCode::DaemonNotFound, + "Cadder could not find the daemon executable; no daemon was started.", + "Install Cadder or provide a trusted cadderd path, then retry.", + None, + ) + })?; let process_config = DaemonProcessConfig::for_launch_mode(options.launch_mode); let caddy_backend = options @@ -285,13 +281,17 @@ fn daemon_not_ready_yet(error: &IpcClientError) -> bool { fn sibling_binary(name: &str) -> Option { let current = env::current_exe().ok()?; + sibling_binary_next_to(¤t, name) +} + +fn sibling_binary_next_to(current: &std::path::Path, name: &str) -> Option { let dir = current.parent()?; let candidate = dir.join(exe_name(name)); candidate.is_file().then_some(candidate) } -pub(super) fn find_on_path(name: &str) -> Option { - which::which(exe_name(name)).ok() +fn resolve_daemon_binary(explicit: Option) -> Option { + explicit.or_else(|| sibling_binary("cadderd")) } pub(super) fn exe_name(name: &str) -> String { @@ -321,6 +321,7 @@ fn prepend_path_dir(command: &mut Command, dir: &std::path::Path) { #[cfg(test)] mod readiness_tests { use super::*; + use std::fs; #[test] fn launch_readiness_retries_connection_timeouts() { @@ -330,4 +331,26 @@ mod readiness_tests { let permanent = super::super::client::connection_error(io::Error::other("connect failed")); assert!(!daemon_not_ready_yet(&permanent)); } + + #[test] + fn daemon_discovery_accepts_only_an_explicit_path_or_version_matched_sibling() { + let directory = tempfile::tempdir().unwrap(); + let current = directory.path().join(exe_name("cadder")); + fs::write(¤t, b"client").unwrap(); + + assert!(sibling_binary_next_to(¤t, "cadderd").is_none()); + + let sibling = directory.path().join(exe_name("cadderd")); + fs::write(&sibling, b"daemon").unwrap(); + assert_eq!( + sibling_binary_next_to(¤t, "cadderd"), + Some(sibling.clone()) + ); + + let explicit = directory.path().join(exe_name("diagnostic-cadderd")); + assert_eq!( + resolve_daemon_binary(Some(explicit.clone())), + Some(explicit) + ); + } } diff --git a/crates/cadder-daemon/src/logs.rs b/crates/cadder-daemon/src/logs.rs index 18e943d..0f2d53f 100644 --- a/crates/cadder-daemon/src/logs.rs +++ b/crates/cadder-daemon/src/logs.rs @@ -3,31 +3,78 @@ use cadder_ipc::{ LogAttributionKind, LogEntry, LogEntryKind, LogSeverity, LogStreamIdentity, LogStreamStatus, }; use chrono::Utc; +use regex::Regex; use std::{ collections::{HashMap, VecDeque}, - sync::{Arc, Mutex}, + sync::{Arc, Mutex, OnceLock}, }; +const REDACTION_MARKER: &str = "[redacted]"; + +struct RedactionPatterns { + private_key: Regex, + header: Regex, + bearer: Regex, + quoted_assignment: Regex, + assignment: Regex, +} + +fn redaction_patterns() -> &'static RedactionPatterns { + static PATTERNS: OnceLock = OnceLock::new(); + PATTERNS.get_or_init(|| RedactionPatterns { + private_key: Regex::new( + r"(?is)-----BEGIN(?: [A-Z0-9]+)* PRIVATE KEY-----.*?-----END(?: [A-Z0-9]+)* PRIVATE KEY-----", + ) + .expect("private-key redaction pattern is valid"), + header: Regex::new( + r"(?im)\b(authorization|proxy-authorization|cookie|set-cookie)\s*:\s*[^\r\n]*", + ) + .expect("header redaction pattern is valid"), + bearer: Regex::new(r"(?i)\bbearer\s+[^\s,;]+") + .expect("bearer redaction pattern is valid"), + quoted_assignment: Regex::new( + r#"(?i)([\"']?(?:access[_-]?token|api[_-]?token|token|password|secret)[\"']?\s*[:=]\s*)(?:\"[^\"]*\"|'[^']*')"#, + ) + .expect("quoted credential redaction pattern is valid"), + assignment: Regex::new( + r#"(?i)([\"']?(?:access[_-]?token|api[_-]?token|token|password|secret)[\"']?\s*[:=]\s*)[^\s,;&}\]]+"#, + ) + .expect("credential redaction pattern is valid"), + }) +} + #[derive(Debug, Clone)] pub struct Redactor; impl Redactor { pub fn redact(input: &str) -> String { - let mut output = Vec::new(); - for token in input.split_whitespace() { - let lower = token.to_ascii_lowercase(); - if lower.contains("authorization:") - || lower.starts_with("bearer") - || lower.contains("token=") - || lower.contains("password=") - || lower.contains("secret=") - { - output.push("[redacted]"); - } else { - output.push(token); - } - } - output.join(" ") + let patterns = redaction_patterns(); + let output = patterns + .private_key + .replace_all(input, REDACTION_MARKER) + .into_owned(); + let output = patterns + .header + .replace_all(&output, |captures: ®ex::Captures<'_>| { + format!("{}: {REDACTION_MARKER}", &captures[1]) + }) + .into_owned(); + let output = patterns + .bearer + .replace_all(&output, format!("Bearer {REDACTION_MARKER}")) + .into_owned(); + let output = patterns + .quoted_assignment + .replace_all(&output, |captures: ®ex::Captures<'_>| { + format!("{}{REDACTION_MARKER}", &captures[1]) + }) + .into_owned(); + patterns + .assignment + .replace_all(&output, |captures: ®ex::Captures<'_>| { + format!("{}{REDACTION_MARKER}", &captures[1]) + }) + .into_owned() } } diff --git a/crates/cadder-daemon/src/logs/tests.rs b/crates/cadder-daemon/src/logs/tests.rs index c663eaa..d8e85d9 100644 --- a/crates/cadder-daemon/src/logs/tests.rs +++ b/crates/cadder-daemon/src/logs/tests.rs @@ -4,10 +4,51 @@ use super::*; fn redacts_token_like_values() { assert_eq!( Redactor::redact("ok Authorization: bearer token=abc password=def"), - "ok [redacted] [redacted] [redacted] [redacted]" + "ok Authorization: [redacted]" ); } +#[test] +fn redacts_documented_credential_forms_without_changing_unrelated_text() { + let input = concat!( + "Cookie: session=abc\n", + "payload={\"token\":\"json-secret\",\"password\":\"two words\"}\n", + "url=https://app.localhost/?access_token=query-secret&safe=yes\n", + "Authorization: Basic header-secret\n", + "safe=value" + ); + + let redacted = Redactor::redact(input); + + for secret in [ + "session=abc", + "json-secret", + "two words", + "query-secret", + "header-secret", + ] { + assert!( + !redacted.contains(secret), + "secret remained in {redacted:?}" + ); + } + assert!(redacted.contains("Cookie: [redacted]")); + assert!(redacted.contains("\"token\":[redacted]")); + assert!(redacted.contains("\"password\":[redacted]")); + assert!(redacted.contains("access_token=[redacted]&safe=yes")); + assert!(redacted.contains("safe=value")); +} + +#[test] +fn redacts_complete_private_key_blocks() { + let input = + "before\n-----BEGIN PRIVATE KEY-----\nsecret-key-material\n-----END PRIVATE KEY-----\nafter"; + + let redacted = Redactor::redact(input); + + assert_eq!(redacted, "before\n[redacted]\nafter"); +} + #[tokio::test] async fn query_returns_only_the_newest_requested_entries_for_one_stream() { let store = CaddyLogStore::new(10, 10); diff --git a/crates/cadder-daemon/src/process_tree.rs b/crates/cadder-daemon/src/process_tree.rs index 1de0dbb..d2a139f 100644 --- a/crates/cadder-daemon/src/process_tree.rs +++ b/crates/cadder-daemon/src/process_tree.rs @@ -83,6 +83,7 @@ impl ProcessTreeChild { Ok(()) } + #[cfg(all(test, windows))] pub(crate) async fn wait_for_output(self, deadline: Duration, operation: &str) -> Result { self .wait_for_bounded_output(deadline, operation, usize::MAX) diff --git a/crates/cadder-daemon/src/process_tree/tests.rs b/crates/cadder-daemon/src/process_tree/tests.rs index 0285af5..27e4534 100644 --- a/crates/cadder-daemon/src/process_tree/tests.rs +++ b/crates/cadder-daemon/src/process_tree/tests.rs @@ -37,6 +37,18 @@ async fn kill_terminates_descendants_and_closes_their_pipes() { #[tokio::test] async fn pinned_caddy_image_metadata_reader_bounds_and_drains_output() { + let (mut writer, reader) = tokio::io::duplex(64); + let write = tokio::spawn(async move { + writer.write_all(b"0123").await.unwrap(); + writer.shutdown().await.unwrap(); + }); + let mut pipe = Some(reader); + let mut bytes = Vec::new(); + + read_pipe_bounded(&mut pipe, &mut bytes, 4).await.unwrap(); + write.await.unwrap(); + assert_eq!(bytes, b"0123"); + let (mut writer, reader) = tokio::io::duplex(64); let write = tokio::spawn(async move { writer.write_all(b"0123456789").await.unwrap(); diff --git a/crates/cadder-daemon/tests/fixtures/test_process.rs b/crates/cadder-daemon/tests/fixtures/test_process.rs index 632442d..3b1bb8a 100644 --- a/crates/cadder-daemon/tests/fixtures/test_process.rs +++ b/crates/cadder-daemon/tests/fixtures/test_process.rs @@ -97,6 +97,10 @@ fn adapt(mode: &str) -> io::Result { println!("{{\"apps\":{{}}}}"); Ok(0) } + "project-adapt-oversized" => { + io::stdout().write_all(&vec![b'x'; 2_048])?; + Ok(0) + } mode if mode.starts_with("adapter-") => { println!("{ADAPTER_CONFIG}"); Ok(0) diff --git a/crates/cadder-daemon/tests/testcontainers_e2e.rs b/crates/cadder-daemon/tests/testcontainers_e2e.rs index 57168ae..fe045f7 100644 --- a/crates/cadder-daemon/tests/testcontainers_e2e.rs +++ b/crates/cadder-daemon/tests/testcontainers_e2e.rs @@ -5,7 +5,6 @@ use cadder_ipc::{ LogStreamStatus, QueryLogsPayload, QueryLogsResponse, QueryStatePayload, QueryStateResponse, RuntimeStatus, SetDomainEnabledPayload, ShutdownDaemonPayload, new_request_id, }; -use reqwest::{Client as HttpClient, StatusCode, Url, header::HOST, redirect::Policy}; use std::{ env, fs, path::{Path, PathBuf}, @@ -15,7 +14,7 @@ use std::{ use tempfile::TempDir; use testcontainers::{ ContainerAsync, GenericImage, ImageExt, - core::{AccessMode, IntoContainerPort, Mount, WaitFor}, + core::{AccessMode, ExecCommand, Mount, WaitFor}, runners::AsyncRunner, }; use tokio::{ @@ -26,8 +25,7 @@ use tokio::{ const CONTAINER_WORKSPACE: &str = "/workspace"; const CADDY_IMAGE: &str = "caddy"; -const CADDY_TAG: &str = "2.11.3-alpine"; -const HTTP_PORT: u16 = 80; +const CADDY_TAG: &str = "2.11.4-alpine"; const ALPHA_HOST: &str = "alpha.cadder-e2e.localhost"; const BETA_HOST: &str = "beta.cadder-e2e.localhost"; const INVALID_HOST: &str = "invalid.cadder-e2e.localhost"; @@ -223,9 +221,6 @@ async fn run_scenario(harness: &mut E2eHarness) -> Result<()> { struct E2eHarness { temp: TempDir, container: Option>, - container_host: String, - container_port: u16, - http: HttpClient, client: CadderClient, shim_path: PathBuf, proxy_log_path: PathBuf, @@ -246,28 +241,12 @@ impl E2eHarness { .with_access_mode(AccessMode::ReadWrite); let container = GenericImage::new(CADDY_IMAGE, CADDY_TAG) .with_entrypoint("/bin/sh") - .with_exposed_port(HTTP_PORT.tcp()) .with_wait_for(WaitFor::seconds(1)) .with_cmd(["-c", "sleep infinity"]) .with_mount(mount) .start() .await .with_context(|| format!("start Docker container {CADDY_IMAGE}:{CADDY_TAG}"))?; - let container_host = container - .get_host() - .await - .context("read mapped Caddy container host")? - .to_string(); - let container_port = container - .get_host_port_ipv4(HTTP_PORT.tcp()) - .await - .context("read mapped Caddy container HTTP port")?; - let http = HttpClient::builder() - .no_proxy() - .redirect(Policy::none()) - .timeout(Duration::from_secs(3)) - .build() - .context("build e2e HTTP client")?; let proxy_command = write_caddy_proxy(temp.path(), container.id())?; let proxy_log_path = temp.path().join("caddy-proxy.log"); let paths = RuntimePaths::resolve(Some(runtime_dir.clone()))?; @@ -278,9 +257,6 @@ impl E2eHarness { Ok(Self { temp, container: Some(container), - container_host, - container_port, - http, client, shim_path, proxy_log_path, @@ -384,9 +360,8 @@ impl E2eHarness { async fn wait_for_http_ok(&self, host: &str, expected_body: &str) -> Result<()> { for _ in 0..300 { - if let Ok(response) = self.http_get(host).await - && response.0 == StatusCode::OK - && response.1.contains(expected_body) + if let Ok(Some(body)) = self.http_get(host).await + && body.contains(expected_body) { return Ok(()); } @@ -398,8 +373,7 @@ impl E2eHarness { async fn wait_for_http_not_ok(&self, host: &str) -> Result<()> { for _ in 0..300 { match self.http_get(host).await { - Ok(response) if response.0 != StatusCode::OK => return Ok(()), - Err(_) => return Ok(()), + Ok(None) => return Ok(()), _ => sleep(Duration::from_millis(100)).await, } } @@ -413,13 +387,11 @@ impl E2eHarness { healthy_body: &str, ) -> Result<()> { for _ in 0..300 { - let blocked_not_ok = match self.http_get(blocked_host).await { - Ok(response) => response.0 != StatusCode::OK, - Err(_) => false, - }; + let blocked_not_ok = matches!(self.http_get(blocked_host).await, Ok(None)); let healthy_ok = match self.http_get(healthy_host).await { - Ok(response) => response.0 == StatusCode::OK && response.1.contains(healthy_body), + Ok(Some(body)) => body.contains(healthy_body), Err(_) => false, + Ok(None) => false, }; if blocked_not_ok && healthy_ok { return Ok(()); @@ -446,24 +418,30 @@ impl E2eHarness { bail!("expected proxy command `{command}` in log:\n{log}"); } - async fn http_get(&self, host: &str) -> Result<(StatusCode, String)> { - let mut url = Url::parse("http://localhost/").expect("static e2e URL is valid"); - url - .set_host(Some(&self.container_host)) - .map_err(|_| anyhow::anyhow!("invalid Caddy container host {}", self.container_host))?; - url - .set_port(Some(self.container_port)) - .map_err(|_| anyhow::anyhow!("invalid Caddy container port {}", self.container_port))?; - let response = self - .http - .get(url) - .header(HOST, host) - .send() + async fn http_get(&self, host: &str) -> Result> { + let container = self.container.as_ref().context("Caddy container missing")?; + let mut result = container + .exec(ExecCommand::new([ + "wget".to_string(), + "-qO-".to_string(), + "--header".to_string(), + format!("Host: {host}"), + "http://127.0.0.1/".to_string(), + ])) .await - .with_context(|| format!("request mapped Caddy endpoint for {host}"))?; - let status = response.status(); - let body = response.text().await.context("read Caddy response body")?; - Ok((status, body)) + .with_context(|| format!("request loopback Caddy endpoint for {host}"))?; + let stdout = result.stdout_to_vec().await?; + let _ = result.stderr_to_vec().await?; + let exit_code = result + .exit_code() + .await? + .context("container HTTP probe exit code missing")?; + if exit_code != 0 { + return Ok(None); + } + Ok(Some( + String::from_utf8(stdout).context("Caddy response body was not UTF-8")?, + )) } async fn cleanup(&mut self) -> Result<()> { diff --git a/crates/cadder-shim/Cargo.toml b/crates/cadder-shim/Cargo.toml index eef3091..eb229f4 100644 --- a/crates/cadder-shim/Cargo.toml +++ b/crates/cadder-shim/Cargo.toml @@ -15,8 +15,8 @@ path = "src/main.rs" [dependencies] anyhow = "=1.0.104" -cadder-api = { version = "1.0.0", path = "../cadder-api" } -cadder-ipc = { version = "1.0.0", path = "../cadder-ipc" } +cadder-api = { version = "1.0.1", path = "../cadder-api" } +cadder-ipc = { version = "1.0.1", path = "../cadder-ipc" } chrono = { version = "=0.4.45", features = ["serde"] } clap = { version = "=4.6.1", features = ["derive"] } serde_json = "=1.0.151" diff --git a/docs/site/package-lock.json b/docs/site/package-lock.json index a5e4afa..5b5dd49 100644 --- a/docs/site/package-lock.json +++ b/docs/site/package-lock.json @@ -3284,9 +3284,9 @@ } }, "node_modules/devalue": { - "version": "5.9.2", - "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.2.tgz", - "integrity": "sha512-po4PAY5c53tw5XMocSnf8A/5OHhbbUftpr93aEN6BBoAdntUmK7vu7wOATqvt7cXO7m1Cl4gMVn6p7n6n4mj0w==", + "version": "5.9.4", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz", + "integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==", "dev": true, "license": "MIT" }, diff --git a/docs/site/src/content/docs/reference/real-caddy-resolution.mdx b/docs/site/src/content/docs/reference/real-caddy-resolution.mdx index b095f86..6a3b948 100644 --- a/docs/site/src/content/docs/reference/real-caddy-resolution.mdx +++ b/docs/site/src/content/docs/reference/real-caddy-resolution.mdx @@ -27,7 +27,7 @@ Cadder does not require a special owner, parent-directory permission layout, or ## Version and image pinning -Cadder accepts Caddy 2.11.3 or newer within the 2.x release line. The selected build contains the standard modules used by Cadder and passes the compatibility probe shipped with the Cadder release. +Cadder accepts Caddy 2.11.4 or newer within the 2.x release line. The selected build contains the standard modules used by Cadder and passes the compatibility probe shipped with the Cadder release. The daemon pins the executable's canonical path, source, operating-system file identity, SHA-256 digest, semantic version, module inventory, and probe revision. It verifies the pinned image again before every probe, adaptation, runtime start, reload, and stop operation. Metadata output is bounded and each metadata command has a 30-second deadline. diff --git a/docs/verification/testcontainers-e2e.md b/docs/verification/testcontainers-e2e.md index 43fb3cd..e9378d2 100644 --- a/docs/verification/testcontainers-e2e.md +++ b/docs/verification/testcontainers-e2e.md @@ -12,7 +12,7 @@ complements the fast fake-Caddy lifecycle tests and does not replace `cargo test - Docker daemon is running. - Docker CLI is available on `PATH`. -- The current user can start containers and pull `caddy:2.11.3-alpine`. +- The current user can start containers and pull `caddy:2.11.4-alpine`. - No host-global Caddy installation is required. ## Command diff --git a/mise.lock b/mise.lock index a6667fe..207c0f8 100644 --- a/mise.lock +++ b/mise.lock @@ -1,8 +1,74 @@ # @generated - this file is auto-generated by `mise lock` https://mise.jdx.dev/dev-tools/mise-lock.html -[[tools."cargo:cargo-dist"]] -version = "0.32.0" -backend = "cargo:cargo-dist" +[[tools."aqua:axodotdev/cargo-dist"]] +version = "0.33.0" +backend = "aqua:axodotdev/cargo-dist" + +[tools."aqua:axodotdev/cargo-dist"."platforms.linux-arm64"] +checksum = "sha256:4761cff5fc547ad66d1449abbf321380b0e6bd8093b1fe6593852a3314fd0c19" +url = "https://github.com/axodotdev/cargo-dist/releases/download/v0.33.0/cargo-dist-aarch64-unknown-linux-musl.tar.xz" +url_api = "https://api.github.com/repos/axodotdev/cargo-dist/releases/assets/556576967" +provenance = "github-attestations" + +[tools."aqua:axodotdev/cargo-dist"."platforms.linux-arm64-musl"] +checksum = "sha256:4761cff5fc547ad66d1449abbf321380b0e6bd8093b1fe6593852a3314fd0c19" +url = "https://github.com/axodotdev/cargo-dist/releases/download/v0.33.0/cargo-dist-aarch64-unknown-linux-musl.tar.xz" +url_api = "https://api.github.com/repos/axodotdev/cargo-dist/releases/assets/556576967" +provenance = "github-attestations" + +[tools."aqua:axodotdev/cargo-dist"."platforms.linux-x64"] +checksum = "sha256:b8e95bc76c63375958173ef5ae2dbd8e9211cc1ed03cdee0899702766b4c2a2e" +url = "https://github.com/axodotdev/cargo-dist/releases/download/v0.33.0/cargo-dist-x86_64-unknown-linux-musl.tar.xz" +url_api = "https://api.github.com/repos/axodotdev/cargo-dist/releases/assets/556576998" +provenance = "github-attestations" + +[tools."aqua:axodotdev/cargo-dist"."platforms.linux-x64-baseline"] +checksum = "sha256:b8e95bc76c63375958173ef5ae2dbd8e9211cc1ed03cdee0899702766b4c2a2e" +url = "https://github.com/axodotdev/cargo-dist/releases/download/v0.33.0/cargo-dist-x86_64-unknown-linux-musl.tar.xz" +url_api = "https://api.github.com/repos/axodotdev/cargo-dist/releases/assets/556576998" +provenance = "github-attestations" + +[tools."aqua:axodotdev/cargo-dist"."platforms.linux-x64-musl"] +checksum = "sha256:b8e95bc76c63375958173ef5ae2dbd8e9211cc1ed03cdee0899702766b4c2a2e" +url = "https://github.com/axodotdev/cargo-dist/releases/download/v0.33.0/cargo-dist-x86_64-unknown-linux-musl.tar.xz" +url_api = "https://api.github.com/repos/axodotdev/cargo-dist/releases/assets/556576998" +provenance = "github-attestations" + +[tools."aqua:axodotdev/cargo-dist"."platforms.linux-x64-musl-baseline"] +checksum = "sha256:b8e95bc76c63375958173ef5ae2dbd8e9211cc1ed03cdee0899702766b4c2a2e" +url = "https://github.com/axodotdev/cargo-dist/releases/download/v0.33.0/cargo-dist-x86_64-unknown-linux-musl.tar.xz" +url_api = "https://api.github.com/repos/axodotdev/cargo-dist/releases/assets/556576998" +provenance = "github-attestations" + +[tools."aqua:axodotdev/cargo-dist"."platforms.macos-arm64"] +checksum = "sha256:7b3cbe25511de01d74c0f5fcb7909edabd379bea9cfa284d93af5a3cdfa3247c" +url = "https://github.com/axodotdev/cargo-dist/releases/download/v0.33.0/cargo-dist-aarch64-apple-darwin.tar.xz" +url_api = "https://api.github.com/repos/axodotdev/cargo-dist/releases/assets/556576963" +provenance = "github-attestations" + +[tools."aqua:axodotdev/cargo-dist"."platforms.macos-x64"] +checksum = "sha256:6a49bfb61bd86770d79c27f3d2b40c6b2e71cde940d3d31a6ccaaffc124d7a29" +url = "https://github.com/axodotdev/cargo-dist/releases/download/v0.33.0/cargo-dist-x86_64-apple-darwin.tar.xz" +url_api = "https://api.github.com/repos/axodotdev/cargo-dist/releases/assets/556576979" +provenance = "github-attestations" + +[tools."aqua:axodotdev/cargo-dist"."platforms.macos-x64-baseline"] +checksum = "sha256:6a49bfb61bd86770d79c27f3d2b40c6b2e71cde940d3d31a6ccaaffc124d7a29" +url = "https://github.com/axodotdev/cargo-dist/releases/download/v0.33.0/cargo-dist-x86_64-apple-darwin.tar.xz" +url_api = "https://api.github.com/repos/axodotdev/cargo-dist/releases/assets/556576979" +provenance = "github-attestations" + +[tools."aqua:axodotdev/cargo-dist"."platforms.windows-x64"] +checksum = "sha256:9a36d70795e14326a5ec4bf17aee085df00ab85a322739291ea5d4b1b5f693cd" +url = "https://github.com/axodotdev/cargo-dist/releases/download/v0.33.0/cargo-dist-x86_64-pc-windows-msvc.zip" +url_api = "https://api.github.com/repos/axodotdev/cargo-dist/releases/assets/556576987" +provenance = "github-attestations" + +[tools."aqua:axodotdev/cargo-dist"."platforms.windows-x64-baseline"] +checksum = "sha256:9a36d70795e14326a5ec4bf17aee085df00ab85a322739291ea5d4b1b5f693cd" +url = "https://github.com/axodotdev/cargo-dist/releases/download/v0.33.0/cargo-dist-x86_64-pc-windows-msvc.zip" +url_api = "https://api.github.com/repos/axodotdev/cargo-dist/releases/assets/556576987" +provenance = "github-attestations" [[tools."cargo:cargo-llvm-cov"]] version = "0.8.7" diff --git a/mise.toml b/mise.toml index 6a1ac32..a6fb04c 100644 --- a/mise.toml +++ b/mise.toml @@ -5,7 +5,7 @@ rust = { version = "1.95.0", components = "rustfmt,clippy,llvm-tools-preview" } node = "24.18.0" "npm:@fission-ai/openspec" = "1.5.0" "cargo:cargo-llvm-cov" = "0.8.7" -"cargo:cargo-dist" = "0.32.0" +"aqua:axodotdev/cargo-dist" = "0.33.0" [tasks.fmt] description = "Check Rust formatting" @@ -64,8 +64,8 @@ run = [ "openspec validate --all --strict --no-interactive", { task = "docs-check" }, { task = "npm-check" }, - "dist generate --check", - "dist plan", + { task = "dist-workflow-check" }, + "dist plan --allow-dirty", ] [tasks.dev] @@ -79,8 +79,19 @@ run = "ttyglass -- mise run dev" [tasks.dist-plan] description = "Create a non-publishing cargo-dist release plan" -run = ["dist generate --check", "dist plan"] +run = [{ task = "dist-workflow-check" }, "dist plan --allow-dirty"] + +[tasks.dist-workflow-sync] +description = "Regenerate and harden the cargo-dist GitHub workflow" +run = ["dist generate", "node scripts/harden-dist-workflow.mjs --apply"] + +[tasks.dist-workflow-check] +description = "Verify the generated and hardened cargo-dist GitHub workflow" +run = [ + "node --test scripts/test/harden-dist-workflow.test.mjs", + "node scripts/harden-dist-workflow.mjs --check-generated", +] [tasks.dist-build] description = "Build non-publishing cargo-dist artifacts" -run = "dist build" +run = "dist build --allow-dirty" diff --git a/npm/nub.lock b/npm/nub.lock index 716085f..d80e10b 100644 --- a/npm/nub.lock +++ b/npm/nub.lock @@ -13,16 +13,16 @@ importers: version: 2.8.3 optionalDependencies: '@maxiedev/cadder-darwin-arm64': - specifier: 1.0.0 + specifier: 1.0.1 version: link:packages/darwin-arm64 '@maxiedev/cadder-darwin-x64': - specifier: 1.0.0 + specifier: 1.0.1 version: link:packages/darwin-x64 '@maxiedev/cadder-linux-x64-gnu': - specifier: 1.0.0 + specifier: 1.0.1 version: link:packages/linux-x64-gnu '@maxiedev/cadder-win32-x64': - specifier: 1.0.0 + specifier: 1.0.1 version: link:packages/win32-x64 packages/darwin-arm64: {} diff --git a/npm/package.json b/npm/package.json index 64119ce..8acc6cd 100644 --- a/npm/package.json +++ b/npm/package.json @@ -1,6 +1,6 @@ { "name": "cadder", - "version": "1.0.0", + "version": "1.0.1", "description": "Portable launcher for the Cadder Caddy coordinator.", "keywords": [ "caddy", @@ -48,10 +48,10 @@ "bootstrap:pack": "node scripts/pack-bootstrap.js" }, "optionalDependencies": { - "@maxiedev/cadder-darwin-arm64": "1.0.0", - "@maxiedev/cadder-darwin-x64": "1.0.0", - "@maxiedev/cadder-linux-x64-gnu": "1.0.0", - "@maxiedev/cadder-win32-x64": "1.0.0" + "@maxiedev/cadder-darwin-arm64": "1.0.1", + "@maxiedev/cadder-darwin-x64": "1.0.1", + "@maxiedev/cadder-linux-x64-gnu": "1.0.1", + "@maxiedev/cadder-win32-x64": "1.0.1" }, "publishConfig": { "access": "public", diff --git a/npm/packages/darwin-arm64/package.json b/npm/packages/darwin-arm64/package.json index 5d5cede..a1e5613 100644 --- a/npm/packages/darwin-arm64/package.json +++ b/npm/packages/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@maxiedev/cadder-darwin-arm64", - "version": "1.0.0", + "version": "1.0.1", "description": "macOS Apple Silicon native binaries for Cadder.", "license": "Apache-2.0", "repository": { diff --git a/npm/packages/darwin-x64/package.json b/npm/packages/darwin-x64/package.json index 13ea7c1..4b3df75 100644 --- a/npm/packages/darwin-x64/package.json +++ b/npm/packages/darwin-x64/package.json @@ -1,6 +1,6 @@ { "name": "@maxiedev/cadder-darwin-x64", - "version": "1.0.0", + "version": "1.0.1", "description": "macOS Intel native binaries for Cadder.", "license": "Apache-2.0", "repository": { diff --git a/npm/packages/linux-x64-gnu/package.json b/npm/packages/linux-x64-gnu/package.json index 0b667a3..ba7a371 100644 --- a/npm/packages/linux-x64-gnu/package.json +++ b/npm/packages/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@maxiedev/cadder-linux-x64-gnu", - "version": "1.0.0", + "version": "1.0.1", "description": "Linux x64 glibc native binaries for Cadder.", "license": "Apache-2.0", "repository": { diff --git a/npm/packages/win32-x64/package.json b/npm/packages/win32-x64/package.json index ee288b6..0fa1f06 100644 --- a/npm/packages/win32-x64/package.json +++ b/npm/packages/win32-x64/package.json @@ -1,6 +1,6 @@ { "name": "@maxiedev/cadder-win32-x64", - "version": "1.0.0", + "version": "1.0.1", "description": "Windows x64 native binaries for Cadder.", "license": "Apache-2.0", "repository": { diff --git a/npm/scripts/assemble-release.js b/npm/scripts/assemble-release.js index 5639ca8..25a63cc 100644 --- a/npm/scripts/assemble-release.js +++ b/npm/scripts/assemble-release.js @@ -4,6 +4,7 @@ import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { platformTargets } from '../lib/platforms.js'; +import { attestationVerifyArguments, releaseSignerWorkflow } from './attestation-policy.js'; import { commandNames, documentationFiles, @@ -19,8 +20,8 @@ import { const npmDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const projectDirectory = resolve(npmDirectory, '..'); -async function verifyAttestation(path) { - await run('gh', ['attestation', 'verify', path, '--repo', 'MrMaxie/Cadder']); +async function verifyAttestation(path, provenance) { + await run('gh', attestationVerifyArguments(path, provenance)); } async function verifyArchiveChecksum(archive, checksum) { @@ -56,13 +57,20 @@ async function prepareRootPackage(output, expectedVersion) { return destination; } -async function preparePlatformPackage({ assets, output, target, expectedVersion, verifyAttestations }) { +async function preparePlatformPackage({ + assets, + output, + target, + expectedVersion, + provenance, + verifyAttestations, +}) { const archive = resolve(assets, target.archive); const checksum = `${archive}.sha256`; await verifyArchiveChecksum(archive, checksum); if (verifyAttestations) { - await verifyAttestation(archive); - await verifyAttestation(checksum); + await verifyAttestation(archive, provenance); + await verifyAttestation(checksum, provenance); } const extractionRoot = await mkdtemp(resolve(output, `.extract-${target.directory}-`)); @@ -118,6 +126,17 @@ const selectedTargets = if (typeof targetDirectory !== 'undefined' && selectedTargets.length !== 1) { throw new Error(`Unknown npm platform target: ${targetDirectory}`); } +const provenance = testMode + ? null + : { + sourceRef: requiredArgument(argumentsMap, 'source-ref'), + sourceDigest: requiredArgument(argumentsMap, 'source-digest'), + signerWorkflow: requiredArgument(argumentsMap, 'signer-workflow'), + }; +if (provenance) { + attestationVerifyArguments('release-asset', provenance); + assert.equal(provenance.signerWorkflow, releaseSignerWorkflow); +} await prepareRootPackage(output, version); const packages = []; @@ -128,6 +147,7 @@ for (const target of selectedTargets) { output, target, expectedVersion: version, + provenance, verifyAttestations: !testMode, }), ); diff --git a/npm/scripts/attestation-policy.js b/npm/scripts/attestation-policy.js new file mode 100644 index 0000000..9ada035 --- /dev/null +++ b/npm/scripts/attestation-policy.js @@ -0,0 +1,23 @@ +import assert from 'node:assert/strict'; + +export const releaseRepository = 'MrMaxie/Cadder'; +export const releaseSignerWorkflow = 'MrMaxie/Cadder/.github/workflows/release.yml'; + +export function attestationVerifyArguments(path, { sourceRef, sourceDigest, signerWorkflow }) { + assert.match(sourceRef, /^refs\/tags\/v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/); + assert.match(sourceDigest, /^[0-9a-f]{40}$/); + assert.equal(signerWorkflow, releaseSignerWorkflow); + return [ + 'attestation', + 'verify', + path, + '--repo', + releaseRepository, + '--source-ref', + sourceRef, + '--source-digest', + sourceDigest, + '--signer-workflow', + signerWorkflow, + ]; +} diff --git a/npm/scripts/check-workflow.js b/npm/scripts/check-workflow.js index 50403f1..0ca68c1 100644 --- a/npm/scripts/check-workflow.js +++ b/npm/scripts/check-workflow.js @@ -8,10 +8,18 @@ const npmDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const projectDirectory = resolve(npmDirectory, '..'); const workflowPath = resolve(projectDirectory, '.github', 'workflows', 'npm.yml'); const ciWorkflowPath = resolve(projectDirectory, '.github', 'workflows', 'ci.yml'); +const releaseWorkflowPath = resolve(projectDirectory, '.github', 'workflows', 'release.yml'); const source = await readFile(workflowPath, 'utf8'); const ciSource = await readFile(ciWorkflowPath, 'utf8'); +const releaseSource = await readFile(releaseWorkflowPath, 'utf8'); const stageSource = await readFile(resolve(npmDirectory, 'scripts', 'stage-release.js'), 'utf8'); +const assemblySource = await readFile(resolve(npmDirectory, 'scripts', 'assemble-release.js'), 'utf8'); +const attestationPolicySource = await readFile( + resolve(npmDirectory, 'scripts', 'attestation-policy.js'), + 'utf8', +); const workflow = parse(source); +const releaseWorkflow = parse(releaseSource); assert.deepEqual(workflow.on.release.types, ['published']); assert.ok(workflow.on.workflow_dispatch, 'The npm workflow must expose a non-publishing manual dry run.'); @@ -29,11 +37,37 @@ assert.match(stageSource, /['"]stage['"]\s*,\s*['"]publish['"]/, 'The stage scri assert.match(stageSource, /['"]publish['"]\s*,\s*archive/, 'The stage script must publish only the verified tarball path.'); assert.match(stageSource, /['"]--provenance['"]/, 'The stage script must request npm provenance.'); assert.equal(source.includes('npm publish '), false, 'The npm workflow must not publish directly.'); +assert.match(source, /ref: \$\{\{ env\.RELEASE_TAG \}\}/); +assert.match(source, /git rev-parse HEAD\^\{commit\}/); +assert.match(source, /--source-ref "refs\/tags\/\$RELEASE_TAG"/); +assert.match(source, /--source-digest "\$\{\{ steps\.source\.outputs\.commit \}\}"/); +assert.match(source, /--signer-workflow "\$GITHUB_REPOSITORY\/\.github\/workflows\/release\.yml"/); +assert.match(assemblySource, /attestationVerifyArguments\(path, provenance\)/); +for (const option of ['--repo', '--source-ref', '--source-digest', '--signer-workflow']) { + assert.ok(attestationPolicySource.includes(`'${option}'`), `Attestation policy must require ${option}.`); +} for (const jobName of ['prepare', 'verify-native', 'stage']) { assert.ok(workflow.jobs[jobName], `Missing ${jobName} job.`); } +assert.equal(releaseWorkflow.permissions.contents, 'read'); +for (const jobName of ['plan', 'build-local-artifacts', 'build-global-artifacts', 'host']) { + assert.equal( + releaseWorkflow.jobs[jobName].env?.GH_TOKEN, + undefined, + `${jobName} must not receive a GitHub publication token.`, + ); +} +assert.deepEqual(releaseWorkflow.jobs.announce.permissions, { + attestations: 'write', + contents: 'write', + 'id-token': 'write', +}); +assert.equal(releaseSource.includes('tag-flag'), false); +assert.equal(releaseSource.match(/github\.ref_name/g)?.length, 1); +assert.match(releaseSource, /gh release create "\$RELEASE_TAG"/); + const setupNodeAction = 'actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903'; const nubInstallCommand = 'npm install --global @nubjs/nub@0.7.5'; diff --git a/npm/test/attestation-policy.test.js b/npm/test/attestation-policy.test.js new file mode 100644 index 0000000..1c27f17 --- /dev/null +++ b/npm/test/attestation-policy.test.js @@ -0,0 +1,51 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { + attestationVerifyArguments, + releaseRepository, + releaseSignerWorkflow, +} from '../scripts/attestation-policy.js'; + +const provenance = { + sourceRef: 'refs/tags/v1.0.1', + sourceDigest: 'a'.repeat(40), + signerWorkflow: releaseSignerWorkflow, +}; + +test('binds verification to the exact release identity', () => { + assert.deepEqual(attestationVerifyArguments('artifact.zip', provenance), [ + 'attestation', + 'verify', + 'artifact.zip', + '--repo', + releaseRepository, + '--source-ref', + provenance.sourceRef, + '--source-digest', + provenance.sourceDigest, + '--signer-workflow', + releaseSignerWorkflow, + ]); +}); + +test('rejects a non-release ref, invalid commit, or another signer workflow', () => { + assert.throws(() => + attestationVerifyArguments('artifact.zip', { + ...provenance, + sourceRef: 'refs/heads/master', + }), + ); + assert.throws(() => + attestationVerifyArguments('artifact.zip', { + ...provenance, + sourceDigest: 'not-a-commit', + }), + ); + assert.throws(() => + attestationVerifyArguments('artifact.zip', { + ...provenance, + signerWorkflow: 'MrMaxie/Cadder/.github/workflows/other.yml', + }), + ); +}); diff --git a/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/.openspec.yaml b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/.openspec.yaml new file mode 100644 index 0000000..ad94bad --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-02 diff --git a/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/README.md b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/README.md new file mode 100644 index 0000000..1ce9972 --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/README.md @@ -0,0 +1,3 @@ +# harden-local-runtime-boundaries + +Keep local development routes loopback-only, isolate registered hosts, bound adaptation output, redact required secrets, render logs safely, and launch only the version-matched sibling daemon. diff --git a/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/design.md b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/design.md new file mode 100644 index 0000000..950a6c8 --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/design.md @@ -0,0 +1,54 @@ +## Context + +Cadder runs one real Caddy process for trusted projects on a personal development workstation. Project Caddyfiles remain trusted inputs, but Cadder owns the shared listeners, active-host boundary, retained diagnostics, and managed daemon launch. The current generated configuration listens on wildcard addresses, recursively edits project routes without guarding their full route tree, captures unbounded adaptation output, and may launch `cadderd` from PATH even though the supported installation keeps version-matched executables together. + +## Goals / Non-Goals + +**Goals:** + +- Preserve managed `caddy run` while making every Cadder-owned HTTP and HTTPS listener loopback-only. +- Guarantee that one registration cannot handle a host outside its active domain set. +- Complete the existing bounded-output and redaction contracts without building a general secret scanner. +- Keep terminal control bytes inert at the presentation boundary. +- Align automatic daemon launch with the documented version-matched sibling installation. + +**Non-Goals:** + +- Protect one operating-system account from another account on a shared host. +- Replace the loopback Caddy administration endpoint. +- Treat trusted project files or the current user as adversarial code. +- Add new ports, commands, IPC fields, installation forms, or an executable snapshot cache. + +## Decisions + +Cadder emits explicit IPv4 and IPv6 loopback listeners for both existing ports. Listener ownership remains in configuration composition, so adapted project input cannot widen it. + +Each registration contributes one outer host-matched route whose subroute contains its filtered adapted routes. Recursive filtering remains useful for removing inactive host values, but the outer matcher is the security and isolation boundary even when an adapted route contains hostless sibling handlers. + +`caddy adapt` uses the existing bounded process-tree capture with a 32 MiB limit per output stream. Limit failures retain the existing process cleanup guarantee and never parse partial output. + +Redaction uses a small set of precompiled regular expressions plus a focused private-key block recognizer. The options were manual string parsing, the mature `regex` crate, and a general secret-scanning framework. Manual parsing adds more delimiter and escaping cases, while a framework introduces configuration and false-positive policy beyond the accepted contract. Focused regular expressions add one established dependency and cover only authorization, cookie, token, password, and private-key forms named by OpenSpec. + +Terminal sanitation remains presentation-only. A small standard-library state machine removes ANSI CSI and OSC sequences and remaining C0/C1 controls from diagnostic and log messages before `comfy-table` renders them. Persisted redacted logs remain otherwise unchanged. + +Automatic launch accepts the version-matched sibling `cadderd`. The existing explicit path stays available to focused tests and foreground diagnostics. Native PATH discovery is removed from this launch path, while trusted real-Caddy resolution remains unchanged. + +## Risks / Trade-offs + +- Binding IPv4 and IPv6 loopback can expose a platform-specific listener failure that wildcard binding previously hid. Startup already reports Caddy configuration failures and must fail rather than widen the listener. +- Focused redaction cannot recognize every possible secret name. Tests cover only the forms promised by OBS-001, and the implementation does not claim general detection. +- Stripping terminal controls can change the visual representation of a diagnostic. The retained redacted source remains available through the existing storage contract. +- A 32 MiB adaptation response can still be large, but it bounds daemon memory while allowing substantial generated configurations. + +## Migration Plan + +1. Add focused failing tests for listener addresses, guarded route trees, adaptation limits, required redaction forms, terminal sanitation, and sibling-only daemon discovery. +2. Implement each boundary using existing configuration, process-tree, log-store, and CLI ownership seams. +3. Raise the minimum and integration fixture Caddy patch version to 2.11.4. +4. Run focused crate tests followed by the complete repository gate. + +Rollback restores the previous implementation and minimum Caddy patch version. No stored data or wire migration is required. + +## Open Questions + +None. diff --git a/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/proposal.md b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/proposal.md new file mode 100644 index 0000000..662be02 --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/proposal.md @@ -0,0 +1,27 @@ +## Why + +Cadder coordinates trusted local development projects, but its generated Caddy configuration currently widens local routes to all network interfaces, can retain sibling catch-all branches, and leaves several bounded-output and presentation guarantees incomplete. The existing `caddy run` journey must remain unchanged while the daemon enforces the local-only and owner-selected boundaries promised by the product. + +## What Changes + +- Bind Cadder-owned HTTP and HTTPS servers to loopback without changing their ports or the managed `caddy run` workflow. +- Place each adapted project route set behind an exact active-host guard. +- Bound `caddy adapt` output, redact the credential forms named by the observability contract, and neutralize terminal control characters only when the CLI renders diagnostic text. +- Launch the managed daemon only from the version-matched sibling executable or an explicit diagnostic override, without automatic PATH fallback. +- Raise the minimum tested Caddy patch release to 2.11.4 while retaining the existing trusted Caddy resolution and loopback administration endpoint. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `caddy-runtime`: Cadder-owned listeners and composed project routes remain local and host-scoped. +- `observability`: Required credential forms are redacted before retention, while terminal rendering is control-character safe. +- `daemon-lifecycle`: Managed startup uses the version-matched sibling daemon rather than PATH discovery. + +## Impact + +This change affects Caddy configuration composition, adaptation process limits, daemon launch resolution, log redaction, CLI rendering, focused runtime tests, and the tested Caddy version. It does not change the IPC schema, Caddy administration transport, public commands, ports, or installation model. diff --git a/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/release.md b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/release.md new file mode 100644 index 0000000..47281d8 --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/release.md @@ -0,0 +1,18 @@ +--- +impact: patch +components: + - caddy-runtime + - observability + - daemon-lifecycle +audiences: + - developers + - operators +observable_impact: user-felt +changelog: include +--- + +## Fixed + +### Keep managed development routes local and isolated + +Cadder now binds its shared HTTP and HTTPS listeners only to loopback, keeps every project behind its active host names, redacts the documented credential forms from retained logs, and renders diagnostic text without active terminal control sequences. diff --git a/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/specs/caddy-runtime/spec.md b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/specs/caddy-runtime/spec.md new file mode 100644 index 0000000..a63a4bd --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/specs/caddy-runtime/spec.md @@ -0,0 +1,19 @@ +## ADDED Requirements + +### Requirement: CADDY-004: Owned listeners and routes remain local +Cadder SHALL bind its owned HTTP and HTTPS servers only to IPv4 and IPv6 loopback addresses on the existing ports. Each registration's complete adapted route tree MUST remain behind an outer matcher containing only that registration's active canonical hosts, and project input MUST NOT widen either boundary. + +#### Scenario: Remote peer addresses the developer host +- **WHEN** a peer connects through a non-loopback interface and supplies an active `.localhost` host header +- **THEN** no Cadder-owned HTTP or HTTPS listener accepts the connection + +#### Scenario: Adapted route contains a hostless sibling +- **WHEN** one retained branch matches an active host and a sibling branch has no host matcher +- **THEN** the complete route tree remains reachable only under the registration's active canonical hosts + +### Requirement: CADDY-005: Project configuration adaptation is bounded +Cadder MUST capture at most 32 MiB from each `caddy adapt` output stream, reject partial adaptation output when either limit is exceeded, and retain bounded cleanup for any adapter process tree that remains active. + +#### Scenario: Adapter exceeds an output limit +- **WHEN** `caddy adapt` writes more than 32 MiB to stdout or stderr +- **THEN** Cadder reports a bounded failure without applying configuration and cleans up the owned adapter process tree if it remains active diff --git a/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/specs/daemon-lifecycle/spec.md b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/specs/daemon-lifecycle/spec.md new file mode 100644 index 0000000..de63b3d --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/specs/daemon-lifecycle/spec.md @@ -0,0 +1,8 @@ +## MODIFIED Requirements + +### Requirement: RUN-002: Managed run may start the daemon +When attachment reports that no daemon is running, supported `caddy run` MUST launch the version-matched sibling `cadderd`, poll the exact handshake to readiness, and retry attachment. Automatic managed startup MUST NOT discover `cadderd` through PATH. An explicit daemon path MAY remain available to focused tests and foreground diagnostics. + +#### Scenario: Startup fails +- **WHEN** the sibling daemon cannot be found or become ready within the bounded deadline +- **THEN** the shim reports actionable diagnostics and never launches an unrelated PATH executable or delegates an unmanaged run diff --git a/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/specs/observability/spec.md b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/specs/observability/spec.md new file mode 100644 index 0000000..703685c --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/specs/observability/spec.md @@ -0,0 +1,17 @@ +## MODIFIED Requirements + +### Requirement: OBS-001: Redaction precedes persistence and response +Cadder MUST redact authorization and cookie header values, token and password values in supported text, JSON, and URL query forms, and private-key blocks before a log reaches SQLite or an IPC response. Retained data SHALL use one stable redaction marker and MUST NOT preserve any part of the matched credential value. + +#### Scenario: Documented credential form appears +- **WHEN** a log contains an authorization header, cookie, token, password, or private key +- **THEN** the retained value contains the stable redaction marker instead of the credential value + +## ADDED Requirements + +### Requirement: OBS-004: Terminal rendering is control-safe +The operator CLI MUST neutralize ANSI escape sequences and C0 or C1 control characters in diagnostic and log messages before writing them to an interactive terminal. Redacted retained log content SHALL otherwise remain unchanged. + +#### Scenario: Diagnostic contains terminal controls +- **WHEN** a retained log or diagnostic message contains an ANSI sequence or another C0 or C1 control character +- **THEN** the CLI renders the message without executing or forwarding that control sequence diff --git a/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/tasks.md b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/tasks.md new file mode 100644 index 0000000..a1723a6 --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-local-runtime-boundaries/tasks.md @@ -0,0 +1,16 @@ +## 1. Local Caddy boundaries + +- [x] 1.1 Add focused configuration tests and bind both owned servers to IPv4 and IPv6 loopback on the existing ports. (verification: configuration tests inspect exact listener addresses) +- [x] 1.2 Guard each registration's complete adapted route tree with its active canonical hosts. (verification: a hostless sibling cannot match outside the registration host set) +- [x] 1.3 Bound each `caddy adapt` output stream at 32 MiB and preserve process-tree cleanup. (verification: focused tests cover success at the limit and failure above it) + +## 2. Diagnostics and launch trust + +- [x] 2.1 Redact the credential forms required by OBS-001 before storage and IPC. (verification: focused tests cover headers, text, JSON, URL query values, and private-key blocks) +- [x] 2.2 Remove terminal control sequences from log and diagnostic messages at the CLI rendering boundary. (verification: focused unit tests cover ANSI CSI, OSC, C0, and C1 input) +- [x] 2.3 Remove automatic PATH discovery for `cadderd` while preserving sibling and explicit diagnostic launch paths. (verification: launch tests reject a PATH-only daemon and accept the sibling or explicit path) + +## 3. Compatibility and complete validation + +- [x] 3.1 Raise the minimum and integration fixture Caddy version to 2.11.4. (verification: version and integration fixtures target the same patch release) +- [x] 3.2 Run focused crate checks and the complete repository validation, then review the full diff and working tree. (verification: all applicable gates pass with no unrelated files) diff --git a/openspec/changes/archive/2026-10-02-harden-release-pipeline/.openspec.yaml b/openspec/changes/archive/2026-10-02-harden-release-pipeline/.openspec.yaml new file mode 100644 index 0000000..ad94bad --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-release-pipeline/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-02 diff --git a/openspec/changes/archive/2026-10-02-harden-release-pipeline/README.md b/openspec/changes/archive/2026-10-02-harden-release-pipeline/README.md new file mode 100644 index 0000000..2421f26 --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-release-pipeline/README.md @@ -0,0 +1,3 @@ +# harden-release-pipeline + +Apply least-privilege release permissions, validate release tags outside shell expressions, bind npm verification to exact release provenance, and update security-relevant release tools. diff --git a/openspec/changes/archive/2026-10-02-harden-release-pipeline/design.md b/openspec/changes/archive/2026-10-02-harden-release-pipeline/design.md new file mode 100644 index 0000000..3d2fc5f --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-release-pipeline/design.md @@ -0,0 +1,52 @@ +## Context + +cargo-dist owns Cadder's release planning, artifacts, and generated GitHub workflow. Its current generated workflow grants `contents: write` globally, exports `GH_TOKEN` to planning and build jobs, and inserts a GitHub ref expression directly into shell source. The npm workflow verifies repository attestations but does not bind them to the selected tag, commit, or signer workflow. + +## Goals / Non-Goals + +**Goals:** + +- Preserve cargo-dist ownership of release planning and artifact construction. +- Give build jobs read-only repository access and no publication token. +- Treat a release tag as validated data rather than shell program text. +- Prove npm inputs belong to the exact selected release and expected signer workflow. +- Keep local and CI checks deterministic after the focused hardening pass. + +**Non-Goals:** + +- Publish, tag, stage, or approve a release. +- Replace cargo-dist with a hand-maintained release pipeline. +- Add a general workflow generation framework. +- Upgrade unrelated Rust dependencies or adopt breaking dependency releases. + +## Decisions + +The options were waiting for cargo-dist support, maintaining the complete workflow by hand, and applying a focused deterministic postprocessor. Waiting leaves accepted findings open, while a hand-maintained workflow duplicates cargo-dist policy. A standard-library Node.js postprocessor is selected because Node is already pinned by the repository, it changes only known permission and tag-handling fragments, fails closed when the generated shape changes, and preserves cargo-dist ownership of every artifact operation. + +The postprocessor has apply and check modes. Apply mode hardens a freshly generated workflow. Check mode verifies both the exact structural transformations and the resulting security invariants. The supported `mise` tasks call the script through the pinned Node.js runtime and keep the committed workflow equal to the generated-then-hardened result. Commands that consume the intentionally customized workflow pass cargo-dist's `--allow-dirty` flag only after the dedicated repository check proves that the committed workflow equals generated output after hardening. + +The workflow places the tag expression in `RELEASE_TAG`, validates the accepted Cadder `v` form once, and passes the quoted value to cargo-dist. Planning and build jobs receive `contents: read`; only the announce path receives the write and attestation permissions needed to publish immutable assets. + +The npm prepare job checks out the selected tag, resolves its commit, and passes the tag ref, commit digest, and expected release workflow to the assembly script. Each `gh attestation verify` invocation requires all three identities in addition to the repository. + +The documentation lockfile is refreshed with npm so the existing compatible dependency range resolves `devalue` at or above 5.9.4. No direct documentation dependency or TypeScript major changes are included. + +## Risks / Trade-offs + +- The postprocessor is intentionally coupled to cargo-dist's generated workflow shape. Unexpected upstream changes fail the check and require a reviewed adapter update rather than silently weakening permissions. +- A custom adapter is one additional repository concept. It remains narrow, contains no artifact policy, and is removed when cargo-dist can express the same invariants. +- Exact signer and source binding rejects otherwise valid attestations produced by a different workflow. That is the intended release identity boundary. + +## Migration Plan + +1. Update cargo-dist to 0.33.0 and regenerate the official workflow. +2. Add the postprocessor and tests, then commit only the hardened generated result. +3. Bind npm checkout and attestation verification to the selected release identity. +4. Refresh the documentation lockfile and confirm the vulnerable transitive version is absent. +5. Run release workflow checks, npm tests and audit, cargo-dist planning, OpenSpec validation, and the complete repository gate. + +Rollback restores the previous generated workflow, cargo-dist version, npm provenance checks, and lockfile. No published artifact is modified. + +## Open Questions + +None. diff --git a/openspec/changes/archive/2026-10-02-harden-release-pipeline/proposal.md b/openspec/changes/archive/2026-10-02-harden-release-pipeline/proposal.md new file mode 100644 index 0000000..bb1508f --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-release-pipeline/proposal.md @@ -0,0 +1,26 @@ +## Why + +Cadder's release automation grants repository write access to build jobs and interpolates release refs into shell programs, while npm assembly accepts attestations that are not tied to the selected release identity. Public artifacts need least-privilege construction and exact provenance without replacing cargo-dist as the release owner. + +## What Changes + +- Keep cargo-dist as the release generator, update it to 0.33.0, and apply one deterministic Cadder hardening pass to the generated GitHub workflow. +- Default release permissions to read-only, with write and attestation permissions only on publishing jobs. +- Pass release tags through validated environment values instead of embedding GitHub context expressions in shell source. +- Check out the selected npm release tag and bind artifact attestation verification to its source ref, commit digest, repository, and release workflow. +- Refresh the documentation lockfile so the vulnerable transitive `devalue` 5.9.2 is replaced by at least 5.9.4. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `quality-tooling`: Generated release automation receives a focused, verified least-privilege hardening pass. +- `distribution-and-upgrades`: npm packages consume artifacts proven to belong to the exact selected Cadder release. + +## Impact + +This change affects cargo-dist configuration and generated workflow verification, the npm release workflow and assembly script, release-focused tests, and the documentation dependency lockfile. It does not publish a release, create a tag, change package versions, or alter runtime behavior. diff --git a/openspec/changes/archive/2026-10-02-harden-release-pipeline/release.md b/openspec/changes/archive/2026-10-02-harden-release-pipeline/release.md new file mode 100644 index 0000000..61dfc9b --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-release-pipeline/release.md @@ -0,0 +1,16 @@ +--- +impact: patch +components: + - quality-tooling + - distribution-and-upgrades +audiences: + - maintainers +observable_impact: maintenance +changelog: omit +--- + +## Changed + +### Harden release credentials and artifact provenance + +Release builds now use least-privilege GitHub permissions and validated tag data, while npm assembly accepts only assets attested for the exact selected release commit by Cadder's release workflow. diff --git a/openspec/changes/archive/2026-10-02-harden-release-pipeline/specs/distribution-and-upgrades/spec.md b/openspec/changes/archive/2026-10-02-harden-release-pipeline/specs/distribution-and-upgrades/spec.md new file mode 100644 index 0000000..4cf792a --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-release-pipeline/specs/distribution-and-upgrades/spec.md @@ -0,0 +1,18 @@ +## MODIFIED Requirements + +### Requirement: DIST-002: Archives are portable and verifiable +Each cargo-dist archive MUST contain exactly the three expected executables, README, changelog, Apache-2.0 license, and sample configuration and MUST have a SHA-256 checksum. + +Before publication, each archive MUST be extracted into a fresh directory outside the source checkout on its native operating system. The verifier MUST check the checksum, exact file set, executable permissions where applicable, and successful `--version` and `--help` behavior for all three executables. Published archives, checksums, source archive, cargo-dist manifest MUST carry GitHub artifact attestations from the release workflow. A downstream package workflow MUST bind attestation verification to the selected tag ref, its exact source commit, the Cadder repository, and that signer workflow. + +#### Scenario: User downloads a release +- **WHEN** an archive and checksum are obtained from one release +- **THEN** the checksum can be verified before extraction without an installer +- **AND** a GitHub attestation can associate the asset with the exact release source and workflow + +#### Scenario: Release archive is verified +- **WHEN** a release archive is evaluated before publication or downstream packaging +- **THEN** only the accepted binaries and static release files are present +- **AND** each executable reports the planned version and exposes help outside the source checkout +- **AND** Unix executables retain their executable permissions +- **AND** downstream verification rejects an attestation for a different ref, commit, repository, or signer workflow diff --git a/openspec/changes/archive/2026-10-02-harden-release-pipeline/specs/quality-tooling/spec.md b/openspec/changes/archive/2026-10-02-harden-release-pipeline/specs/quality-tooling/spec.md new file mode 100644 index 0000000..23be8cc --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-release-pipeline/specs/quality-tooling/spec.md @@ -0,0 +1,59 @@ +## MODIFIED Requirements + +### Requirement: QT-003: Maintained tools own validation and release formats +Cargo SHALL own Rust formatting, linting, builds, and tests; `cargo-llvm-cov` SHALL own coverage calculation and the configured threshold; the official OpenSpec CLI SHALL own specification validation; npm and Astro SHALL own documentation dependency and build checks; and `cargo-dist` SHALL own release planning, portable archives, included release files, SHA-256 checksums, and generated GitHub Release automation. + +Cadder MAY apply one deterministic, focused postprocessor to cargo-dist's generated workflow only for security invariants that cargo-dist cannot express. The adapter MUST fail when its expected generated structure changes, MUST be verified by the supported repository task surface, and MUST NOT recreate release planning, artifact construction, checksums, or publication policy. + +Cadder-specific executable behavior MUST be verified by tests in the package that owns the executable. Repository checks that only restate a native manifest, generated release plan, or accepted OpenSpec declaration MUST NOT be retained as independent policy engines. + +#### Scenario: Complete repository gate +- **WHEN** a contributor or CI runs the complete supported check task +- **THEN** each required validation runs through its owning maintained tool or focused product test +- **AND** a failure identifies the owning validation boundary + +#### Scenario: Portable release is planned +- **WHEN** release automation plans a Cadder version +- **THEN** `cargo-dist` describes one portable application for every supported target with the accepted binaries, included files, and SHA-256 checksums +- **AND** the committed workflow equals cargo-dist's generated output after the focused security hardening pass + +### Requirement: QT-004: Local and CI task parity +Continuous integration SHALL invoke the same supported task definitions used locally for platform-independent repository validation. Platform-specific jobs MAY add only the runner, target, permissions, or external service evidence required by their operating-system contract. + +Release pull requests MUST build and upload the complete cargo-dist artifact plan without publishing a release. Planning and artifact-build jobs MUST have read-only repository permissions and MUST NOT receive a publication token. Release tag values MUST be validated as data outside generated shell source. Release publication MUST remain separate from general validation, MUST use the source revision and artifact plan accepted by the release gate, MUST verify the exact tagged archives on their native operating-system runners before announce, and MUST grant write permission only to the stages that attest or publish immutable release assets. + +#### Scenario: Pull request validation +- **WHEN** a pull request runs repository validation +- **THEN** CI installs the pinned project environment and invokes the documented `mise run` tasks +- **AND** the jobs do not receive release publication credentials + +#### Scenario: Release candidate pull request +- **WHEN** cargo-dist evaluates a release pull request +- **THEN** it builds and uploads the complete portable artifact set for inspection with read-only repository access +- **AND** it does not create or modify a public GitHub Release + +#### Scenario: Platform-specific evidence +- **WHEN** a requirement needs Windows, Linux, macOS, or Docker evidence +- **THEN** CI runs the focused task on the required runner or service +- **AND** the platform job does not introduce an alternative repository task implementation + +#### Scenario: Tagged release publication +- **WHEN** a validated supported release tag is built +- **THEN** every target archive is verified on its native runner from a fresh directory outside the checkout +- **AND** GitHub Release publication waits for all verification jobs to succeed and receives write permission only in the publishing path + +### Requirement: QT-007: npm publication uses staged trusted publishing +Cadder npm publication SHALL use npm trusted publishing from the exact GitHub-hosted workflow and protected release environment through short-lived OIDC credentials. The trusted publisher MUST allow staged publishing only, package publishing access MUST disallow traditional tokens, and no long-lived npm publish credential may be stored in the repository or GitHub Actions. + +The workflow MUST stage packages only after it verifies the corresponding GitHub Release assets, SHA-256 checksums, and attestations. Every accepted asset attestation MUST identify the selected release tag, its exact source commit, and Cadder's release workflow as signer. npm provenance MUST identify the public repository and publishing workflow. A maintainer MUST review and approve each stage with 2FA, approving all platform packages before the root package. + +#### Scenario: Automated staging +- **WHEN** a verified tagged release reaches the npm workflow +- **THEN** GitHub Actions checks out that exact tag and verifies every consumed asset against its ref, commit digest, repository, and release workflow +- **AND** it obtains a short-lived OIDC publishing identity and stages rather than directly publishes all version-matched packages +- **AND** no npm access token is available to the job + +#### Scenario: Human publication approval +- **WHEN** the staged package set is ready for publication +- **THEN** a maintainer reviews the staged artifacts and approves them with 2FA +- **AND** the root package cannot become public before every referenced platform package diff --git a/openspec/changes/archive/2026-10-02-harden-release-pipeline/tasks.md b/openspec/changes/archive/2026-10-02-harden-release-pipeline/tasks.md new file mode 100644 index 0000000..499ddb2 --- /dev/null +++ b/openspec/changes/archive/2026-10-02-harden-release-pipeline/tasks.md @@ -0,0 +1,15 @@ +## 1. Generated release workflow + +- [x] 1.1 Update cargo-dist to 0.33.0 and regenerate its official GitHub workflow. (verification: cargo-dist planning succeeds on the updated pinned tool) +- [x] 1.2 Add and test the deterministic workflow postprocessor for least-privilege permissions and validated tag data. (verification: apply and check modes accept the committed workflow and reject each missing invariant) +- [x] 1.3 Route the supported mise release and complete-check tasks through generated-then-hardened workflow verification. (verification: local and CI task definitions use the same focused check) + +## 2. Exact npm release provenance + +- [x] 2.1 Check out the selected release tag and resolve its exact commit before downloading assets. (verification: workflow structure tests require the exact ref and exported commit) +- [x] 2.2 Bind each artifact attestation to the selected ref, commit digest, repository, and release workflow. (verification: assembly tests require every provenance argument and reject missing or mismatched identity) +- [x] 2.3 Refresh the documentation lockfile so `devalue` resolves to at least 5.9.4 without upgrading direct documentation dependencies. (verification: npm audit passes and the vulnerable lock entry is absent) + +## 3. Complete validation + +- [x] 3.1 Run workflow, npm, cargo-dist, OpenSpec, audit, and complete repository gates, then review the full diff and working tree. (verification: all applicable gates pass with no publication or unrelated files) diff --git a/openspec/specs/caddy-runtime/spec.md b/openspec/specs/caddy-runtime/spec.md index 7aa8f5c..78b89a6 100644 --- a/openspec/specs/caddy-runtime/spec.md +++ b/openspec/specs/caddy-runtime/spec.md @@ -25,3 +25,21 @@ A desired-state mutation MUST publish only after Caddy accepts the candidate con #### Scenario: Persistence fails after apply - **WHEN** Caddy accepted a candidate but SQLite cannot commit it - **THEN** Cadder rolls Caddy back and keeps the previous authoritative state + +### Requirement: CADDY-004: Owned listeners and routes remain local +Cadder SHALL bind its owned HTTP and HTTPS servers only to IPv4 and IPv6 loopback addresses on the existing ports. Each registration's complete adapted route tree MUST remain behind an outer matcher containing only that registration's active canonical hosts, and project input MUST NOT widen either boundary. + +#### Scenario: Remote peer addresses the developer host +- **WHEN** a peer connects through a non-loopback interface and supplies an active `.localhost` host header +- **THEN** no Cadder-owned HTTP or HTTPS listener accepts the connection + +#### Scenario: Adapted route contains a hostless sibling +- **WHEN** one retained branch matches an active host and a sibling branch has no host matcher +- **THEN** the complete route tree remains reachable only under the registration's active canonical hosts + +### Requirement: CADDY-005: Project configuration adaptation is bounded +Cadder MUST capture at most 32 MiB from each `caddy adapt` output stream, reject partial adaptation output when either limit is exceeded, and retain bounded cleanup for any adapter process tree that remains active. + +#### Scenario: Adapter exceeds an output limit +- **WHEN** `caddy adapt` writes more than 32 MiB to stdout or stderr +- **THEN** Cadder reports a bounded failure without applying configuration and cleans up the owned adapter process tree if it remains active diff --git a/openspec/specs/daemon-lifecycle/spec.md b/openspec/specs/daemon-lifecycle/spec.md index c4365c3..69a0e2f 100644 --- a/openspec/specs/daemon-lifecycle/spec.md +++ b/openspec/specs/daemon-lifecycle/spec.md @@ -13,11 +13,11 @@ Define singleton ownership, startup, and bounded shutdown for one installation r - **THEN** exactly one process becomes the daemon and the other observes its readiness ### Requirement: RUN-002: Managed run may start the daemon -When attachment reports that no daemon is running, supported `caddy run` MUST launch the version-matched sibling `cadderd`, poll the exact handshake to readiness, and retry attachment. +When attachment reports that no daemon is running, supported `caddy run` MUST launch the version-matched sibling `cadderd`, poll the exact handshake to readiness, and retry attachment. Automatic managed startup MUST NOT discover `cadderd` through PATH. An explicit daemon path MAY remain available to focused tests and foreground diagnostics. #### Scenario: Startup fails -- **WHEN** the sibling daemon cannot become ready within the bounded deadline -- **THEN** the shim reports actionable diagnostics and never delegates an unmanaged run +- **WHEN** the sibling daemon cannot be found or become ready within the bounded deadline +- **THEN** the shim reports actionable diagnostics and never launches an unrelated PATH executable or delegates an unmanaged run ### Requirement: RUN-003: Shutdown is bounded and owned Shutdown SHALL stop accepting work, drain or revoke owned operations, close SQLite, terminate only the Cadder-owned Caddy child, and release the endpoint within bounded phase deadlines. diff --git a/openspec/specs/distribution-and-upgrades/spec.md b/openspec/specs/distribution-and-upgrades/spec.md index 57bed3e..d5b50b5 100644 --- a/openspec/specs/distribution-and-upgrades/spec.md +++ b/openspec/specs/distribution-and-upgrades/spec.md @@ -13,18 +13,19 @@ Cadder SHALL version and release the `cadder`, `cadderd`, and `caddy` executable ### Requirement: DIST-002: Archives are portable and verifiable Each cargo-dist archive MUST contain exactly the three expected executables, README, changelog, Apache-2.0 license, and sample configuration and MUST have a SHA-256 checksum. -Before publication, each archive MUST be extracted into a fresh directory outside the source checkout on its native operating system. The verifier MUST check the checksum, exact file set, executable permissions where applicable, and successful `--version` and `--help` behavior for all three executables. Published archives, checksums, source archive, and cargo-dist manifest MUST carry GitHub artifact attestations from the release workflow. +Before publication, each archive MUST be extracted into a fresh directory outside the source checkout on its native operating system. The verifier MUST check the checksum, exact file set, executable permissions where applicable, and successful `--version` and `--help` behavior for all three executables. Published archives, checksums, source archive, cargo-dist manifest MUST carry GitHub artifact attestations from the release workflow. A downstream package workflow MUST bind attestation verification to the selected tag ref, its exact source commit, the Cadder repository, and that signer workflow. #### Scenario: User downloads a release - **WHEN** an archive and checksum are obtained from one release - **THEN** the checksum can be verified before extraction without an installer -- **AND** a GitHub attestation can associate the asset with the release workflow +- **AND** a GitHub attestation can associate the asset with the exact release source and workflow #### Scenario: Release archive is verified -- **WHEN** a release archive is evaluated before publication +- **WHEN** a release archive is evaluated before publication or downstream packaging - **THEN** only the accepted binaries and static release files are present - **AND** each executable reports the planned version and exposes help outside the source checkout - **AND** Unix executables retain their executable permissions +- **AND** downstream verification rejects an attestation for a different ref, commit, repository, or signer workflow ### Requirement: DIST-003: Upgrades replace the coherent executable set Public guidance MUST instruct the user to stop through the TUI, replace all three executables from one release, and restart through managed run or the TUI. diff --git a/openspec/specs/observability/spec.md b/openspec/specs/observability/spec.md index e641255..35d669f 100644 --- a/openspec/specs/observability/spec.md +++ b/openspec/specs/observability/spec.md @@ -6,11 +6,11 @@ Define bounded, redacted diagnostic logs exposed through the operator CLI. ## Requirements ### Requirement: OBS-001: Redaction precedes persistence and response -Cadder MUST redact credentials and sensitive values before a log reaches SQLite or an IPC response. +Cadder MUST redact authorization and cookie header values, token and password values in supported text, JSON, and URL query forms, and private-key blocks before a log reaches SQLite or an IPC response. Retained data SHALL use one stable redaction marker and MUST NOT preserve any part of the matched credential value. -#### Scenario: Token-like value appears -- **WHEN** a log contains a token, password, cookie, authorization header, or private key -- **THEN** the retained value contains a stable redaction marker +#### Scenario: Documented credential form appears +- **WHEN** a log contains an authorization header, cookie, token, password, or private key +- **THEN** the retained value contains the stable redaction marker instead of the credential value ### Requirement: OBS-002: Log retention is deterministic The runtime SHALL retain at most 1,000 events per canonical stream and 5,000 events globally, deleting the oldest excess within the insertion transaction. @@ -25,3 +25,10 @@ A query MUST select one runtime, entrypoint, or domain stream and return at most #### Scenario: A diagnostic client requests logs - **WHEN** a client requests a limit within 1 through 200 for one canonical stream - **THEN** the daemon returns the newest redacted rows in stable ascending order + +### Requirement: OBS-004: Terminal rendering is control-safe +The operator CLI MUST neutralize ANSI escape sequences and C0 or C1 control characters in diagnostic and log messages before writing them to an interactive terminal. Redacted retained log content SHALL otherwise remain unchanged. + +#### Scenario: Diagnostic contains terminal controls +- **WHEN** a retained log or diagnostic message contains an ANSI sequence or another C0 or C1 control character +- **THEN** the CLI renders the message without executing or forwarding that control sequence diff --git a/openspec/specs/quality-tooling/spec.md b/openspec/specs/quality-tooling/spec.md index 9619b03..647d95e 100644 --- a/openspec/specs/quality-tooling/spec.md +++ b/openspec/specs/quality-tooling/spec.md @@ -36,6 +36,8 @@ Tasks MUST remain small adapters to an owning tool. The repository MUST NOT add ### Requirement: QT-003: Maintained tools own validation and release formats Cargo SHALL own Rust formatting, linting, builds, and tests; `cargo-llvm-cov` SHALL own coverage calculation and the configured threshold; the official OpenSpec CLI SHALL own specification validation; npm and Astro SHALL own documentation dependency and build checks; and `cargo-dist` SHALL own release planning, portable archives, included release files, SHA-256 checksums, and generated GitHub Release automation. +Cadder MAY apply one deterministic, focused postprocessor to cargo-dist's generated workflow only for security invariants that cargo-dist cannot express. The adapter MUST fail when its expected generated structure changes, MUST be verified by the supported repository task surface, and MUST NOT recreate release planning, artifact construction, checksums, or publication policy. + Cadder-specific executable behavior MUST be verified by tests in the package that owns the executable. Repository checks that only restate a native manifest, generated release plan, or accepted OpenSpec declaration MUST NOT be retained as independent policy engines. #### Scenario: Complete repository gate @@ -46,12 +48,12 @@ Cadder-specific executable behavior MUST be verified by tests in the package tha #### Scenario: Portable release is planned - **WHEN** release automation plans a Cadder version - **THEN** `cargo-dist` describes one portable application for every supported target with the accepted binaries, included files, and SHA-256 checksums -- **AND** no Cadder-owned archive or checksum implementation is invoked +- **AND** the committed workflow equals cargo-dist's generated output after the focused security hardening pass ### Requirement: QT-004: Local and CI task parity Continuous integration SHALL invoke the same supported task definitions used locally for platform-independent repository validation. Platform-specific jobs MAY add only the runner, target, permissions, or external service evidence required by their operating-system contract. -Release pull requests MUST build and upload the complete cargo-dist artifact plan without publishing a release. Release publication MUST remain separate from general validation, MUST use the source revision and artifact plan accepted by the release gate, MUST verify the exact tagged archives on their native operating-system runners before announce, and MUST grant write permission only to the stages that attest or publish immutable release assets. +Release pull requests MUST build and upload the complete cargo-dist artifact plan without publishing a release. Planning and artifact-build jobs MUST have read-only repository permissions and MUST NOT receive a publication token. Release tag values MUST be validated as data outside generated shell source. Release publication MUST remain separate from general validation, MUST use the source revision and artifact plan accepted by the release gate, MUST verify the exact tagged archives on their native operating-system runners before announce, and MUST grant write permission only to the stages that attest or publish immutable release assets. #### Scenario: Pull request validation - **WHEN** a pull request runs repository validation @@ -60,7 +62,7 @@ Release pull requests MUST build and upload the complete cargo-dist artifact pla #### Scenario: Release candidate pull request - **WHEN** cargo-dist evaluates a release pull request -- **THEN** it builds and uploads the complete portable artifact set for inspection +- **THEN** it builds and uploads the complete portable artifact set for inspection with read-only repository access - **AND** it does not create or modify a public GitHub Release #### Scenario: Platform-specific evidence @@ -69,9 +71,9 @@ Release pull requests MUST build and upload the complete cargo-dist artifact pla - **AND** the platform job does not introduce an alternative repository task implementation #### Scenario: Tagged release publication -- **WHEN** a supported release tag is built +- **WHEN** a validated supported release tag is built - **THEN** every target archive is verified on its native runner from a fresh directory outside the checkout -- **AND** GitHub Release publication waits for all verification jobs to succeed +- **AND** GitHub Release publication waits for all verification jobs to succeed and receives write permission only in the publishing path ### Requirement: QT-005: Evidence-gated task-runner removal The `xtask` package and command surface SHALL be removed only after every retained responsibility is mapped to a maintained tool, a focused owning-package test, or an explicit accepted removal rationale. @@ -101,20 +103,17 @@ On every supported native runner, the gate MUST install locally packed packages - **AND** unexpected files, lifecycle scripts, version drift, or launcher recursion fail the gate before registry staging ### Requirement: QT-007: npm publication uses staged trusted publishing - Cadder npm publication SHALL use npm trusted publishing from the exact GitHub-hosted workflow and protected release environment through short-lived OIDC credentials. The trusted publisher MUST allow staged publishing only, package publishing access MUST disallow traditional tokens, and no long-lived npm publish credential may be stored in the repository or GitHub Actions. -The workflow MUST stage packages only after it verifies the corresponding GitHub Release assets, SHA-256 checksums, and attestations. npm provenance MUST identify the public repository and publishing workflow. A maintainer MUST review and approve each stage with 2FA, approving all platform packages before the root package. +The workflow MUST stage packages only after it verifies the corresponding GitHub Release assets, SHA-256 checksums, and attestations. Every accepted asset attestation MUST identify the selected release tag, its exact source commit, and Cadder's release workflow as signer. npm provenance MUST identify the public repository and publishing workflow. A maintainer MUST review and approve each stage with 2FA, approving all platform packages before the root package. #### Scenario: Automated staging - - **WHEN** a verified tagged release reaches the npm workflow -- **THEN** GitHub Actions obtains a short-lived OIDC publishing identity -- **AND** it stages rather than directly publishes all version-matched packages +- **THEN** GitHub Actions checks out that exact tag and verifies every consumed asset against its ref, commit digest, repository, and release workflow +- **AND** it obtains a short-lived OIDC publishing identity and stages rather than directly publishes all version-matched packages - **AND** no npm access token is available to the job #### Scenario: Human publication approval - - **WHEN** the staged package set is ready for publication - **THEN** a maintainer reviews the staged artifacts and approves them with 2FA - **AND** the root package cannot become public before every referenced platform package diff --git a/releases/1.0.1.yaml b/releases/1.0.1.yaml new file mode 100644 index 0000000..bbd99e2 --- /dev/null +++ b/releases/1.0.1.yaml @@ -0,0 +1,5 @@ +version: 1.0.1 +date: 2026-10-03 +changes: + - harden-local-runtime-boundaries + - harden-release-pipeline diff --git a/scripts/harden-dist-workflow.mjs b/scripts/harden-dist-workflow.mjs new file mode 100644 index 0000000..c4d4cd2 --- /dev/null +++ b/scripts/harden-dist-workflow.mjs @@ -0,0 +1,227 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { readFile, writeFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const projectDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const workflowPath = resolve(projectDirectory, '.github', 'workflows', 'release.yml'); + +function lines(...values) { + return values.join('\n'); +} + +function replaceOnce(source, expected, replacement, label) { + const first = source.indexOf(expected); + assert.notEqual(first, -1, `cargo-dist output is missing the expected ${label} fragment`); + assert.equal( + source.indexOf(expected, first + expected.length), + -1, + `cargo-dist output contains more than one ${label} fragment`, + ); + return `${source.slice(0, first)}${replacement}${source.slice(first + expected.length)}`; +} + +export function hardenGeneratedWorkflow(generated) { + let source = replaceOnce( + generated, + lines('permissions:', ' "contents": "write"'), + lines('permissions:', ' "contents": "read"'), + 'root permission', + ); + source = replaceOnce( + source, + lines( + ' outputs:', + ' val: ${{ steps.plan.outputs.manifest }}', + " tag: ${{ !github.event.pull_request && github.ref_name || '' }}", + " tag-flag: ${{ !github.event.pull_request && format('--tag={0}', github.ref_name) || '' }}", + ' publishing: ${{ !github.event.pull_request }}', + ' env:', + ' GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}', + ), + lines( + ' outputs:', + ' val: ${{ steps.plan.outputs.manifest }}', + ' tag: ${{ steps.plan.outputs.tag }}', + ' publishing: ${{ !github.event.pull_request }}', + ' env:', + " RELEASE_TAG: ${{ !github.event.pull_request && github.ref_name || '' }}", + ), + 'plan outputs and environment', + ); + source = replaceOnce( + source, + lines( + ' - id: plan', + ' run: |', + " dist ${{ (!github.event.pull_request && format('host --steps=create --tag={0}', github.ref_name)) || 'plan' }} --output-format=json > plan-dist-manifest.json", + ' echo "dist ran successfully"', + ' cat plan-dist-manifest.json', + ' echo "manifest=$(jq -c "." plan-dist-manifest.json)" >> "$GITHUB_OUTPUT"', + ), + lines( + ' - id: plan', + ' shell: bash', + ' run: |', + ' if [[ -n "$RELEASE_TAG" ]]; then', + ' if [[ ! "$RELEASE_TAG" =~ ^v(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?(\\+[0-9A-Za-z.-]+)?$ ]]; then', + ' echo "Invalid Cadder release tag: $RELEASE_TAG" >&2', + ' exit 1', + ' fi', + ' dist host --allow-dirty --steps=create --tag "$RELEASE_TAG" --output-format=json > plan-dist-manifest.json', + ' else', + ' dist plan --allow-dirty --output-format=json > plan-dist-manifest.json', + ' fi', + ' echo "dist ran successfully"', + ' cat plan-dist-manifest.json', + ' echo "tag=$RELEASE_TAG" >> "$GITHUB_OUTPUT"', + ' echo "manifest=$(jq -c "." plan-dist-manifest.json)" >> "$GITHUB_OUTPUT"', + ), + 'plan command', + ); + source = replaceOnce( + source, + lines( + ' env:', + ' GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}', + " BUILD_MANIFEST_NAME: target/distrib/${{ join(matrix.targets, '-') }}-dist-manifest.json", + ), + lines( + ' env:', + ' RELEASE_TAG: ${{ needs.plan.outputs.tag }}', + " BUILD_MANIFEST_NAME: target/distrib/${{ join(matrix.targets, '-') }}-dist-manifest.json", + ), + 'local build environment', + ); + source = replaceOnce( + source, + lines( + ' - name: Build artifacts', + ' run: |', + ' # Actually do builds and make zips and whatnot', + ' dist build ${{ needs.plan.outputs.tag-flag }} --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json', + ' echo "dist ran successfully"', + ), + lines( + ' - name: Build artifacts', + ' shell: bash', + ' run: |', + ' # Actually do builds and make zips and whatnot', + ' tag_args=()', + ' if [[ -n "$RELEASE_TAG" ]]; then tag_args=(--tag "$RELEASE_TAG"); fi', + ' dist build --allow-dirty "${tag_args[@]}" --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json', + ' echo "dist ran successfully"', + ), + 'local build command', + ); + source = replaceOnce( + source, + lines( + ' env:', + ' GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}', + ' BUILD_MANIFEST_NAME: target/distrib/global-dist-manifest.json', + ), + lines( + ' env:', + ' RELEASE_TAG: ${{ needs.plan.outputs.tag }}', + ' BUILD_MANIFEST_NAME: target/distrib/global-dist-manifest.json', + ), + 'global build environment', + ); + source = replaceOnce( + source, + ' dist build ${{ needs.plan.outputs.tag-flag }} --output-format=json "--artifacts=global" > dist-manifest.json', + lines( + ' tag_args=()', + ' if [[ -n "$RELEASE_TAG" ]]; then tag_args=(--tag "$RELEASE_TAG"); fi', + ' dist build --allow-dirty "${tag_args[@]}" --output-format=json "--artifacts=global" > dist-manifest.json', + ), + 'global build command', + ); + source = replaceOnce( + source, + lines(' env:', ' GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}', ' runs-on: "ubuntu-22.04"'), + lines(' env:', ' RELEASE_TAG: ${{ needs.plan.outputs.tag }}', ' runs-on: "ubuntu-22.04"'), + 'host environment', + ); + source = replaceOnce( + source, + ' dist host ${{ needs.plan.outputs.tag-flag }} --steps=upload --steps=release --output-format=json > dist-manifest.json', + ' dist host --allow-dirty --tag "$RELEASE_TAG" --steps=upload --steps=release --output-format=json > dist-manifest.json', + 'host command', + ); + source = replaceOnce( + source, + ' RELEASE_COMMIT: "${{ github.sha }}"', + lines( + ' RELEASE_COMMIT: "${{ github.sha }}"', + ' RELEASE_TAG: "${{ needs.plan.outputs.tag }}"', + ), + 'announce environment', + ); + source = replaceOnce( + source, + ' gh release create "${{ needs.plan.outputs.tag }}" --target "$RELEASE_COMMIT" $PRERELEASE_FLAG --title "$ANNOUNCEMENT_TITLE" --notes-file "$RUNNER_TEMP/notes.txt" artifacts/*', + ' gh release create "$RELEASE_TAG" --target "$RELEASE_COMMIT" $PRERELEASE_FLAG --title "$ANNOUNCEMENT_TITLE" --notes-file "$RUNNER_TEMP/notes.txt" artifacts/*', + 'announce command', + ); + validateHardenedWorkflow(source); + return source; +} + +export function validateHardenedWorkflow(source) { + assert.match(source, /permissions:\n "contents": "read"/); + assert.equal(source.match(/GH_TOKEN: \$\{\{ secrets\.GITHUB_TOKEN \}\}/g)?.length, 1); + assert.equal(source.match(/"contents": "write"/g)?.length, 1); + assert.equal(source.match(/github\.ref_name/g)?.length, 1); + assert.doesNotMatch(source, /tag-flag/); + assert.doesNotMatch(source, /run:[^]*?github\.ref_name/); + assert.equal(source.match(/dist (?:plan|build|host) --allow-dirty/g)?.length, 5); + assert.match(source, /RELEASE_TAG: \$\{\{ needs\.plan\.outputs\.tag \}\}/); + assert.match(source, /gh release create "\$RELEASE_TAG"/); + assert.match(source, /if \[\[ ! "\$RELEASE_TAG" =~ \^v/); +} + +async function apply() { + const generated = await readFile(workflowPath, 'utf8'); + await writeFile(workflowPath, hardenGeneratedWorkflow(generated), 'utf8'); +} + +async function checkGenerated() { + const committed = await readFile(workflowPath); + try { + const result = spawnSync('dist', ['generate', '--mode', 'ci'], { + cwd: projectDirectory, + encoding: 'utf8', + shell: false, + }); + if (result.error) throw result.error; + if (result.status !== 0) { + throw new Error(`dist generate failed with status ${result.status}: ${result.stderr}`); + } + const generated = await readFile(workflowPath, 'utf8'); + const expected = Buffer.from(hardenGeneratedWorkflow(generated), 'utf8'); + assert.deepEqual( + committed, + expected, + 'release.yml differs from cargo-dist output after the required security hardening pass', + ); + } finally { + await writeFile(workflowPath, committed); + } +} + +if (resolve(process.argv[1] ?? '') === fileURLToPath(import.meta.url)) { + const mode = process.argv[2]; + const operation = mode === '--apply' ? apply : mode === '--check-generated' ? checkGenerated : null; + if (!operation) { + process.stderr.write('usage: node scripts/harden-dist-workflow.mjs --apply|--check-generated\n'); + process.exitCode = 2; + } else { + operation().catch((error) => { + process.stderr.write(`${error.stack ?? error}\n`); + process.exitCode = 1; + }); + } +} diff --git a/scripts/test/harden-dist-workflow.test.mjs b/scripts/test/harden-dist-workflow.test.mjs new file mode 100644 index 0000000..f5de99d --- /dev/null +++ b/scripts/test/harden-dist-workflow.test.mjs @@ -0,0 +1,49 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import test from 'node:test'; + +import { validateHardenedWorkflow } from '../harden-dist-workflow.mjs'; + +const workflowPath = resolve('.github', 'workflows', 'release.yml'); + +test('accepts the committed hardened release workflow', async () => { + validateHardenedWorkflow(await readFile(workflowPath, 'utf8')); +}); + +test('rejects repository write permission at the workflow root', async () => { + const source = (await readFile(workflowPath, 'utf8')).replace( + 'permissions:\n "contents": "read"', + 'permissions:\n "contents": "write"', + ); + assert.throws(() => validateHardenedWorkflow(source)); +}); + +test('rejects publication tokens outside the announce job', async () => { + const source = `${await readFile(workflowPath, 'utf8')}\nGH_TOKEN: \${{ secrets.GITHUB_TOKEN }}\n`; + assert.throws(() => validateHardenedWorkflow(source)); +}); + +test('rejects direct release-tag interpolation in shell source', async () => { + const source = (await readFile(workflowPath, 'utf8')).replace( + 'gh release create "$RELEASE_TAG"', + 'gh release create "${{ github.ref_name }}"', + ); + assert.throws(() => validateHardenedWorkflow(source)); +}); + +test('rejects missing release-tag validation', async () => { + const source = (await readFile(workflowPath, 'utf8')).replace( + 'if [[ ! "$RELEASE_TAG" =~ ^v', + 'if [[ "$RELEASE_TAG" =~ ^v', + ); + assert.throws(() => validateHardenedWorkflow(source)); +}); + +test('rejects cargo-dist commands without the reviewed workflow override', async () => { + const source = (await readFile(workflowPath, 'utf8')).replace( + 'dist plan --allow-dirty', + 'dist plan', + ); + assert.throws(() => validateHardenedWorkflow(source)); +});