From 203ec2d4d87414f93d754f6dddacd94ddccf0029 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:19:56 -0600 Subject: [PATCH 1/6] test(db): pin merged migration digests so edits to applied versions fail --- crates/twigpine-node/src/db/mod.rs | 261 +++++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index cb6a59f0..e90a22fa 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -12673,6 +12673,267 @@ impl Db { mod migration_tests { use super::{MIGRATIONS, MIGRATION_V1_NAME}; + /// SHA-256 over a migration's version, name and statements, NUL-separated. + fn migration_digest(m: &super::Migration) -> String { + use sha2::{Digest, Sha256}; + let mut h = Sha256::new(); + h.update(m.version.to_le_bytes()); + h.update(m.name.as_bytes()); + for stmt in m.stmts { + h.update([0u8]); + h.update(stmt.as_bytes()); + } + hex::encode(h.finalize()) + } + + /// Digest of every merged migration. Operators deploy from main and the runner + /// skips a version it has already recorded, so an edit to a merged entry never + /// reaches an existing node while a fresh test database applies it: CI stays + /// green and deployments diverge. Change a schema by appending a new version. + /// Add a row here only for a NEW migration; changing an existing row's digest + /// is the edit this test exists to stop. + const MERGED_MIGRATION_DIGESTS: &[(i64, &str)] = &[ + ( + 1, + "c4e8536e1d00f04568c9fa32ac8b92385e997f8af7ce4384b1fbdf323bea8bab", + ), + ( + 2, + "8b81c534a91c170dff24956eeb5740a60ac3cc0e17917f883381712085c9eb91", + ), + ( + 3, + "67612684736b25840535bed3b9f63a4aba007e9b7ed0128356c9ecd6ed4df72c", + ), + ( + 4, + "9c1fed237f918b90520937c8e117c3298604e391f0d776f8b7b14d7c814e8473", + ), + ( + 5, + "44037047c6f55d625c506716d322339242b8ba3d305a5754b49e489a5acddac0", + ), + ( + 6, + "588779247289421096efd27f30cd77222590ae048cbd0557c3ce4b68f6d5260f", + ), + ( + 7, + "3a3aeefe2c8b78655c67eca27c94ca5ee8e3847ab412d02f006a4ce50f149d46", + ), + ( + 8, + "46cbf40d546fd119cc69300d092232eb6c193fa1e1fba4ebbc0ceed21bd16084", + ), + ( + 9, + "4d4f4fe78f71da77582e70776debdb5910404c040eb64bd9e24e2e7bde15f3aa", + ), + ( + 10, + "e091d7b3f3d6628914ee1d6a479b098d1c1d56392fadee7f612bf4060a77493a", + ), + ( + 11, + "bd54dd6a8db326dd4808ba3d788af479a2f812aeed6855ab819193e1fc440725", + ), + ( + 16, + "edd64a7f16030955806c9e1e1ea81a158c3c74268cda4daac84e861e195c35f5", + ), + ( + 17, + "1092ee4fed3fa435851684332a0f6a43a70462bcb2ea2eae574aac57182e6a47", + ), + ( + 18, + "e641c11ebbc564d87f9713e82d90c19199c297de6c961d99c6aa6b35d3e713e2", + ), + ( + 19, + "285be59c43dc1225ae7476b8c26e399b191fc54291df567cafcca4495fc1ad1e", + ), + ( + 20, + "e10ba674ae5ff23ec0777a4f27cc713c382b57b911dabe825d8f5684dbec5412", + ), + ( + 21, + "cce72a34aa56c4820d365fd12b546882f875c9bd4e8cb2df22bd7c78ee90d6f5", + ), + ( + 22, + "6a9561aa9d5e22c4519a0e5bcf1f4d89505508df7eed9502d00ab2094438dad3", + ), + ( + 23, + "1d5eb714e41f63474abd139b32d40ceb81fdaa28f9e6f45cff4a67e882344684", + ), + ( + 24, + "8ab6132a35a616f5791eb6480e4553dd29fd3d9f46124f832e214e129cd4e485", + ), + ( + 25, + "068686142daa7a9e0b008c3961c82a44aad8e976afb5bce58a0849568672ab13", + ), + ( + 26, + "ac4c7ae387d580be1f7740e1f3cd7c804bc4a2f18907b99f910d8db0633542ff", + ), + ( + 27, + "5c33888712d5dd1ebb8cdc383bb3e53b8a19d5c4b8ea11d5b80a727ad326a25a", + ), + ( + 28, + "9e7f22e7d469ded905e4da81dc04b568bff834b0d0f2313c6f1fd37698dffe78", + ), + ( + 29, + "b270bc1b03da34c4959a68bc67389dc3c138967cc2b513943e9e984e08773a14", + ), + ( + 30, + "28eac367a1fbbfb03f23dfe3f4ad42a5d3aec2dbf6e8f9eb003a38c0043c0b34", + ), + ( + 31, + "f338852189ace3d09690ddee0cff59002b422cd2000f95464d87c7fb38fe0441", + ), + ( + 32, + "adbfe1aca8f06bd9fd65981b9103f25210e62d7ce94a20aa2973b2054f820b75", + ), + ( + 33, + "9b3dcd00f0608f592ed62b3e425f7bf8e745a1bc42e8b629c6a1c7b8375df9da", + ), + ( + 34, + "35fbed0085bc25bc2eb0dee442098af66faa4b6083071368d216b20ce354eab3", + ), + ( + 35, + "e029663cd5d181cae33629f5b4cb4a7a06d796f3c173427c0790e16248fda2a9", + ), + ( + 36, + "3d243d47975c8ad39fad3acd00131e68081cf515fd22cc898dd725200c31defd", + ), + ( + 37, + "b78ab1c70b44d8f8eae67c6a91bb0a5fa32f8a1cb898323980301547598edd66", + ), + ( + 38, + "4fb10bcdf704664ecd60ba38ac54ab2bc9c601bb86504201aac9826ba8d2fc05", + ), + ( + 39, + "8ff9c1ea04f1da96575c0b39f87a3a5661b679378b57a491cfea2740b52393a8", + ), + ( + 40, + "e15428e13ec8facf18dd9a460a22f9f958a3f3f4a739b540f424dda6110561d8", + ), + ( + 41, + "57a27dcf40a5f77ffde51bb460dcab1630f4ad1bff400e8833d58df3d8685e76", + ), + ( + 42, + "de96405cecb986b738628ce563a1454e0ec1403ef4bf587ee81685f383d777f1", + ), + ( + 43, + "8c8e425fda0a04e561a3044953e3a1ca8f60cd8b34f546392356a9b2cdb0249a", + ), + ( + 44, + "86eb084358d3df0c529f54d1c5da2d49a372e7295090a965c220ee766671fc73", + ), + ( + 45, + "4ff5eb870d21fc7ba25cd1422e58542d6cbc7490f7c790135270e74eb1e1aa07", + ), + ( + 46, + "dbd9d3f11f851bec54bb71a7aa7c5edb7b425f3dcdff1a0f6305b5cb7a395e20", + ), + ( + 47, + "2fa674c448311fbbc33ccf924d98ab330f11145f5fdfdb563f9471e49e170178", + ), + ( + 48, + "2dc0381e5d23a199bc4afafa68c1b6aba689230ed84a13595fa5c740bdb9a884", + ), + ( + 49, + "6e19dccf092a99ac4c5d1304cabe972624c725b5d49d20f975be362e7f57567b", + ), + ( + 50, + "27c7e30b9a636842e244a977d2cd82c165bf2ef60d9665f2e7e994b446b7f411", + ), + ( + 51, + "e6e2fdc78e73a57b2ff3592ba36506db2e8cb09af793f927be370567029bb619", + ), + ( + 52, + "c871d7b31f999ec44dc5df39174f4c0422c3331df443195fc3e94adc92bf1ce9", + ), + ( + 53, + "d6dda4570e3d434b834c8db230354384ca30025bc57df944ca0aa145268f046a", + ), + ( + 54, + "0a36cc41717c97a815d997d2a489a472cd2314d2171ba5dc079f8bf771282d84", + ), + ( + 55, + "ee11c3a365725daed0158e3ae270774c3b98f9484a7287b52b82a0966e3c3445", + ), + ( + 56, + "9d8cd60ec26a939c028e5794255e269ec9244f649316469972ead28aceaab4ce", + ), + ]; + + #[test] + fn merged_migrations_are_append_only() { + let mut unpinned = Vec::new(); + for m in MIGRATIONS { + let got = migration_digest(m); + match MERGED_MIGRATION_DIGESTS + .iter() + .find(|(v, _)| *v == m.version) + { + Some((_, want)) => assert_eq!( + got, *want, + "migration v{} ({}) changed after merge. Existing nodes will never \ + re-run it. Revert the edit and append a new migration instead.", + m.version, m.name + ), + None => unpinned.push(format!(" ({}, \"{}\"),", m.version, got)), + } + } + for (v, _) in MERGED_MIGRATION_DIGESTS { + assert!( + MIGRATIONS.iter().any(|m| m.version == *v), + "merged migration v{v} was removed from MIGRATIONS; never delete a merged entry" + ); + } + assert!( + unpinned.is_empty(), + "new migration(s) not pinned in MERGED_MIGRATION_DIGESTS; append:\n{}", + unpinned.join("\n") + ); + } + #[test] fn migrations_are_non_empty() { assert!( From a9c56966750ad6a67f8276dfee09888a6866dcfa Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:20:49 -0600 Subject: [PATCH 2/6] ci: require a Conventional Commit PR title --- .github/workflows/pr-title.yml | 34 ++++++++++++++++++++++++++++++++ scripts/check-pr-title.sh | 16 +++++++++++++++ scripts/test-check-pr-title.sh | 36 ++++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 .github/workflows/pr-title.yml create mode 100755 scripts/check-pr-title.sh create mode 100755 scripts/test-check-pr-title.sh diff --git a/.github/workflows/pr-title.yml b/.github/workflows/pr-title.yml new file mode 100644 index 00000000..cd992d12 --- /dev/null +++ b/.github/workflows/pr-title.yml @@ -0,0 +1,34 @@ +name: PR Title + +# PRs are squash-merged and release-please parses the resulting commit, so the +# title has to be a Conventional Commit. `edited` re-runs the check when only +# the title changes, without re-running the heavy PR Checks workflow. +on: + pull_request: + types: [opened, edited, synchronize, reopened] + +permissions: + contents: read + +concurrency: + group: pr-title-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + conventional-title: + name: conventional PR title + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Check out repository + uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.1 + with: + persist-credentials: false + + - name: Test the title checker + run: scripts/test-check-pr-title.sh + + - name: Check the PR title + env: + PR_TITLE: ${{ github.event.pull_request.title }} + run: scripts/check-pr-title.sh diff --git a/scripts/check-pr-title.sh b/scripts/check-pr-title.sh new file mode 100755 index 00000000..718ea038 --- /dev/null +++ b/scripts/check-pr-title.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# PRs are squash-merged, so the PR title becomes the commit release-please +# parses. A title it cannot parse drops the change from the release notes and +# the version bump. Reads the title from $PR_TITLE (never interpolated into +# shell source, since titles are attacker-controlled). +set -euo pipefail + +title="${PR_TITLE-}" +types='feat|fix|docs|refactor|test|chore|perf|ci|build|style|revert' +pattern="^(${types})(\([a-z0-9._/,-]+\))?!?: [^[:space:]].*$" + +if [[ "$title" == *$'\n'* ]] || ! [[ "$title" =~ $pattern ]]; then + printf 'PR title is not a Conventional Commit: %q\n' "$title" >&2 + printf 'Expected "(): " with type one of: %s\n' "${types//|/, }" >&2 + exit 1 +fi diff --git a/scripts/test-check-pr-title.sh b/scripts/test-check-pr-title.sh new file mode 100755 index 00000000..ba94074e --- /dev/null +++ b/scripts/test-check-pr-title.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Cases for scripts/check-pr-title.sh. Titles that landed on main and that +# release-please could not parse are kept as must-fail rows. +set -euo pipefail + +checker="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/check-pr-title.sh" +fail=0 + +expect() { + local want="$1" title="$2" got=pass + PR_TITLE="$title" "$checker" >/dev/null 2>&1 || got=fail + if [ "$got" != "$want" ]; then + printf 'want %s, got %s: %q\n' "$want" "$got" "$title" >&2 + fail=1 + fi +} + +expect pass 'fix(git): validate literal branch refs and node URLs' +expect pass 'feat: add repo topics' +expect pass 'perf!: drop the v1 cursor' +expect pass 'chore(deps): bump ws' +expect pass 'fix(api,sync): delimit positional arguments' +expect pass 'docs: shrink AGENTS.md' +expect pass 'revert: "feat: add repo topics"' + +expect fail 'SWF(perf): Bucket ref-update visibility by repo name' +expect fail 'Add a completeness fence over the GraphQL mutation surface' +expect fail 'gl: add --icaptcha-proof flag to register command' +expect fail 'fix:no space' +expect fail 'fix: ' +expect fail 'Fix: capitalised type' +expect fail 'feature: not a type' +expect fail '' +expect fail $'fix: ok\nsecond line' + +exit "$fail" From b381e86a807a4b3f901ff09e98fbe9e731edad08 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:19:21 -0600 Subject: [PATCH 3/6] docs: cut AGENTS.md to the rules no check enforces Drop lines that restate code or are now enforced by the authz_guard scans, the deny harness completeness check, the migration digest pins, clippy's MSRV lint, and the PR-title check. What remains is the authorization, signature, and client-denial judgment those checks cannot see. --- AGENTS.md | 50 ++++++++++++++----------------------------------- CONTRIBUTING.md | 2 +- 2 files changed, 15 insertions(+), 37 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a4221e65..73ff1994 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,44 +1,22 @@ # Contributor guide for coding agents -This file carries the rules a patch author cannot recover from the code alone, for humans and coding agents alike. For build, test, and PR basics, read `CONTRIBUTING.md` first. +Rules the tests cannot check. Build, test, and PR basics are in `CONTRIBUTING.md`. The `authz_guard` tests, the deny harness, the migration digest pins, clippy's MSRV lint, and the PR-title check enforce the rest and say how to fix what they catch. -## Authorization invariants (the rules PRs most often break) +## Authorization -Every repo-scoped endpoint must bind the caller to an authorization decision before serving or mutating anything. The `known_ungated` allowlist in `authz_guard::every_repo_scoped_handler_is_gated` is empty on main: `list_webhooks`, `list_replicas`, and `list_protected_branches` are gated (`list_webhooks` with read-visibility then owner; the other two with `authorize_repo_read`). Do not re-open those surfaces as exceptions. +- Content reads (blobs, trees, raw files) call `authorize_repo_read` with the exact path served, so a withheld subtree stays denied on a public repo. Repo-level reads pass `"/"`. The source scans cannot see this argument. +- A route that reaches repo data through a global id, or through an extractor the scans do not recognize, still needs the gate. +- A caller who may not read a repo or subtree gets the same 404 as a missing repo, never a 403. +- Some writes are deliberately not owner-only: stars bind to the signer, replica registration to the replica's DID, bounties have multi-party rules, and closing a PR or issue is owner-or-author. Do not add owner gates to these. +- A new gated route gets tests for an unauthorized signed caller and an anonymous caller, each asserting the exact status and that the body leaks nothing. -- Owner-only mutations (visibility, webhooks, protected branches, merges) are gated against the repo owner. Three gate forms are in use and all are recognized: webhooks and merges call `require_repo_owner` (`crates/twigpine-node/src/api/mod.rs`), visibility uses its module-local `require_owner`, and protected branches compare inline with `did_matches`. Use the form the surrounding module already uses. -- Not every write is owner-only, and that is by design: `star_repo`/`unstar_repo` bind to the signer (they still require repo read access), `register_replica`/`unregister_replica` bind to the replica's own DID, the bounty actions (claim, submit, approve, cancel, dispute) have their own multi-party rules, and closing a PR or issue is owner-or-author. Do not add owner gates to these. -- Content-serving reads (blobs, trees, raw files) gate through `authorize_repo_read` with the specific path being served, so a withheld subtree is denied even on an otherwise-public repo; repo-level reads (listings) pass `"/"` by the helper's own contract. The source scans below cannot check this argument's value, so review will. -- A route that reaches repo data through a global id, with no repo in its path, or through an extractor shape the scans do not recognize still needs the same gate; the scans cannot see those. -- Read-surface denials must not reveal existence: a caller who may not read a repo (or a withheld subtree) gets the same 404 as a missing repo, never a 403. (Owner-gated mutations currently return 403 after the repo lookup; do not widen that shape to read paths.) -- Two tests in module `authz_guard` (`crates/twigpine-node/src/api/mod.rs`) scan handler sources and fail on a repo-scoped handler without a recognized gate: `every_in_scope_mutation_has_its_gate` and `every_repo_scoped_handler_is_gated`. If they fail on your handler, add the gate. The second test's `known_ungated` allowlist is empty; never add an entry to it without an open issue and review. +## Signatures and certificates -## Adding or changing routes +- Take the verifying key from outside the artifact: the node's own DID, a pinned value, a peers lookup. A key read from the artifact itself proves only self-consistency, since anyone can mint a DID. A mismatch fails the result. +- Test a positive case with an independently anchored artifact and a rejection for a well-formed forgery. Invalid-only suites pass an implementation that rejects everything. +- Signed fields are a versioned format: version the payload, keep verifying the old form, and test an artifact signed before your change. -- A new gated handler needs tests proving its route-specific gate fires: exercise an unauthorized authenticated caller and an anonymous caller where applicable, assert the exact denial status each way, and assert the body leaks nothing. The non-owner tests in `crates/twigpine-node/src/test_support.rs` show the shape for owner-gated routes. -- A new mutation handler also gets a row in `every_in_scope_mutation_has_its_gate` naming its gate type; the per-handler row is the point of that test. -- A table-driven deny suite covering every deny-bearing route is in review (#194, #195). If it is present in your checkout, add a probe row there for any new deny-bearing route. +## Other -## Verifying signatures and certificates - -- Derive the verifying key from something outside the artifact you are checking: the node's own DID, a pinned or configured value, a peers lookup. A key read from a field of the object being verified (`Did::from_str(&cert.node_did)`) only proves the artifact is self-consistent, and identities here are permissionless, so anyone can mint a keypair, name it in the artifact, self-sign, and be told it is valid. A mismatch against that anchor has to fail the result, not log a warning. -- A handler whose correct answer is "valid" needs a positive case driven by a trusted, independently anchored artifact, and a rejection case for a well-formed, fully populated forged artifact. Invalid-only suites miss an implementation that rejects everything; a forged artifact that still returns valid is the regression that matters. -- The fields a signature covers are a versioned format. Adding one invalidates every artifact already signed, so give the payload a version, keep a path that verifies the older form, and add a test that verifies an artifact signed before your change. - -## Removing a serving path - -When a fix removes a path that used to serve content, the same PR must add a test asserting the removed path now denies. The deletion is what turns that test green; without it the path can quietly come back. - -## Database migrations - -Schema changes are code-defined in `MIGRATIONS` (`crates/twigpine-node/src/db/mod.rs`). Always append a new versioned entry; never edit an entry that has merged (operators deploy from main). Test runs build the schema from scratch, so editing an applied version stays green in CI while breaking every existing deployment. - -## Client behavior (`twigpine`, `git-remote-twigpine`) - -When a node denies a request, surface the denial to the user. Never render a denial as an empty list or a silent success; that turns an authorization boundary into invisible data loss. - -## Toolchain and CI reality - -- MSRV is Rust 1.91 (`rust-version` in the workspace `Cargo.toml`). The MSRV CI job runs `cargo check --workspace --all-targets` on exactly 1.91, so check that an API you rely on is stable there; the full test suite runs on stable. -- The PR workflow's jobs are `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test` (against Postgres), a release build, `cargo audit`, the MSRV check, and a Docker build. On a PR, `scripts/ci-surfaces.sh` runs each job only when the PR touches its inputs, and scopes `cargo test` and the release build to the touched crates plus every crate that depends on them. Root `Cargo.toml`/`Cargo.lock`/`.cargo/` changes run the Rust jobs (fmt, clippy, tests, release build, MSRV) on the whole workspace; every other job still runs only when its own inputs change. Edits to the CI wiring itself (`pr-checks.yml`, `codeql.yml`, `scripts/ci-surfaces.sh`), push to `main`, and the merge queue run every job on the whole workspace. Edits to any other workflow run none of these jobs on a PR; CodeQL only analyzes them as Actions code. Run `cargo test --workspace` locally regardless. The same script limits CodeQL (`codeql.yml`) to the languages a PR touches. The `main` branch ruleset currently requires one approving review but does not require these checks to pass before merge; a failing job should block review approval in practice, but nothing enforces that mechanically today. -- Conventional commit titles (`feat:`, `fix:`, `docs:`, ...) are required by convention and drive releases, but no CI job checks them; a bad title fails review, not the pipeline. +- When a fix removes a serving path, add a test asserting the path now denies. +- Clients (`twigpine`, `git-remote-twigpine`) surface a node's denial to the user, never as an empty list or silent success. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e6279c3d..7ce48f71 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -56,7 +56,7 @@ Smart contracts live in a separate repo: [github.com/Twigpine/contracts](https:/ 3. **No breaking changes without discussion.** Open an issue first for protocol-level changes. 4. **Conventional commits.** Use `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`. Releases are automated by [release-please](https://github.com/googleapis/release-please) — your commit prefixes drive the next version bump. 5. **Format and lint.** Run `cargo fmt --all` and `cargo clippy --workspace --all-targets -- -D warnings` before submitting. CI will reject anything that fails these. -6. **Security-surface rules.** [`AGENTS.md`](AGENTS.md) carries the authorization invariants PRs most often break; it is written for coding agents and humans alike, so read it before touching endpoints, visibility, or migrations. +6. **Security-surface rules.** [`AGENTS.md`](AGENTS.md) carries the authorization invariants PRs most often break; it is written for coding agents and humans alike, so read it before touching endpoints, visibility, or signatures. ## What gets merged, what gets closed From 7813e55a3477eae102ac029025434d4fd26f63db Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:34:58 -0600 Subject: [PATCH 4/6] fix(ci): close migration pin and title checker gaps --- .github/workflows/pr-checks.yml | 41 ++++++++ .github/workflows/pr-title.yml | 24 ++++- AGENTS.md | 2 +- crates/twigpine-node/src/db/mod.rs | 8 +- scripts/check-migration-pins.sh | 137 ++++++++++++++++++++++++++ scripts/check-pr-title.sh | 2 +- scripts/ci-surfaces.sh | 8 ++ scripts/test-check-migration-pins.sh | 140 +++++++++++++++++++++++++++ scripts/test-check-pr-title.sh | 2 + scripts/test-ci-surfaces.sh | 7 +- 10 files changed, 361 insertions(+), 10 deletions(-) create mode 100755 scripts/check-migration-pins.sh create mode 100755 scripts/test-check-migration-pins.sh diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index fc7f60d4..af53566e 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -51,6 +51,7 @@ jobs: core_deps: ${{ steps.surfaces.outputs.core_deps }} release_versioning: ${{ steps.surfaces.outputs.release_versioning }} release_tag: ${{ steps.surfaces.outputs.release_tag }} + migration_pins: ${{ steps.surfaces.outputs.migration_pins }} steps: - name: Check out repository uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.1 @@ -82,6 +83,46 @@ jobs: cat surfaces.out cat surfaces.out >> "$GITHUB_OUTPUT" + migration-pins: + name: migration pin append-only + needs: changes + if: needs.changes.outputs.migration_pins == 'true' + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Check out repository + uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.1 + with: + persist-credentials: false + + - name: Test the migration pin checker + run: scripts/test-check-migration-pins.sh + + - name: Check merged migration pins are append-only + env: + EVENT_NAME: ${{ github.event_name }} + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} + GROUP_BASE_SHA: ${{ github.event.merge_group.base_sha }} + run: | + set -euo pipefail + base_sha="" + if [ "$EVENT_NAME" = "pull_request" ]; then + base_sha="$PR_BASE_SHA" + elif [ "$EVENT_NAME" = "merge_group" ]; then + base_sha="$GROUP_BASE_SHA" + else + echo "migration pin comparison only applies to pull_request and merge_group" + exit 0 + fi + if [[ ! "$base_sha" =~ ^[0-9a-f]{40}$ ]]; then + echo "base sha is missing or malformed for $EVENT_NAME" >&2 + exit 1 + fi + git fetch --no-tags --depth=1 origin "$base_sha" + base_file="$(mktemp)" + git show FETCH_HEAD:crates/twigpine-node/src/db/mod.rs > "$base_file" + scripts/check-migration-pins.sh "$base_file" crates/twigpine-node/src/db/mod.rs + fmt-clippy: name: fmt + clippy needs: changes diff --git a/.github/workflows/pr-title.yml b/.github/workflows/pr-title.yml index cd992d12..84763648 100644 --- a/.github/workflows/pr-title.yml +++ b/.github/workflows/pr-title.yml @@ -6,12 +6,15 @@ name: PR Title on: pull_request: types: [opened, edited, synchronize, reopened] + merge_group: + types: [checks_requested] permissions: contents: read + pull-requests: read concurrency: - group: pr-title-${{ github.event.pull_request.number }} + group: pr-title-${{ github.ref }} cancel-in-progress: true jobs: @@ -30,5 +33,22 @@ jobs: - name: Check the PR title env: + EVENT_NAME: ${{ github.event_name }} + MERGE_QUEUE_REF: ${{ github.ref }} PR_TITLE: ${{ github.event.pull_request.title }} - run: scripts/check-pr-title.sh + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + if [ "$EVENT_NAME" = "merge_group" ]; then + if [[ "$MERGE_QUEUE_REF" =~ ^(refs/heads/)?gh-readonly-queue/.+/pr-([0-9]+)-[0-9a-f]{40}$ ]]; then + pr_number="${BASH_REMATCH[2]}" + else + echo "merge queue ref does not contain a PR number: $MERGE_QUEUE_REF" >&2 + exit 1 + fi + PR_TITLE="$(gh pr view "$pr_number" --json title -q .title)" + export PR_TITLE + elif [ "$EVENT_NAME" != "pull_request" ]; then + echo "unsupported event for PR title check: $EVENT_NAME" >&2 + exit 1 + fi + scripts/check-pr-title.sh diff --git a/AGENTS.md b/AGENTS.md index 73ff1994..6921d4ab 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # Contributor guide for coding agents -Rules the tests cannot check. Build, test, and PR basics are in `CONTRIBUTING.md`. The `authz_guard` tests, the deny harness, the migration digest pins, clippy's MSRV lint, and the PR-title check enforce the rest and say how to fix what they catch. +This file carries rules that require judgment rather than mechanical checks. Build, test, and PR basics are in `CONTRIBUTING.md`. The `authz_guard` tests, the deny harness, the migration digest and append-only pin checks, the MSRV CI job, the PR-title check, cargo fmt, and clippy enforce their own rules and say how to fix what they catch. ## Authorization diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index e90a22fa..a44cfde3 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -12688,10 +12688,10 @@ mod migration_tests { /// Digest of every merged migration. Operators deploy from main and the runner /// skips a version it has already recorded, so an edit to a merged entry never - /// reaches an existing node while a fresh test database applies it: CI stays - /// green and deployments diverge. Change a schema by appending a new version. - /// Add a row here only for a NEW migration; changing an existing row's digest - /// is the edit this test exists to stop. + /// reaches an existing node while a fresh test database applies it. Change a + /// schema by appending a new version. Add a row here only for a NEW migration. + /// This test pins the current contents; the migration pin CI check rejects + /// edits to rows that already exist on the base branch. const MERGED_MIGRATION_DIGESTS: &[(i64, &str)] = &[ ( 1, diff --git a/scripts/check-migration-pins.sh b/scripts/check-migration-pins.sh new file mode 100755 index 00000000..54d5eecb --- /dev/null +++ b/scripts/check-migration-pins.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# Compare MERGED_MIGRATION_DIGESTS between a base and head copy of db/mod.rs. +# Existing rows must survive unchanged, in order; new rows may only append new, +# higher versions. CI supplies the base file because a unit test cannot see the +# branch's merge history. +set -euo pipefail + +if [ "$#" -ne 2 ]; then + echo "usage: $0 " >&2 + exit 2 +fi + +base_file="$1" +head_file="$2" + +rows_from_file() { + local file="$1" section compact prefix rest inside residual + if [ ! -r "$file" ]; then + echo "cannot read $file" >&2 + return 1 + fi + + section=$(awk ' + !in_table && index($0, "const MERGED_MIGRATION_DIGESTS") { in_table=1 } + in_table { print } + in_table && index($0, "];") { exit } + ' "$file") + if [ -z "$section" ]; then + echo "$file: missing MERGED_MIGRATION_DIGESTS table" >&2 + return 3 + fi + + compact=$(printf '%s\n' "$section" | tr -d '[:space:]') + prefix='MERGED_MIGRATION_DIGESTS:&[(i64,&str)]=&[' + rest="${compact#*"$prefix"}" + if [ "$rest" = "$compact" ]; then + echo "$file: malformed MERGED_MIGRATION_DIGESTS declaration" >&2 + return 1 + fi + if ! printf '%s' "$rest" | grep -qF '];'; then + echo "$file: unterminated MERGED_MIGRATION_DIGESTS table" >&2 + return 1 + fi + inside="${rest%%];*}" + if [ -z "$inside" ]; then + echo "$file: empty MERGED_MIGRATION_DIGESTS table" >&2 + return 1 + fi + + residual=$(printf '%s' "$inside" | sed -E 's/\([0-9]+,"[0-9a-f]{64}",?\),//g') + if [ -n "$residual" ]; then + echo "$file: malformed row in MERGED_MIGRATION_DIGESTS" >&2 + return 1 + fi + printf '%s' "$inside" | grep -oE '\([0-9]+,"[0-9a-f]{64}",?\)' | sed -E 's/^\(([0-9]+),"([0-9a-f]{64})",?\)$/(\1,"\2")/' +} + +version_of() { + local row="$1" + row="${row#(}" + printf '%s\n' "${row%%,*}" +} + +tmp_dir=$(mktemp -d) +trap 'rm -r -- "$tmp_dir"' EXIT +base_rows_file="$tmp_dir/base-rows" +head_rows_file="$tmp_dir/head-rows" +base_missing=0 +if rows_from_file "$base_file" > "$base_rows_file"; then + base_rc=0 +else + base_rc=$? +fi +if [ "$base_rc" -eq 3 ]; then + # This PR introduces the table. Once it merges, a missing base table means + # the guard itself was removed and the nonzero path below fails closed. + base_missing=1 + : > "$base_rows_file" +elif [ "$base_rc" -ne 0 ]; then + exit 1 +fi +if ! rows_from_file "$head_file" > "$head_rows_file"; then + exit 1 +fi +mapfile -t base_rows < "$base_rows_file" +mapfile -t head_rows < "$head_rows_file" + +if [ "$base_missing" -eq 0 ] && [ "${#base_rows[@]}" -eq 0 ]; then + echo "$base_file: no digest rows found" >&2 + exit 1 +fi +if [ "${#head_rows[@]}" -eq 0 ]; then + echo "$head_file: no digest rows found" >&2 + exit 1 +fi +if [ "${#head_rows[@]}" -lt "${#base_rows[@]}" ]; then + echo "migration pin table shrank: ${#base_rows[@]} base rows, ${#head_rows[@]} head rows" >&2 + exit 1 +fi + +declare -A seen_versions=() +for row in "${head_rows[@]}"; do + version=$(version_of "$row") + if [ -n "${seen_versions[$version]:-}" ]; then + echo "migration pin version $version appears more than once" >&2 + exit 1 + fi + seen_versions[$version]=1 +done + +for ((i = 0; i < ${#base_rows[@]}; i++)); do + if [ "${head_rows[$i]}" != "${base_rows[$i]}" ]; then + echo "existing migration pin row $((i + 1)) changed, moved, or was removed" >&2 + echo "base: ${base_rows[$i]}" >&2 + echo "head: ${head_rows[$i]}" >&2 + exit 1 + fi +done + +last=0 +for row in "${base_rows[@]}"; do + version=$(version_of "$row") + if [ "$version" -gt "$last" ]; then + last="$version" + fi +done +for ((i = ${#base_rows[@]}; i < ${#head_rows[@]}; i++)); do + version=$(version_of "${head_rows[$i]}") + if [ "$version" -le "$last" ]; then + echo "new migration pin version $version is not appended after existing version $last" >&2 + exit 1 + fi + last="$version" +done + +printf 'migration pin table is append-only: %s existing rows unchanged, %s appended\n' \ + "${#base_rows[@]}" "$((${#head_rows[@]} - ${#base_rows[@]}))" diff --git a/scripts/check-pr-title.sh b/scripts/check-pr-title.sh index 718ea038..5f685e7b 100755 --- a/scripts/check-pr-title.sh +++ b/scripts/check-pr-title.sh @@ -9,7 +9,7 @@ title="${PR_TITLE-}" types='feat|fix|docs|refactor|test|chore|perf|ci|build|style|revert' pattern="^(${types})(\([a-z0-9._/,-]+\))?!?: [^[:space:]].*$" -if [[ "$title" == *$'\n'* ]] || ! [[ "$title" =~ $pattern ]]; then +if [[ "$title" == *$'\n'* ]] || [[ "$title" == *$'\r'* ]] || ! [[ "$title" =~ $pattern ]]; then printf 'PR title is not a Conventional Commit: %q\n' "$title" >&2 printf 'Expected "(): " with type one of: %s\n' "${types//|/, }" >&2 exit 1 diff --git a/scripts/ci-surfaces.sh b/scripts/ci-surfaces.sh index 7b6fb56c..70ca62fa 100755 --- a/scripts/ci-surfaces.sh +++ b/scripts/ci-surfaces.sh @@ -86,6 +86,7 @@ audit=false core_deps=false release_versioning=false release_tag=false +migration_pins=false cq_actions=false cq_js=false cq_rust=false @@ -132,6 +133,11 @@ for path in "${changed[@]}"; do scripts/resolve-release-tag.sh | scripts/test-resolve-release-tag.sh) release_tag=true ;; esac + case "$path" in + crates/twigpine-node/src/db/mod.rs | scripts/check-migration-pins.sh \ + | scripts/test-check-migration-pins.sh) + migration_pins=true ;; + esac case "$path" in .github/workflows/* | .github/actions/*) cq_actions=true ;; @@ -151,6 +157,7 @@ if [ "$all" = true ]; then core_deps=true release_versioning=true release_tag=true + migration_pins=true cq_actions=true cq_js=true cq_swift=true @@ -216,6 +223,7 @@ audit=$audit core_deps=$core_deps release_versioning=$release_versioning release_tag=$release_tag +migration_pins=$migration_pins codeql=$codeql codeql_matrix=$codeql_matrix EOF diff --git a/scripts/test-check-migration-pins.sh b/scripts/test-check-migration-pins.sh new file mode 100755 index 00000000..50f415f9 --- /dev/null +++ b/scripts/test-check-migration-pins.sh @@ -0,0 +1,140 @@ +#!/usr/bin/env bash +# Fixture test for scripts/check-migration-pins.sh. Covers the pass cases and +# each mutation that must fail closed. +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +checker="$repo_root/scripts/check-migration-pins.sh" +test_tmp="$(mktemp -d)" +trap 'rm -r -- "$test_tmp"' EXIT +failures=0 + +digest_a="$(printf 'a%.0s' {1..64})" +digest_b="$(printf 'b%.0s' {1..64})" +digest_c="$(printf 'c%.0s' {1..64})" +digest_d="$(printf 'd%.0s' {1..64})" +digest_e="$(printf 'e%.0s' {1..64})" + +base="$test_tmp/base.rs" +head="$test_tmp/head.rs" + +write_table() { + local file="$1" row version digest + shift + { + echo 'mod tests {' + echo ' const MERGED_MIGRATION_DIGESTS: &[(i64, &str)] = &[' + for row in "$@"; do + version="${row%%:*}" + digest="${row#*:}" + printf ' (\n %s,\n "%s",\n ),\n' "$version" "$digest" + done + echo ' ];' + echo '}' + } > "$file" +} + +write_one_line_table() { + local file="$1" row version digest + shift + printf 'mod tests { const MERGED_MIGRATION_DIGESTS: &[(i64, &str)] = &[' > "$file" + for row in "$@"; do + version="${row%%:*}" + digest="${row#*:}" + printf '(%s, "%s"),' "$version" "$digest" >> "$file" + done + printf ']; }\n' >> "$file" +} + +write_base() { + write_table "$base" "1:$digest_a" "2:$digest_b" "4:$digest_c" +} + +expect() { + local want="$1" name="$2" got=pass + "$checker" "$base" "$head" >/dev/null 2>&1 || got=fail + if [ "$got" != "$want" ]; then + printf 'FAIL %s: want %s, got %s\n' "$name" "$want" "$got" >&2 + failures=$((failures + 1)) + fi +} + +write_base +write_table "$head" "1:$digest_a" "2:$digest_b" "4:$digest_c" +expect pass 'unchanged table' + +write_base +write_one_line_table "$head" "1:$digest_a" "2:$digest_b" "4:$digest_c" "5:$digest_d" +expect pass 'one valid append in one-line layout' + +printf 'mod tests {\n}\n' > "$base" +write_table "$head" "1:$digest_a" "2:$digest_b" "4:$digest_c" +expect pass 'initial pin table introduction' + +write_base +write_table "$head" "1:$digest_a" "2:$digest_d" "4:$digest_c" +expect fail 'changed digest' + +write_base +write_table "$head" "1:$digest_a" "2:$digest_b" +expect fail 'removed row' + +write_base +write_table "$head" "1:$digest_a" "4:$digest_c" "2:$digest_b" +expect fail 'reordered rows' + +write_base +write_table "$head" "1:$digest_a" "2:$digest_b" "2:$digest_d" "4:$digest_c" +expect fail 'duplicate version' + +write_base +write_table "$head" "1:$digest_a" "2:$digest_b" "4:$digest_c" "3:$digest_d" +expect fail 'non-appended lower version' + +write_base +printf 'mod tests {\n}\n' > "$head" +expect fail 'missing table' + +write_base +cat > "$head" <<'EOF' +mod tests { + const MERGED_MIGRATION_DIGESTS: &[(i64, &str)] = &[ + (1, "not-a-sha256"), + ]; +} +EOF +expect fail 'malformed row' + +write_base +cat > "$head" < "$head" < "$base" <&2 + exit 1 +fi +echo "migration pin checks: all checks passed" diff --git a/scripts/test-check-pr-title.sh b/scripts/test-check-pr-title.sh index ba94074e..18b8a560 100755 --- a/scripts/test-check-pr-title.sh +++ b/scripts/test-check-pr-title.sh @@ -32,5 +32,7 @@ expect fail 'Fix: capitalised type' expect fail 'feature: not a type' expect fail '' expect fail $'fix: ok\nsecond line' +expect fail $'fix: ok\r' +expect fail $'fix: ok\rmore' exit "$fail" diff --git a/scripts/test-ci-surfaces.sh b/scripts/test-ci-surfaces.sh index f358b5c9..21474bfa 100755 --- a/scripts/test-ci-surfaces.sh +++ b/scripts/test-ci-surfaces.sh @@ -43,10 +43,10 @@ has_packages() { nothing=(rust=false rust_packages= windows=false windows_packages= docker=false audit=false core_deps=false release_versioning=false release_tag=false - codeql=false 'codeql_matrix={"include":[]}') + migration_pins=false codeql=false 'codeql_matrix={"include":[]}') everything=(rust=true rust_packages=--workspace windows=true 'windows_packages=-p twigpine-cli -p git-remote-twigpine' docker=true audit=true - core_deps=true release_versioning=true release_tag=true codeql=true) + core_deps=true release_versioning=true release_tag=true migration_pins=true codeql=true) all_languages='codeql_matrix={"include":[{"language":"actions","build-mode":"none","runner":"ubuntu-latest"},{"language":"javascript-typescript","build-mode":"none","runner":"ubuntu-latest"},{"language":"rust","build-mode":"none","runner":"ubuntu-latest"},{"language":"swift","build-mode":"autobuild","runner":"macos-latest"}]}' rust_only='codeql_matrix={"include":[{"language":"rust","build-mode":"none","runner":"ubuntu-latest"}]}' @@ -87,6 +87,9 @@ check "core allowlist" "$(map ci/twigpine-core-allowed-deps.txt)" core_deps=true check "release-please config" "$(map release-please-config.json)" \ release_versioning=true rust=false check "release tag resolver" "$(map scripts/resolve-release-tag.sh)" release_tag=true rust=false +check "migration definitions" "$(map crates/twigpine-node/src/db/mod.rs)" migration_pins=true rust=true +check "migration pin checker" "$(map scripts/check-migration-pins.sh)" migration_pins=true rust=false +check "migration pin checker test" "$(map scripts/test-check-migration-pins.sh)" migration_pins=true rust=false check "other workflow" "$(map .github/workflows/release.yml)" "${nothing[@]:0:9}" \ codeql=true 'codeql_matrix={"include":[{"language":"actions","build-mode":"none","runner":"ubuntu-latest"}]}' check "npm" "$(map npm/package.json)" codeql=true \ From 6c8120f6b737fb7c42d113212d663d7b0eeed907 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:08:12 -0600 Subject: [PATCH 5/6] fix(ci): close migration pin parser gaps --- CONTRIBUTING.md | 2 +- scripts/check-migration-pins.sh | 81 ++++++++++++++++++++++++++-- scripts/test-check-migration-pins.sh | 65 ++++++++++++++++++++++ 3 files changed, 143 insertions(+), 5 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7ce48f71..35103379 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -54,7 +54,7 @@ Smart contracts live in a separate repo: [github.com/Twigpine/contracts](https:/ 1. **One thing per PR.** Small, focused PRs get reviewed faster. 2. **Tests.** New functionality should have tests. Run `cargo test --workspace` before opening a PR. 3. **No breaking changes without discussion.** Open an issue first for protocol-level changes. -4. **Conventional commits.** Use `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`. Releases are automated by [release-please](https://github.com/googleapis/release-please) — your commit prefixes drive the next version bump. +4. **Conventional PR titles.** PRs are squash-merged, so [release-please](https://github.com/googleapis/release-please) parses the PR title as the resulting commit title. Use `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, or `chore:` in the PR title. The `PR Title` workflow enforces this with `scripts/check-pr-title.sh`, which you can run locally before opening or editing a PR. 5. **Format and lint.** Run `cargo fmt --all` and `cargo clippy --workspace --all-targets -- -D warnings` before submitting. CI will reject anything that fails these. 6. **Security-surface rules.** [`AGENTS.md`](AGENTS.md) carries the authorization invariants PRs most often break; it is written for coding agents and humans alike, so read it before touching endpoints, visibility, or signatures. diff --git a/scripts/check-migration-pins.sh b/scripts/check-migration-pins.sh index 54d5eecb..32e25f89 100755 --- a/scripts/check-migration-pins.sh +++ b/scripts/check-migration-pins.sh @@ -14,17 +14,90 @@ base_file="$1" head_file="$2" rows_from_file() { - local file="$1" section compact prefix rest inside residual + local file="$1" stripped declarations section compact prefix rest inside residual if [ ! -r "$file" ]; then echo "cannot read $file" >&2 return 1 fi - section=$(awk ' - !in_table && index($0, "const MERGED_MIGRATION_DIGESTS") { in_table=1 } + stripped=$(awk ' + BEGIN { depth=0; in_str=0; raw_hashes=-1 } + { + out="" + for (i=1; i<=length($0); i++) { + c=substr($0,i,1); n=substr($0,i+1,1) + if (raw_hashes >= 0) { + out=out c + if (c=="\"") { + hashes=0 + while (substr($0,i+1+hashes,1)=="#") hashes++ + if (hashes==raw_hashes) { + for (j=0; j 0) { + if (c=="/" && n=="*") { depth++; i++; continue } + if (c=="*" && n=="/") { depth--; i++; continue } + continue + } + if (c=="r") { + hashes=0 + while (substr($0,i+1+hashes,1)=="#") hashes++ + if (substr($0,i+1+hashes,1)=="\"") { + raw_hashes=hashes + out=out c + for (j=0; j&2 + return 3 + fi + if [ "$declarations" -gt 1 ]; then + echo "$file: more than one active MERGED_MIGRATION_DIGESTS declaration" >&2 + return 1 + fi + + section=$(printf '%s\n' "$stripped" | awk ' + !in_table && $0 ~ /(^|[^A-Za-z0-9_])const[[:space:]]+MERGED_MIGRATION_DIGESTS([^A-Za-z0-9_]|$)/ { in_table=1 } in_table { print } in_table && index($0, "];") { exit } - ' "$file") + ') if [ -z "$section" ]; then echo "$file: missing MERGED_MIGRATION_DIGESTS table" >&2 return 3 diff --git a/scripts/test-check-migration-pins.sh b/scripts/test-check-migration-pins.sh index 50f415f9..a6128e97 100755 --- a/scripts/test-check-migration-pins.sh +++ b/scripts/test-check-migration-pins.sh @@ -63,6 +63,35 @@ write_base write_table "$head" "1:$digest_a" "2:$digest_b" "4:$digest_c" expect pass 'unchanged table' +write_base +cat > "$head" < "$head" < "$head" < "$head" < Date: Sat, 5 Dec 2026 00:30:30 -0600 Subject: [PATCH 6/6] fix(ci): close migration pin lexer and coverage gaps Review on the pin checker found three holes: a raw string could shadow the digest table while the real declaration went unseen, byte and C raw strings were not lexed at all, and scripts-only edits to the checker never re-ran the semantic digest test. The awk extraction is replaced with a small token-aware Rust lexer (strings opaque, comments stripped, the const declaration recognized across whitespace), the pin-checker scripts now map to the twigpine-node rust surface so the digest test runs whenever the checker changes, and CONTRIBUTING documents the PR_TITLE invocation, the accepted types, and the test oracle. --- CONTRIBUTING.md | 2 +- scripts/check-migration-pins.sh | 290 +++++++++++++++++---------- scripts/ci-surfaces.sh | 3 + scripts/test-check-migration-pins.sh | 60 ++++++ scripts/test-ci-surfaces.sh | 8 +- 5 files changed, 256 insertions(+), 107 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 35103379..b73e49ff 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -54,7 +54,7 @@ Smart contracts live in a separate repo: [github.com/Twigpine/contracts](https:/ 1. **One thing per PR.** Small, focused PRs get reviewed faster. 2. **Tests.** New functionality should have tests. Run `cargo test --workspace` before opening a PR. 3. **No breaking changes without discussion.** Open an issue first for protocol-level changes. -4. **Conventional PR titles.** PRs are squash-merged, so [release-please](https://github.com/googleapis/release-please) parses the PR title as the resulting commit title. Use `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, or `chore:` in the PR title. The `PR Title` workflow enforces this with `scripts/check-pr-title.sh`, which you can run locally before opening or editing a PR. +4. **Conventional PR titles.** PRs are squash-merged, so [release-please](https://github.com/googleapis/release-please) parses the PR title as the resulting commit title. Accepted types are `feat`, `fix`, `docs`, `refactor`, `test`, `chore`, `perf`, `ci`, `build`, `style`, and `revert`, with an optional `(scope)` and a `!` suffix for breaking changes, in the form `(): `. The `PR Title` workflow enforces this with `scripts/check-pr-title.sh`, which reads the title from `PR_TITLE`. You can run it locally before opening or editing a PR, for example `PR_TITLE='feat(api): add repo topics' scripts/check-pr-title.sh`. `scripts/test-check-pr-title.sh` carries the passing and failing cases as the oracle. 5. **Format and lint.** Run `cargo fmt --all` and `cargo clippy --workspace --all-targets -- -D warnings` before submitting. CI will reject anything that fails these. 6. **Security-surface rules.** [`AGENTS.md`](AGENTS.md) carries the authorization invariants PRs most often break; it is written for coding agents and humans alike, so read it before touching endpoints, visibility, or signatures. diff --git a/scripts/check-migration-pins.sh b/scripts/check-migration-pins.sh index 32e25f89..90281e9f 100755 --- a/scripts/check-migration-pins.sh +++ b/scripts/check-migration-pins.sh @@ -14,118 +14,200 @@ base_file="$1" head_file="$2" rows_from_file() { - local file="$1" stripped declarations section compact prefix rest inside residual + local file="$1" if [ ! -r "$file" ]; then echo "cannot read $file" >&2 return 1 fi - stripped=$(awk ' - BEGIN { depth=0; in_str=0; raw_hashes=-1 } - { - out="" - for (i=1; i<=length($0); i++) { - c=substr($0,i,1); n=substr($0,i+1,1) - if (raw_hashes >= 0) { - out=out c - if (c=="\"") { - hashes=0 - while (substr($0,i+1+hashes,1)=="#") hashes++ - if (hashes==raw_hashes) { - for (j=0; j 0) { - if (c=="/" && n=="*") { depth++; i++; continue } - if (c=="*" && n=="/") { depth--; i++; continue } - continue - } - if (c=="r") { - hashes=0 - while (substr($0,i+1+hashes,1)=="#") hashes++ - if (substr($0,i+1+hashes,1)=="\"") { - raw_hashes=hashes - out=out c - for (j=0; j&2 - return 3 - fi - if [ "$declarations" -gt 1 ]; then - echo "$file: more than one active MERGED_MIGRATION_DIGESTS declaration" >&2 - return 1 - fi + # Token-aware extraction: a small Rust lexer strips line and nested block + # comments, keeps string literals opaque so their contents never count as + # declarations or rows, and recognizes the const declaration across + # whitespace and newlines. Rows are parsed from the token stream, so the + # digest values come from the one active table only. + python3 - "$file" <<'PYLEX' +import re +import sys - section=$(printf '%s\n' "$stripped" | awk ' - !in_table && $0 ~ /(^|[^A-Za-z0-9_])const[[:space:]]+MERGED_MIGRATION_DIGESTS([^A-Za-z0-9_]|$)/ { in_table=1 } - in_table { print } - in_table && index($0, "];") { exit } - ') - if [ -z "$section" ]; then - echo "$file: missing MERGED_MIGRATION_DIGESTS table" >&2 - return 3 - fi +path = sys.argv[1] - compact=$(printf '%s\n' "$section" | tr -d '[:space:]') - prefix='MERGED_MIGRATION_DIGESTS:&[(i64,&str)]=&[' - rest="${compact#*"$prefix"}" - if [ "$rest" = "$compact" ]; then - echo "$file: malformed MERGED_MIGRATION_DIGESTS declaration" >&2 - return 1 - fi - if ! printf '%s' "$rest" | grep -qF '];'; then - echo "$file: unterminated MERGED_MIGRATION_DIGESTS table" >&2 - return 1 - fi - inside="${rest%%];*}" - if [ -z "$inside" ]; then - echo "$file: empty MERGED_MIGRATION_DIGESTS table" >&2 - return 1 - fi - residual=$(printf '%s' "$inside" | sed -E 's/\([0-9]+,"[0-9a-f]{64}",?\),//g') - if [ -n "$residual" ]; then - echo "$file: malformed row in MERGED_MIGRATION_DIGESTS" >&2 - return 1 - fi - printf '%s' "$inside" | grep -oE '\([0-9]+,"[0-9a-f]{64}",?\)' | sed -E 's/^\(([0-9]+),"([0-9a-f]{64})",?\)$/(\1,"\2")/' +def fail(message, code): + print(f"{path}: {message}", file=sys.stderr) + sys.exit(code) + + +src = open(path).read() + +tokens = [] +i = 0 +n = len(src) +hexdigest = re.compile(r"^[0-9a-f]{64}$") +decimal = re.compile(r"^[0-9]+$") +identifier = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") +integer = re.compile(r"[0-9][0-9A-Za-z_]*") +raw_literal = re.compile(r"[bc]?r(#{0,255})\"") +string_literal = re.compile(r"(?:b|c)?\"") +char_literal = re.compile( + r"'(?:\\(?:[nrt0\\'\"]|x[0-9a-fA-F]{2}|u\{[0-9a-fA-F]{1,6}\})|[^\\'])'" +) +while i < n: + c = src[i] + if c.isspace(): + i += 1 + continue + if src.startswith("//", i): + nl = src.find("\n", i) + i = n if nl == -1 else nl + 1 + continue + if src.startswith("/*", i): + depth = 1 + i += 2 + while i < n and depth: + if src.startswith("/*", i): + depth += 1 + i += 2 + elif src.startswith("*/", i): + depth -= 1 + i += 2 + else: + i += 1 + continue + raw = raw_literal.match(src, i) + if raw: + closer = '"' + raw.group(1) + start = i + len(raw.group(0)) + end = src.find(closer, start) + if end == -1: + fail("unterminated raw string literal", 1) + tokens.append(("rawstring", src[start:end])) + i = end + len(closer) + continue + string = string_literal.match(src, i) + if string: + plain = string.group(0) == '"' + j = i + len(string.group(0)) + buf = [] + escaped = False + closed = False + while j < n: + ch = src[j] + if ch == "\\": + escaped = True + j += 2 + continue + if ch == '"': + closed = True + j += 1 + break + buf.append(ch) + j += 1 + if not closed: + fail("unterminated string literal", 1) + tokens.append(("string", "".join(buf) if plain and not escaped else None)) + i = j + continue + if c == "'": + m = char_literal.match(src, i) + if m: + i += len(m.group(0)) + else: + i += 1 + continue + m = identifier.match(src, i) + if m: + tokens.append(("ident", m.group(0))) + i += len(m.group(0)) + continue + m = integer.match(src, i) + if m: + tokens.append(("int", m.group(0))) + i += len(m.group(0)) + continue + tokens.append(("punct", c)) + i += 1 + +decls = [ + k + for k in range(len(tokens) - 1) + if tokens[k] == ("ident", "const") + and tokens[k + 1] == ("ident", "MERGED_MIGRATION_DIGESTS") +] +if not decls: + fail("missing MERGED_MIGRATION_DIGESTS table", 3) +if len(decls) > 1: + fail("more than one active MERGED_MIGRATION_DIGESTS declaration", 1) + +pos = decls[0] + 2 +shape = [ + ("punct", ":"), + ("punct", "&"), + ("punct", "["), + ("punct", "("), + ("ident", "i64"), + ("punct", ","), + ("punct", "&"), + ("ident", "str"), + ("punct", ")"), + ("punct", "]"), + ("punct", "="), + ("punct", "&"), + ("punct", "["), +] +if tokens[pos:pos + len(shape)] != shape: + fail("malformed MERGED_MIGRATION_DIGESTS declaration", 1) +pos += len(shape) + + +def malformed_row(): + fail("malformed row in MERGED_MIGRATION_DIGESTS", 1) + + +rows = [] +while True: + if pos >= len(tokens): + fail("unterminated MERGED_MIGRATION_DIGESTS table", 1) + if tokens[pos] == ("punct", "]"): + if pos + 1 < len(tokens) and tokens[pos + 1] == ("punct", ";"): + break + fail("unterminated MERGED_MIGRATION_DIGESTS table", 1) + if tokens[pos] != ("punct", "("): + malformed_row() + pos += 1 + if pos >= len(tokens) or tokens[pos][0] != "int" or not decimal.match(tokens[pos][1]): + malformed_row() + version = tokens[pos][1] + pos += 1 + if pos >= len(tokens) or tokens[pos] != ("punct", ","): + malformed_row() + pos += 1 + if ( + pos >= len(tokens) + or tokens[pos][0] != "string" + or tokens[pos][1] is None + or not hexdigest.match(tokens[pos][1]) + ): + malformed_row() + digest = tokens[pos][1] + pos += 1 + if pos < len(tokens) and tokens[pos] == ("punct", ","): + pos += 1 + if pos >= len(tokens) or tokens[pos] != ("punct", ")"): + malformed_row() + pos += 1 + if pos >= len(tokens): + fail("unterminated MERGED_MIGRATION_DIGESTS table", 1) + if tokens[pos] == ("punct", ","): + pos += 1 + elif tokens[pos] != ("punct", "]"): + malformed_row() + rows.append((version, digest)) + +if not rows: + fail("empty MERGED_MIGRATION_DIGESTS table", 1) +for version, digest in rows: + print(f'({version},"{digest}")') +PYLEX } version_of() { diff --git a/scripts/ci-surfaces.sh b/scripts/ci-surfaces.sh index 70ca62fa..c0e83f62 100755 --- a/scripts/ci-surfaces.sh +++ b/scripts/ci-surfaces.sh @@ -98,6 +98,9 @@ for path in "${changed[@]}"; do # The CI wiring itself: validate everything it gates. .github/workflows/pr-checks.yml | .github/workflows/codeql.yml | scripts/ci-surfaces.sh) all=true ;; + # Pin-checker edits must re-run the semantic migration digest test. + scripts/check-migration-pins.sh | scripts/test-check-migration-pins.sh) + touch_crate twigpine-node ;; # Workspace-wide Rust inputs. Cargo.toml | Cargo.lock | .cargo/* | rust-toolchain | rust-toolchain.toml \ | rustfmt.toml | .rustfmt.toml | clippy.toml | .clippy.toml) diff --git a/scripts/test-check-migration-pins.sh b/scripts/test-check-migration-pins.sh index a6128e97..0c549d50 100755 --- a/scripts/test-check-migration-pins.sh +++ b/scripts/test-check-migration-pins.sh @@ -92,6 +92,46 @@ mod tests { EOF expect pass 'comment markers inside strings ignored' +write_base +cat > "$head" < "$head" < "$head" <