carlos / platform Public

Merge remote-tracking branch 'origin/main' into race-activator-1249

# Conflicts:
#	.amadan/README.md
#	AGENTS.md
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 71470f238c9d7dd252adcee0875f39a5ccd89fc4 parent 3579a28parent 12158f4
13 files changed, +1,195 −4
  • .amadan/README.md +54 −3
  • .amadan/ci.d/80-gitleaks +32 −0
  • .gitleaks.toml +135 −0
  • AGENTS.md +11 −0
  • Makefile +20 −1
  • docs/superpowers/reviews/FINDINGS-gitleaks-1251-R3.md +41 −0
  • docs/superpowers/reviews/FINDINGS-gitleaks-1251-R4.md +21 −0
  • docs/superpowers/reviews/FINDINGS-race-activator-1249-r3.md +23 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251-R4.md +94 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251.md +53 −0
  • scripts/gitleaks-gate/main.go +367 −0
  • scripts/gitleaks-gate/notscanned.go +49 −0
  • scripts/gitleaks-gate/selftest.go +295 −0

CI failed — run details

diff --git a/.amadan/README.md b/.amadan/README.md
index c9adfb9b6..66728a7e6 100644
--- a/.amadan/README.md
+++ b/.amadan/README.md
@@ -33,10 +33,10 @@ no longer exists.
| `minio-contract` | `30-minio-contract` | MinIO on loopback, no container |
| `gofmt` | `10-gate` | repo-wide, via `make test` — see below |
-Six checks have no ancestor; the deleted workflow never ran them. The
+Seven checks have no ancestor; the deleted workflow never ran them. The
first three were added on 2026-11-16 after a code audit found the gate
-could not see them, and the code-health ratchet's two and the race
-detector on 2026-11-17.
+could not see them, the code-health ratchet's two and the race detector
+on 2026-11-17, and gitleaks on 2026-11-18.
| added | here | |
|---|---|---|
@@ -46,6 +46,7 @@ detector on 2026-11-17.
| code-health gate | `60-code-health` | `make code-health`: the code against `.amadan/code-health.tsv`, scanned with type information; see below |
| code-health record | `61-code-health-record` | the record against the merge base's copy; see below |
| race detector | `70-race` | `make race`: `go test -race` over the edge, activator, rootaws and systemd packages and host's loop and lease tests, sharded like the gate; see below |
+| `gitleaks` | `80-gitleaks` | `make gitleaks`: v8.30.1 over the tracked files, after proving that planted keys are still reported; see below |
## `govulncheck`: what turns it red
@@ -142,6 +143,56 @@ step with that bump.
`-race` needs cgo, so the target sets `CGO_ENABLED=1`, and the runner
needs a C compiler.
+## `gitleaks`: what turns it red
+
+`80-gitleaks` runs `make gitleaks`, which installs gitleaks v8.30.1 and
+hands it to `scripts/gitleaks-gate`. The gate scans the tracked files as
+they are in the working tree, not the history. Untracked files are left
+out. The step fails when:
+
+- gitleaks reports anything that `.gitleaks.toml` does not allow by exact
+ value;
+- a planted key goes unreported, or a file is left out that
+ `notscanned.go` does not name (the self-test, below);
+- `scripts/gitleaks-gate/notscanned.go` names a path git does not track;
+- gitleaks is missing or is not the pinned version, its config does not
+ load, its report cannot be read, or the scan misses the key the gate
+ plants beside the tracked files;
+- a `.gitleaksignore` is tracked. Allowances are made by value, in
+ `.gitleaks.toml`, and `gitleaks:allow` comments are ignored.
+
+**Some files are not scanned at all.** Census test files pin a sha256
+digest of each unit's source, and `implementation/always-awake-consumers.json`
+pins one per file in `source_hashes`. Those are content digests, not
+secrets, but gitleaks' generic rule reads a digest as a key, and nothing in
+a 64-character hex value tells the two apart. So the gate leaves those files
+out whole. `scripts/gitleaks-gate/notscanned.go` names each one by its
+exact repository path: no globs, no directories, only the 26 files gitleaks
+flags today. A credential committed in one of them is not found. A file
+renamed away from its entry is scanned under its new name, and an entry
+for a path git does not track fails the step.
+
+If a new census layer turns the step red, check that every finding in it is
+a digest, then add the file's exact path to `notscanned.go`.
+
+**The self-test runs first, on every scan.** It plants keys generated at
+run time in ordinary source and in an allowed fixture, and scans each case
+with gitleaks' default rules alone as well, so a case the rules would never
+flag fails instead of passing for free. Then it builds a small git
+repository and scans it the way the real scan does: a tracked file named
+`gitleaks-gate-sentinel.env` (the gate's own planted key once used that
+name) must be reported, every file `notscanned.go` names must be left out,
+and the same key under a near miss of each name must be reported. It also
+checks that a broken config, a missing binary and a stale list entry fail
+the scan.
+
+The gate's own planted key goes in a file with a new random name on each
+run, created only if nothing is there, so it can never replace a tracked
+file.
+
+The log names the file and line of a finding and never its value. It needs
+the Go module proxy, to fetch gitleaks.
+
## `gofmt`: ported by widening it, not by reproducing it
This section is the reason it was safe to delete the workflow, so it is
diff --git a/.amadan/ci.d/80-gitleaks b/.amadan/ci.d/80-gitleaks
new file mode 100755
index 000000000..900fd79c4
--- /dev/null
+++ b/.amadan/ci.d/80-gitleaks
@@ -0,0 +1,32 @@
+#!/bin/sh
+# Secrets committed to the tracked files: gitleaks v8.30.1, pinned, with its
+# default rules. `make gitleaks` is the one definition; this step only runs
+# it, so a developer gets the same answer with the same command.
+#
+# Its own step, not part of `make test`, for staticcheck's reasons: a red
+# here is a finding, not a failed test, and `make test` stays no slower.
+#
+# The tree, not the history: what a branch adds is found in the run that
+# adds it, and old values already in every clone would hold every branch red.
+#
+# Not scanned at all: the census test files and the design checklist that
+# scripts/gitleaks-gate/notscanned.go names by exact path. They hold sha256
+# digests of source, not secrets, and a key committed in one is not found.
+#
+# Red means one of:
+# - a value gitleaks takes for a secret. Remove it, and rotate it if it was
+# ever real. A fake a test needs is allowed by exact value in
+# .gitleaks.toml, with its reason;
+# - the self-test: a planted key went unreported, or a file other than the
+# ones notscanned.go names was left out (scripts/gitleaks-gate/selftest.go);
+# - notscanned.go names a path git does not track;
+# - a scan that could not run: no binary, the wrong version, a config that
+# does not load. None of these passes.
+#
+# The log names the file and line of a finding, never its value.
+#
+# Network: the Go module proxy, to fetch gitleaks, as every step already uses.
+set -eu
+. .amadan/go-toolchain.sh
+
+make gitleaks
diff --git a/.gitleaks.toml b/.gitleaks.toml
new file mode 100644
index 000000000..b52233128
--- /dev/null
+++ b/.gitleaks.toml
@@ -0,0 +1,135 @@
+# gitleaks' default rules, less the values this repository commits on
+# purpose. `make gitleaks` (.amadan/ci.d/80-gitleaks) scans the tracked files
+# with it, through scripts/gitleaks-gate.
+#
+# Every allowance here names exact values, anchored, so a value that merely
+# contains one is still found. Where a value only belongs in some files, the
+# allowance is scoped to them (condition AND: a path and a value), so the
+# same value anywhere else still fails the gate.
+#
+# Some files are NOT SCANNED AT ALL: the census test files that pin sha256
+# digests of source, and the design checklist,
+# implementation/always-awake-consumers.json, which pins one per file in
+# source_hashes. They hold content digests, not secrets, but gitleaks'
+# generic rule reads a digest as a key and no allowance can tell the two
+# apart. So scripts/gitleaks-gate leaves those files out whole, each named
+# by its exact path in scripts/gitleaks-gate/notscanned.go (no globs, no
+# directories), and a credential committed in one of them is not found.
+#
+# Nothing is allowed by fingerprint or by comment: the gate refuses a tracked
+# .gitleaksignore and scans with --ignore-gitleaks-allow.
+#
+# AN ALLOWANCE WITH `paths` MUST NAME `targetRules`. In `gitleaks dir`
+# (v8.30.1), a global allowance's paths skip the whole file before it is
+# read, whatever its condition says: an AND of a path and a value allowed
+# every secret in every file the path matched. One with targetRules is
+# moved onto those rules, where the AND holds and the rest of the file is
+# still scanned.
+#
+# A new finding is fixed, not allowed, unless it is a value that has to be
+# committed. Then add it here, in the group that fits, with its reason.
+[extend]
+useDefault = true
+
+# Fake credentials typed into tests, each recognisable as one: a counting
+# run (0123456789abcdef), a word (SecretValue, SENTINEL, nope), a test's
+# own label. The Stripe keys exist to test that the console tells a live
+# key from a test key and a restricted key from a secret one, so they must
+# keep Stripe's prefixes. Three are 64-hex values: 9f86d081... is
+# sha256("test"), fd61a03a... a second stand-in for an HMAC, and
+# c7aff5eb... the callback signature key derived from the golden vector's
+# fixed master, "master-fixed-for-the-vector". Test files only: the same
+# value in production code is still found.
+[[allowlists]]
+description = "fake credentials in tests"
+targetRules = ["generic-api-key", "stripe-access-token"]
+condition = "AND"
+paths = ['''_test\.go$''']
+regexes = [
+ '''^rk_test_51SecretValue$''',
+ '''^rk_live_51SecretValue$''',
+ '''^sk_test_51SecretValue$''',
+ '''^rk_live_51AbCdEfGhIjKlMnOpQrStUv$''',
+ '''^tok-flagship-2$''',
+ '''^tok-second-64hex$''',
+ '''^tok_SECRET_123$''',
+ '''^tok-0123456789abcdef0123456789abcdef$''',
+ '''^SES_SECRET=s3kr1t$''',
+ '''^SECRET-SENTINEL-7f3a$''',
+ '''^cdk1\.bab\.titogo\.0123456789abcdef\.$''',
+ '''^cdk1\.bae\.titogo\.nope$''',
+ '''^carlos-0123456789abcdef0123456789abcdef-1$''',
+ '''^0123456789abcdef0123456789abcdef$''',
+ '''^0123456789abcdefghij0123456789abcdefghijkl$''',
+ '''^3f9a0c1d2e4b5a6978877665544332211$''',
+ '''^AbCd12_EfGh34_IjKl56_MnOp78$''',
+ '''^ba9876543210$''',
+ '''^PLAN14_E45_CONTAINED$''',
+ '''^apps/bab/other/instances/$''',
+ '''^9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08$''',
+ '''^fd61a03af4f77d870fc21e05e7e80678095c92d808cfb3b5c279ee04c74aca13$''',
+ '''^c7aff5eb65835639b68c63a226767768ac2049fe0b57ab83844691ae5cca1d17$''',
+]
+
+# The fake instance key the instance-key tests and their plans share
+# (note its tail, ...bC6dF5gH0iJ1kA=: typed, not generated). Allowed in
+# tests and docs alike, because the plans quote the tests.
+[[allowlists]]
+description = "fake instance key shared by tests and plans"
+regexes = ['''^q\+/Zk3vJ0aW1Yx9sR7tUe2oPl4mN8bC6dF5gH0iJ1kA=$''']
+
+# RFC 6455's sample Sec-WebSocket-Key ("the sample nonce", base64), the
+# one every WebSocket handshake test and its spec quotes. A nonce is not a
+# secret even when it is not the RFC's.
+[[allowlists]]
+description = "RFC 6455 sample WebSocket key"
+regexes = ['''^dGhlIHNhbXBsZSBub25jZQ==$''']
+
+# Committed fixtures. configseal_vectors.json is the cross-language
+# vector set sealed by configseal.js and opened by Go; its key is a
+# throwaway minted for the vectors and protects nothing (the file says so,
+# in the key's own name). lookup.json is a recorded registrar response
+# with its domain auth code replaced by a counting run. Each value in its
+# own file only.
+[[allowlists]]
+description = "configseal test-only vector key"
+targetRules = ["generic-api-key"]
+condition = "AND"
+paths = ['''^internal/console/testdata/configseal_vectors\.json$''']
+regexes = ['''^xKbVxY32zPtWRkhfwugpfIdsamLLebvaWKnV9WLWQ48=$''']
+
+[[allowlists]]
+description = "registrar fixture's placeholder auth code"
+targetRules = ["generic-api-key"]
+condition = "AND"
+paths = ['''^internal/registrar/openprovider/testdata/lookup\.json$''']
+regexes = ['''^1a2b3c4d5e6f$''']
+
+# The password 30-minio-contract gives a user of the MinIO it starts on
+# loopback for one job and then deletes; the plan that wrote the step
+# quotes it.
+[[allowlists]]
+description = "throwaway MinIO user in the contract step"
+targetRules = ["generic-api-key"]
+condition = "AND"
+paths = [
+ '''^\.amadan/ci\.d/30-minio-contract$''',
+ '''^docs/superpowers/plans/2026-10-22-db-region-forward-plan-2-query\.md$''',
+]
+regexes = ['''^dbfukboxsecret1$''']
+
+# Not values at all: generic-api-key matching the word after "key" in code
+# comments and prose (a function name, a header, a review's heading, a
+# CLI flag in a list of flags, an env line in a README), and a bucket name
+# whose number is an AWS account ID, which identifies and does not
+# authenticate.
+[[allowlists]]
+description = "prose and code the generic rule reads as a key"
+regexes = [
+ '''^ed25519\.Verify$''',
+ '''^if-none-match=$''',
+ '''^retry/duplicate$''',
+ '''^CARLOS_REGION=ie$''',
+ '''^--enable-primary-ipv6$''',
+ '''^carlos-flagship-271376211898$''',
+]
diff --git a/AGENTS.md b/AGENTS.md
index 49b99818e..59fe7e7b6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -309,6 +309,17 @@ anything.
parent's, or one it built first): `setKnob` fails it, and the setting
goes in the parent, before the parent builds anything.
`internal/lease` is out for now (`.amadan/README.md` says why).
+- `80-gitleaks` runs `make gitleaks` (v8.30.1, pinned) over the tracked
+ files through `scripts/gitleaks-gate`, which first proves that planted
+ keys are still reported. A real finding is removed, and rotated if it
+ was ever live. A fake a test needs is allowed by exact value in
+ `.gitleaks.toml`, scoped to its files; `gitleaks:allow` comments and
+ `.gitleaksignore` do not work here. The census test files and the design
+ checklist that `scripts/gitleaks-gate/notscanned.go` names by exact path
+ are not scanned at all: they hold sha256 digests of source, not secrets,
+ and a key committed in one would not be found. A new census file that
+ turns the step red with digest findings is added there by its exact
+ path. `.amadan/README.md` has the details.
- `20-cross@5` adds `GOOS=darwin`/`windows`/`linux-arm64` compiles, one
per shard. **The gate is not Linux-only**: `internal/host` is linked
into the CLI, which people run on Macs, so a Linux-only type assumption
diff --git a/Makefile b/Makefile
index 8eeb2c8f4..f419d81df 100644
--- a/Makefile
+++ b/Makefile
@@ -7,7 +7,7 @@ LDFLAGS := -s -w -X github.com/carlosframework/platform/internal/version.Build=$
GOOS ?=
GOARCH ?=
-.PHONY: test build build-console fmt staticcheck govulncheck race census-card census-propose code-health code-health-record console-mockup-kit parity-doc
+.PHONY: test build build-console fmt staticcheck govulncheck gitleaks race census-card census-propose code-health code-health-record console-mockup-kit parity-doc
# The build gate: vet, format, tests. `.amadan/ci.d/10-gate` runs this same
# target, so what CI checks and what you check are one definition.
@@ -99,6 +99,25 @@ govulncheck:
(cd launchctx && go run $(GOVULNCHECK) -format json ./...) >"$$dir/launchctx.json" && \
go run ./scripts/govulncheck-gate -exceptions .amadan/govulncheck-exceptions.tsv "$$dir/platform.json" "$$dir/launchctx.json"
+# Secrets committed to the tracked files, as CI checks them
+# (.amadan/ci.d/80-gitleaks): gitleaks, pinned, with its default rules less
+# the exact values .gitleaks.toml allows. Not part of `make test`, like
+# staticcheck, and fetched at a pinned version for the same reason (no tool
+# line in go.mod).
+#
+# Installed once and handed to scripts/gitleaks-gate, because the gate runs
+# it many times: it plants keys and proves they are reported, then scans the
+# tracked files as they are now, uncommitted edits included. Untracked files
+# are not scanned, nor are the digest files scripts/gitleaks-gate/notscanned.go
+# names by exact path. The tree, not the history: what a branch adds is found in
+# the run that adds it, and old values already in every clone would hold
+# every branch red. The `&&` matters: no binary, no pass.
+GITLEAKS_VERSION := v8.30.1
+gitleaks:
+ @dir=$$(mktemp -d) || exit 1; trap 'rm -rf "$$dir"' EXIT; \
+ GOBIN="$$dir" go install github.com/zricethezav/gitleaks/v8@$(GITLEAKS_VERSION) && \
+ go run ./scripts/gitleaks-gate -gitleaks "$$dir/gitleaks" -version $(GITLEAKS_VERSION) -config .gitleaks.toml
+
# The race detector over the packages with real concurrency, as CI runs it
# (.amadan/ci.d/70-race). Not part of `make test`: -race compiles every
# package again and runs its tests several times slower. The tests in
diff --git a/docs/superpowers/reviews/FINDINGS-gitleaks-1251-R3.md b/docs/superpowers/reviews/FINDINGS-gitleaks-1251-R3.md
new file mode 100644
index 000000000..cd3c1e3b8
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-gitleaks-1251-R3.md
@@ -0,0 +1,41 @@
+Reviewed `origin/main...614cc4ae228f6def225d1a9fc49189a4aecd229a`, round 3 of 3. The difference from the brief’s named commit is only the brief itself.
+
+1. **P1 — Digest-shaped entries are approved without establishing that their values are checked digests.**
+ [scripts/gitleaks-gate/judge.go:127](/home/paulca/amadan.net/carlos/platform-gitleaks-1251/scripts/gitleaks-gate/judge.go:127)
+
+ **Failure scenario:** put a real 64-character lowercase hexadecimal credential under `"internal/console/auth.go"` in the checklist’s `source_hashes` object. The scanner reports it as `generic-api-key`; the judge accepts it because the line matches and `Secret` equals the value. No repository test validates that checklist’s hashes. The judge also accepts matching lines outside `source_hashes`, because it never parses the surrounding JSON.
+
+ The census protection is incomplete for the same reason. `TestPlan9B8RecordWriteCensus` compares the **effective inventory** with source digests. It does not validate every matching line in every `_census_test.go` file. An unused `[]censusEntry` declaration containing a credential passes the judge without entering that inventory. Historical entries overwritten by later layers likewise do not have their original digest checked by that comparison.
+
+ **Evidence:** the pinned v8.30.1 scanner detected generated hexadecimal keys in both a checklist entry and an unused census entry, with the exact `Secret`, rule and single-line location that `approve` accepts. All 28 existing checklist hashes match their declared historical source revision, but that relationship is not enforced by CI.
+
+ **Fix:** require independent verification of each accepted digest, including its inventory membership or historical source, and reject entries without that evidence. Add negative cases for an incorrect checklist digest, a matching line outside `source_hashes`, and an unused census declaration. Shape alone cannot provide the required approval.
+
+ **Fault family:** allowances must distinguish approved source digests from credentials—the same invariant as the earlier rounds.
+
+2. **P1 — The sentinel overwrites a tracked file before scanning it.**
+ [scripts/gitleaks-gate/main.go:159](/home/paulca/amadan.net/carlos/platform-gitleaks-1251/scripts/gitleaks-gate/main.go:159)
+
+ **Failure scenario:** commit a root-level `gitleaks-gate-sentinel.env` containing a credential. `copyTracked` copies it into the scan tree, then `os.WriteFile` truncates it and substitutes the generated sentinel. The scanner therefore never sees the committed credential. Its replacement satisfies `sawSentinel`, allowing the gate to pass.
+
+ **Evidence:** this follows directly from the copy/write ordering. The pinned scanner detected a synthetic credential in equivalent environment-file content; the wrapper would remove that content before invoking it.
+
+ **Fix:** create the sentinel exclusively at an unused path, or reject a tracked-path collision before writing. Exempt only the generated sentinel finding, and add a regression case containing a tracked file with the current sentinel name.
+
+ **Fault family:** scan coverage must preserve every tracked file’s contents.
+
+No additional P2 or P3 findings.
+
+The remaining checks found:
+
+- **Report handling:** the judge compares `Secret` with the digest captured from the actual file line, requires a single-line finding, and rejects `decoded:` tags. Malformed/truncated JSON, inconsistent exit status, missing reports, missing binaries and version mismatches have rejection paths.
+- **Empty scans:** zero copied files fails; failure to detect the generated sentinel also fails. The collision above defeats coverage despite those checks.
+- **Self-test wiring:** `80-gitleaks` invokes `make gitleaks`, whose wrapper runs the self-test before scanning tracked files. Planted cases must be detected by both the default-rule control and the configured scan after judging.
+- **Exact allowances:** all 35 expressions are anchored exact values. Their repository uses support the documented fixture, test, digest-fragment or non-secret explanations; I identified no live credential among them.
+- **Documentation:** README, AGENTS.md and the step header match the invocation and intended behavior, subject to the coverage failures above.
+
+`git diff --check`, shell syntax checking and formatting checks passed. Scanner probes used the cached, version-verified executable. The complete wrapper/self-test was not executed because it requires filesystem writes unavailable in this sandbox. Access to amadan #1251 was blocked by network restrictions. No files were changed, reviewers spawned or full suites run.
+
+This exhausts round 3 and repeats the allowance fault family. **Cutting or holding the new step is better than starting another repair/review round without Paul’s explicit decision.**
+
+NOT READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/FINDINGS-gitleaks-1251-R4.md b/docs/superpowers/reviews/FINDINGS-gitleaks-1251-R4.md
new file mode 100644
index 000000000..47d39591d
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-gitleaks-1251-R4.md
@@ -0,0 +1,21 @@
+Reviewed `origin/main...8ea340c26149f7c0afa3c85a1d7ac7457cea13a8`, round 4 of 4, within the brief’s fixed scope. The change after its named commit, `99612d24`, is the review brief alone.
+
+**No P1, P2 or P3 findings.**
+
+- **Both R3 P1s are closed.** `judge.go` is deleted. The wrapper no longer approves findings by digest shape or source line. In [main.go:219](/home/paulca/amadan.net/carlos/platform-gitleaks-1251/scripts/gitleaks-gate/main.go:219), only a finding matching both the generated sentinel’s exact filename and exact value is set aside; every other reported finding remains.
+
+- **Exclusions are exact paths.** [main.go:247](/home/paulca/amadan.net/carlos/platform-gitleaks-1251/scripts/gitleaks-gate/main.go:247) obtains unquoted, NUL-delimited paths from Git. The exclusion lookup compares those full strings directly, before filesystem path conversion. There is no glob, prefix, suffix, case folding or cleaning in that comparison. Git’s canonical index paths prevent `./`, `..` and trailing-slash aliases. Symlinks and submodules do not satisfy a listed regular-file entry, so substituting either leaves the entry unsatisfied and fails the gate. All 26 current entries are unique, tracked regular files.
+
+- **The rename-and-replace edge is acceptable under the chosen contract.** Renaming listed file A to B makes B eligible for scanning. Removing A without replacement fails the stale-entry check. If the same commit installs new content at A, A remains excluded. That follows the explicitly accepted limitation that credentials at named paths are not found; it does not widen the exclusion to B.
+
+- **The sentinel cannot overwrite a copied file.** [main.go:200](/home/paulca/amadan.net/carlos/platform-gitleaks-1251/scripts/gitleaks-gate/main.go:200) uses `O_CREATE|O_EXCL` after copying tracked files. A collision fails before writing. Creation, write and close errors propagate. [selftest.go:192](/home/paulca/amadan.net/carlos/platform-gitleaks-1251/scripts/gitleaks-gate/selftest.go:192) calls production `scanTree`, which calls production `copyTracked`. Its required findings cover the former sentinel filename, an unlisted census file and three near misses per exclusion. Restoring the former fixed-name overwrite would remove a required finding and fail this test.
+
+- **The requested failure paths reject the scan.** Missing or wrong-version binaries, invalid or missing configuration, unreadable or malformed/truncated JSON, inconsistent report/exit status, zero copied files, a missing sentinel finding, stale exclusions and tracked `.gitleaksignore` files have rejection paths. The self-test runs before the repository scan.
+
+- **Documentation and allowances match the implementation.** The config header, CI step, Makefile, README and AGENTS.md identify the omitted digest files and their exact-path list. The documentation explicitly acknowledges the credential blind spot. None still describes an active digest judge. The remaining allowance definitions and comments are byte-for-byte unchanged from R3; only the 9B8 fragment allowance was removed.
+
+Shell syntax and Go formatting checks passed. `git diff --check` reported only two Markdown hard-break lines in the committed R3 findings.
+
+The complete wrapper/self-test was not executed because this sandbox prohibits filesystem writes. Network restrictions prevented independently reading amadan #1251; the review uses the ruling recorded in the R4 brief. No files were changed, reviewers spawned or full suites run.
+
+READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/FINDINGS-race-activator-1249-r3.md b/docs/superpowers/reviews/FINDINGS-race-activator-1249-r3.md
new file mode 100644
index 000000000..93a118e66
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-race-activator-1249-r3.md
@@ -0,0 +1,23 @@
+Reviewed `3579a282f3e59e9b9e19949fc3a80d876d3160c9`, focusing on changes since round two.
+
+No P1, P2, or P3 findings.
+
+The round-two ownership problem is addressed: `setKnob` checks for an unowned running Service before registering a restore or writing the setting. Refusal leaves both untouched. The converted subtests establish their overrides before building their Services. I found no parallel test reaching `setKnob` in the call paths examined.
+
+The dropped-entry watch is now reachable through the Service’s stop channel. Every resident lease watch uses that channel, initialized before the tracked Service is returned. `sync.Once` prevents duplicate closes. The wait includes short-lease one-shot stops; the subsequent production-goroutine join and Service synchronization precede restoration.
+
+The remaining direct overrides match the brief’s exceptions: synchronous operations, mutex-protected seams, the explicitly joined HA recovery worker, or writes covered by an existing `setKnob` restore. I found no additional restore path violating the stated invariant.
+
+Census verdicts:
+
+| Unit or envelope | Verdict | Basis |
+|---|---|---|
+| `activator.go`, `type Service` | **APPROVE** | [Lines 1691–1699](/home/paulca/amadan.net/carlos/platform-race-activator-1249/internal/activator/activator.go:1691) add synchronization fields without adding input reads or authority. Production leaves `leaseWatchStop` nil and never waits on `leaseWork`. |
+| `rootfs_service.go`, `Service.residentLeaseShort` | **APPROVE** | [Lines 983–1004](/home/paulca/amadan.net/carlos/platform-race-activator-1249/internal/activator/rootfs_service.go:983) retain the existing entry check, route reads, stop selection, and asynchronous execution. Each added count has a deferred decrement. The recorded `legacy` disposition remains appropriate. |
+| Envelope `internal/activator` | **APPROVE** | Reviewed the fields above and [watch creation and execution, lines 902–967](/home/paulca/amadan.net/carlos/platform-race-activator-1249/internal/activator/rootfs_service.go:902). Watch accounting precedes launch and ends on every return. The added select case is disabled in production. No root input, termination check, or execution authority is broadened. |
+
+Validation is limited to static review: `git diff --check` passed, but the seven targeted tests could not start because Go attempted to update `go.mod` on the read-only filesystem. Network restrictions also prevented reading amadan #1249; round history was taken from the checked-in briefs. No files were changed, reviewers spawned, or full suites run.
+
+Round three has no P1 findings; the stopping rule ends this review here.
+
+READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251-R4.md b/docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251-R4.md
new file mode 100644
index 000000000..55bdbe380
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251-R4.md
@@ -0,0 +1,94 @@
+# Review brief: branch gitleaks-1251, round 4 of 4
+
+Repo carlos/platform, branch `gitleaks-1251`, commit 99612d24.
+Under review: the diff `origin/main...99612d24`. The R3 diff was
+`origin/main...7aac4320`; `git diff 7aac4320 99612d24` minus the merge
+of origin/main (2b8fd0e7, no conflicts, nothing in the gate) is what changed.
+Authorities: amadan #1251 (the design and Paul's 2026-11-19 ruling),
+AGENTS.md ("Stopping rules"), `docs/superpowers/reviews/FINDINGS-gitleaks-1251-R3.md`.
+
+**This is the last round.** Paul allowed a fourth round with a fixed scope
+and there is no fifth. Review that scope. Do not ask for a different design.
+
+## What changed since R3
+
+Paul chose the first option on #1251: stop judging digests by shape, leave
+the digest files out by exact path, and say so plainly.
+
+1. **R3 P1 1 (digest-shaped approvals).** `scripts/gitleaks-gate/judge.go`
+ is deleted. The new `scripts/gitleaks-gate/notscanned.go` lists 26
+ whole repository paths: the 25 census test files gitleaks flags for their
+ sha256 digests, and `implementation/always-awake-consumers.json`.
+ `copyTracked` (`main.go:246`) compares each git path to the list for
+ equality and does not copy a listed file, so gitleaks never reads it.
+ An entry naming a path git does not track fails the step (`main.go:302`).
+ Every other finding fails the step. The 9B8 chunk-boundary fragment
+ allowance in `.gitleaks.toml` applied only to a file that is now not
+ scanned, so it was removed. The other allowances are unchanged.
+ **Accepted limit, stated in the docs:** a credential committed in one of
+ the 26 listed files is not found.
+2. **R3 P1 2 (sentinel overwrote a tracked file).** The sentinel goes in
+ `gitleaks-gate-sentinel-<random>.env`, a new name on each run, opened
+ with `O_CREATE|O_EXCL` (`main.go:200`). Only a finding with the
+ sentinel's exact value in that file is set aside (`main.go:219`).
+3. **Self-test.** The census, checklist and chunk-boundary cases went with
+ the judge. The new `trackedTest` (`selftest.go:146`) builds a git
+ repository and runs `scanTree`, the path the real scan takes. It plants
+ a key in a tracked `gitleaks-gate-sentinel.env` and in a census file the
+ list does not name, and requires both to be reported. It plants a key in
+ every listed file and requires none of those to be reported. For each
+ listed name it plants three near misses (`x/` + path, path + `.orig`,
+ `zz_` + file name) and requires each to be reported. It also untracks one
+ listed file and requires `copyTracked` to refuse. With the old sentinel
+ code restored (fixed name, `O_TRUNC`), the self-test fails with
+ "THE PLANTED KEY WAS HIDDEN in gitleaks-gate-sentinel.env".
+4. **Docs.** `.gitleaks.toml` header, `.amadan/ci.d/80-gitleaks` header,
+ the Makefile comment, `.amadan/README.md` ("`gitleaks`: what turns it
+ red") and the AGENTS.md bullet now say which files are not scanned and
+ why: they hold content digests, not secrets.
+
+Local results at 99612d24: `sh .amadan/ci.d/80-gitleaks` passes (10,581
+files scanned, 26 not scanned, clean). In a scratch clone with planted keys
+in a new source file, a tracked `gitleaks-gate-sentinel.env` and a census
+file not on the list, it fails with all three reported.
+
+## What to check
+
+1. **Both R3 P1s are closed.** No finding is accepted because of its shape
+ or its line. Nothing except the sentinel's exact value in its own random
+ file is set aside.
+2. **The exclusion is exact and cannot be widened by a rename.** Check that
+ it uses string equality on the full git path, with no glob, prefix,
+ suffix, case folding or path cleaning that a crafted tracked path
+ (`./`, `..`, a trailing slash, a different case, a symlink, a
+ submodule, a path git quotes) could exploit. Check that a listed file
+ renamed elsewhere is scanned under its new name, and that a stale entry
+ fails. Known edge: one commit that renames listed file A and adds a new
+ file at A keeps A excluded. The commit's diff shows the rename, but
+ `notscanned.go` does not change. Judge whether that is acceptable
+ under "named files are not scanned" or is a P1.
+3. **The sentinel cannot shadow a tracked file.** Look for any ordering,
+ name collision or error path where a tracked file's bytes are replaced,
+ dropped or set aside. Check that `trackedTest` really exercises the
+ production `scanTree`/`copyTracked`, and would fail if either regressed.
+4. **Fails closed.** Missing or wrong-version binary, a config that does
+ not load, a truncated report, zero files copied, a missing sentinel
+ finding, a stale list entry, a tracked `.gitleaksignore`.
+5. **The docs are true.** Every text that describes the gate (config
+ header, step header, Makefile, README, AGENTS.md) says plainly that the
+ listed files are not scanned and why, and matches the code. Nothing
+ still describes the judge.
+6. The remaining `.gitleaks.toml` allowances are byte-for-byte the R3 ones,
+ minus the 9B8 fragment.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Follow-up list only.
+
+## Output
+
+Findings ranked P1, then P2, then P3, each with file:line, failure scenario
+and fix. End with exactly one verdict: READY, READY AFTER FIXES, or NOT
+READY. Do not edit files, spawn reviewers or run full suites.
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251.md b/docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251.md
new file mode 100644
index 000000000..78b696947
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251.md
@@ -0,0 +1,53 @@
+# Review brief: branch gitleaks-1251, round 3 of 3
+
+Repo carlos/platform, branch `gitleaks-1251`, commit c057934314434f290a5d89459f8dc5dd7fee68f6.
+Under review: the diff `origin/main...c057934314434f290a5d89459f8dc5dd7fee68f6`.
+Authorities: amadan #1251 (the design), AGENTS.md ("Stopping rules").
+
+**Round history.** This design had two earlier rounds on branch race-helpers:
+`docs/superpowers/reviews/FINDINGS-race-helpers-R1.md` (on main) rejected a
+path-plus-hex allowance; a scoped check then rejected whole-line patterns
+because the census entry's second field accepted arbitrary text. Stopping
+rule 2 applied and Paul chose to split gitleaks out with a tighter design.
+This is the last round.
+
+You are the independent reviewer. The invariant: **an allowance can only
+ever hide an approved digest, never a credential.**
+
+The design: `.gitleaks.toml` holds 35 exact anchored values and no shape
+patterns; `scripts/gitleaks-gate` runs the scan and accepts a finding as a
+digest only if the whole line is a valid census or checklist entry AND the
+reported secret is that entry's digest field; a self-test plants generated
+keys (38 cases) and requires each to be reported.
+
+## What to check
+
+1. Try to break the invariant. Can any credential, in any field of a census
+ entry, the JSON checklist, a chunk boundary, a multi-line value, a
+ comment after an entry or an ordinary file, pass the gate or the 35
+ exact values? Does the gate parse gitleaks' report so a crafted line or
+ secret can't confuse it (Match vs Secret vs Line, encoded or decoded
+ findings)?
+2. Known limit: a 64-character lowercase hex value in the digest field is
+ accepted. Does the census test independently fail a digest that isn't
+ the real source digest, so a real key there can't reach main? Verify
+ for both census entries and the checklist file.
+3. Fails closed: bad or missing config, missing binary, wrong version,
+ truncated or unparsable report, zero files scanned.
+4. Does the self-test run in CI on every run, and fail if planted keys go
+ unreported?
+5. Are all 35 exact values really non-secrets?
+6. README, AGENTS.md and the step header match the scripts.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Follow-up list only.
+
+## Output
+
+Findings ranked P1, P2, P3 with file:line, failure scenario and fix. End
+with exactly one verdict: READY, READY AFTER FIXES, or NOT READY. A NOT READY
+in this round also says whether cutting the step would be better. Do not
+edit files, spawn reviewers or run full suites.
diff --git a/scripts/gitleaks-gate/main.go b/scripts/gitleaks-gate/main.go
new file mode 100644
index 000000000..8f9e5726d
--- /dev/null
+++ b/scripts/gitleaks-gate/main.go
@@ -0,0 +1,367 @@
+// Command gitleaks-gate is `make gitleaks` (.amadan/ci.d/80-gitleaks): it
+// proves the scan still finds planted keys, then scans the tracked files.
+//
+// gitleaks does the finding, with its default rules less the exact values
+// .gitleaks.toml allows. This program decides what is scanned and what a
+// finding means, as scripts/govulncheck-gate does for govulncheck: every
+// tracked file is scanned except the ones notscanned.go names by exact path,
+// and every finding fails the step except the key the gate plants itself.
+//
+// Anything it cannot establish is a failure: the wrong binary, a config
+// gitleaks will not load, a report it cannot read, or a scan that did not
+// find the key planted beside the tracked files.
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "debug/buildinfo"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io/fs"
+ "math"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "syscall"
+)
+
+const (
+ gitleaksModule = "github.com/zricethezav/gitleaks/v8"
+
+ // exitFindings is the status gitleaks is told to use for "found
+ // something", so that its own failures (status 1) cannot be mistaken
+ // for a scan that finished.
+ exitFindings = 3
+)
+
+// finding is the part of gitleaks' JSON report the gate reads.
+type finding struct {
+ RuleID string
+ File string
+ Secret string
+ StartLine int
+}
+
+func main() {
+ bin := flag.String("gitleaks", "", "path to the gitleaks binary")
+ version := flag.String("version", "", "the version the gitleaks binary must be")
+ config := flag.String("config", ".gitleaks.toml", "path to the gitleaks config")
+ flag.Parse()
+
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ err := run(ctx, *bin, *version, *config)
+ stop()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "gitleaks-gate:", err)
+ os.Exit(1)
+ }
+}
+
+func run(ctx context.Context, bin, version, config string) error {
+ if err := checkBinary(bin, version); err != nil {
+ return err
+ }
+ bin, err := filepath.Abs(bin)
+ if err != nil {
+ return err
+ }
+ if config, err = filepath.Abs(config); err != nil {
+ return err
+ }
+ if err := selfTest(ctx, bin, config); err != nil {
+ return fmt.Errorf("self-test: %w", err)
+ }
+ return scanTracked(ctx, bin, config)
+}
+
+// checkBinary refuses anything but the pinned gitleaks. The version comes
+// from the build information, because a `go install` build prints a
+// placeholder for `gitleaks version`.
+func checkBinary(bin, version string) error {
+ if bin == "" || version == "" {
+ return errors.New("-gitleaks and -version are required")
+ }
+ info, err := buildinfo.ReadFile(bin)
+ if err != nil {
+ return fmt.Errorf("read the gitleaks binary: %w", err)
+ }
+ if info.Main.Path != gitleaksModule || info.Main.Version != version {
+ return fmt.Errorf("%s is %s %s, want %s %s", bin, info.Main.Path, info.Main.Version, gitleaksModule, version)
+ }
+ return nil
+}
+
+// scan runs gitleaks over dir and returns everything it reported. Any end
+// other than a finished scan with a report that agrees with its exit status
+// is an error.
+func scan(ctx context.Context, bin, config, dir string) ([]finding, error) {
+ reportDir, err := os.MkdirTemp("", "gitleaks-gate-report-")
+ if err != nil {
+ return nil, err
+ }
+ defer os.RemoveAll(reportDir)
+ report := filepath.Join(reportDir, "report.json")
+
+ // --ignore-gitleaks-allow: a `gitleaks:allow` comment would otherwise
+ // hide a finding on its line with no review of the value.
+ cmd := exec.CommandContext(ctx, bin, "dir",
+ "--no-banner", "--no-color", "--log-level", "error",
+ "--ignore-gitleaks-allow",
+ "--config", config,
+ "--report-format", "json", "--report-path", report,
+ "--exit-code", strconv.Itoa(exitFindings),
+ ".")
+ cmd.Dir = dir
+ var output bytes.Buffer
+ cmd.Stdout, cmd.Stderr = &output, &output
+ status := 0
+ if err := cmd.Run(); err != nil {
+ var exit *exec.ExitError
+ if !errors.As(err, &exit) {
+ return nil, fmt.Errorf("run gitleaks: %w", err)
+ }
+ status = exit.ExitCode()
+ }
+ if status != 0 && status != exitFindings {
+ return nil, fmt.Errorf("gitleaks exited %d: %s", status, strings.TrimSpace(output.String()))
+ }
+ data, err := os.ReadFile(report)
+ if err != nil {
+ return nil, fmt.Errorf("read the gitleaks report: %w", err)
+ }
+ var findings []finding
+ if err := json.Unmarshal(data, &findings); err != nil {
+ return nil, fmt.Errorf("parse the gitleaks report: %w", err)
+ }
+ if (status == exitFindings) != (len(findings) > 0) {
+ return nil, fmt.Errorf("gitleaks exited %d with %d findings in its report", status, len(findings))
+ }
+ return findings, nil
+}
+
+// scanTracked scans the tracked files of the repository in the current
+// directory and fails on every finding.
+func scanTracked(ctx context.Context, bin, config string) error {
+ tree, err := scanTree(ctx, bin, config, ".")
+ if err != nil {
+ return err
+ }
+ fmt.Printf("gitleaks: scanned %d tracked files; %d not scanned, by exact path (scripts/gitleaks-gate/notscanned.go)\n",
+ tree.scanned, tree.skipped)
+ if len(tree.standing) == 0 {
+ fmt.Println("gitleaks: clean")
+ return nil
+ }
+ for _, f := range tree.standing {
+ // Never the value: this goes to the CI log.
+ fmt.Printf("%s:%d: %s\n", f.File, f.StartLine, f.RuleID)
+ }
+ return fmt.Errorf("%d findings above: remove the value and rotate it if it was ever real; a fake a test needs is allowed by exact value in .gitleaks.toml", len(tree.standing))
+}
+
+// treeScan is what scanTree found in one repository.
+type treeScan struct {
+ scanned int // tracked files copied and scanned
+ skipped int // tracked files left out because notScanned names them
+ standing []finding // every finding but the planted sentinel, by file and line
+}
+
+// scanTree copies the tracked files of repo into a scratch directory, adds a
+// sentinel key beside them, scans the lot and returns every finding but the
+// sentinel's. A scan that does not report the sentinel is an error.
+//
+// The sentinel goes in a file whose name is random for each run and which is
+// created only if nothing is there, so it can never replace or hide a tracked
+// file: a tracked file of any name, gitleaks-gate-sentinel.env included, is
+// copied and scanned like the rest. Only the sentinel's own finding, its
+// exact value in its own file, is set aside.
+func scanTree(ctx context.Context, bin, config, repo string) (treeScan, error) {
+ dir, err := os.MkdirTemp("", "gitleaks-gate-tree-")
+ if err != nil {
+ return treeScan{}, err
+ }
+ defer os.RemoveAll(dir)
+
+ scanned, skipped, err := copyTracked(ctx, repo, dir)
+ if err != nil {
+ return treeScan{}, err
+ }
+ sentinel := newKey(40)
+ sentinelFile := "gitleaks-gate-sentinel-" + newKey(12) + ".env"
+ out, err := os.OpenFile(filepath.Join(dir, sentinelFile), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if err != nil {
+ return treeScan{}, fmt.Errorf("plant the sentinel: %w", err)
+ }
+ _, err = fmt.Fprintf(out, "api_key = \"%s\"\n", sentinel)
+ if cerr := out.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil {
+ return treeScan{}, fmt.Errorf("plant the sentinel: %w", err)
+ }
+
+ findings, err := scan(ctx, bin, config, dir)
+ if err != nil {
+ return treeScan{}, err
+ }
+ tree := treeScan{scanned: scanned, skipped: skipped}
+ sawSentinel := false
+ for _, f := range findings {
+ if f.File == sentinelFile && f.Secret == sentinel {
+ sawSentinel = true
+ continue
+ }
+ tree.standing = append(tree.standing, f)
+ }
+ if !sawSentinel {
+ return treeScan{}, errors.New("the scan did not report the key planted beside the tracked files")
+ }
+ sort.Slice(tree.standing, func(a, b int) bool {
+ if tree.standing[a].File != tree.standing[b].File {
+ return tree.standing[a].File < tree.standing[b].File
+ }
+ return tree.standing[a].StartLine < tree.standing[b].StartLine
+ })
+ return tree, nil
+}
+
+// copyTracked copies every tracked regular file of repo into dir, except the
+// ones notScanned names, and returns how many it copied and how many it left
+// out. It reads the list from the index and the bytes from the working tree,
+// so an uncommitted edit is scanned and an untracked file is not. git archive
+// would do the copying but honours export-ignore, which would let a tracked
+// .gitattributes take files out of the scan.
+//
+// Every notScanned entry has to be a tracked file: one that is not is an
+// error, so the list cannot keep a path that a new file could later take.
+func copyTracked(ctx context.Context, repo, dir string) (copied, skipped int, err error) {
+ cmd := exec.CommandContext(ctx, "git", "ls-files", "-z", "--stage")
+ cmd.Dir = repo
+ out, err := cmd.Output()
+ if err != nil {
+ return 0, 0, fmt.Errorf("list tracked files: %w", err)
+ }
+ excluded := map[string]bool{}
+ for _, path := range notScanned {
+ excluded[path] = false
+ }
+ seen := map[string]bool{}
+ for _, entry := range strings.Split(string(out), "\x00") {
+ meta, path, ok := strings.Cut(entry, "\t")
+ if !ok || seen[path] {
+ continue
+ }
+ seen[path] = true
+ if filepath.Base(path) == ".gitleaksignore" {
+ return 0, 0, fmt.Errorf("%s is tracked: findings are allowed in .gitleaks.toml, by value, and not by fingerprint", path)
+ }
+ // Symlinks (120000) and submodules (160000) have no content here.
+ if !strings.HasPrefix(meta, "100") {
+ continue
+ }
+ if _, listed := excluded[path]; listed {
+ excluded[path] = true
+ skipped++
+ continue
+ }
+ source := filepath.Join(repo, filepath.FromSlash(path))
+ info, err := os.Lstat(source)
+ if errors.Is(err, fs.ErrNotExist) {
+ continue // deleted in the working tree: nothing left to scan
+ }
+ if err != nil {
+ return 0, 0, err
+ }
+ if !info.Mode().IsRegular() {
+ continue
+ }
+ data, err := os.ReadFile(source)
+ if err != nil {
+ return 0, 0, err
+ }
+ target := filepath.Join(dir, filepath.FromSlash(path))
+ if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
+ return 0, 0, err
+ }
+ if err := os.WriteFile(target, data, 0o600); err != nil {
+ return 0, 0, err
+ }
+ copied++
+ }
+ for _, path := range notScanned {
+ if !excluded[path] {
+ return 0, 0, fmt.Errorf("notscanned.go names %s, which is not a tracked file: take it off the list", path)
+ }
+ }
+ if copied == 0 {
+ return 0, 0, errors.New("git lists no tracked files to scan")
+ }
+ return copied, skipped, nil
+}
+
+// newKey returns a random credential-shaped value of n characters. Its
+// alphabet leaves out vowels and the letters of gitleaks' short stopwords
+// (http, sync, vpn and the like), any of which would make the generic rule
+// wave the value through and the test prove nothing.
+func newKey(n int) string {
+ const letters = "BCDFGJKLNPRSTZbcdfgjklnprstz"
+ const digits = "2346789"
+ alphabet := letters + digits
+ raw := make([]byte, n)
+ if _, err := rand.Read(raw); err != nil {
+ panic(err)
+ }
+ key := make([]byte, n)
+ for i, b := range raw {
+ // A value of letters alone is also waved through, so every
+ // fourth character is a digit.
+ if i%4 == 3 {
+ key[i] = digits[int(b)%len(digits)]
+ } else {
+ key[i] = alphabet[int(b)%len(alphabet)]
+ }
+ }
+ return string(key)
+}
+
+// newDigest returns 64 random lowercase hex characters that gitleaks' generic
+// rule will report: no stopword inside it, and enough entropy.
+func newDigest() string {
+ for {
+ raw := make([]byte, 32)
+ if _, err := rand.Read(raw); err != nil {
+ panic(err)
+ }
+ digest := hex.EncodeToString(raw)
+ if strings.Contains(digest, "dead") || strings.Contains(digest, "feed") ||
+ strings.Contains(digest, "000000") || strings.Contains(digest, "aaaaaa") {
+ continue
+ }
+ if entropy(digest) > 3.6 {
+ return digest
+ }
+ }
+}
+
+// entropy is the Shannon entropy gitleaks' generic rule requires above 3.5.
+func entropy(s string) float64 {
+ counts := map[rune]int{}
+ for _, r := range s {
+ counts[r]++
+ }
+ total := 0.0
+ for _, n := range counts {
+ p := float64(n) / float64(len(s))
+ total -= p * math.Log2(p)
+ }
+ return total
+}
diff --git a/scripts/gitleaks-gate/notscanned.go b/scripts/gitleaks-gate/notscanned.go
new file mode 100644
index 000000000..889e92e5a
--- /dev/null
+++ b/scripts/gitleaks-gate/notscanned.go
@@ -0,0 +1,49 @@
+package main
+
+// notScanned names the tracked files the gate does not scan at all. Nothing
+// in them is read by gitleaks, so a credential committed in one of them is
+// NOT found.
+//
+// They hold sha256 digests of source, not secrets: the census test files pin
+// a digest per unit, and the design checklist pins a digest per file in its
+// source_hashes. gitleaks' generic rule reads a digest after a key-like word
+// as a key, and no allowance can tell a digest from a 64-character hex key,
+// so these files are left out whole, by name, rather than judged by shape.
+//
+// Each entry is a whole repository path, compared for equality: no globs, no
+// directory prefixes, no patterns. A file renamed away from its entry is
+// scanned under its new name, and the gate fails while an entry names a path
+// that git does not track, so a stale entry cannot later cover a new file.
+//
+// The list holds only the files gitleaks flags. A census file not listed here
+// is scanned like any other; if a new census layer turns the step red with
+// digest findings, check that every finding is a digest, then add the file's
+// exact path below.
+var notScanned = []string{
+ "implementation/always-awake-consumers.json",
+ "internal/provision/agent_start_demo_3_census_test.go",
+ "internal/provision/claim_empty_cohort_fix1_census_test.go",
+ "internal/provision/console_remote_instances_census_test.go",
+ "internal/provision/demo_census_test.go",
+ "internal/provision/edge_asset_cache_1_census_test.go",
+ "internal/provision/fleet_public_routes_census_test.go",
+ "internal/provision/instance_egress_sizes_census_test.go",
+ "internal/provision/instance_restore_658_census_test.go",
+ "internal/provision/linked_deployments_slice1_census_test.go",
+ "internal/provision/nearest_region_a_census_test.go",
+ "internal/provision/nearest_region_b_census_test.go",
+ "internal/provision/operator_pages_census_test.go",
+ "internal/provision/plan14_e_write_census_test.go",
+ "internal/provision/plan14_p3_census_test.go",
+ "internal/provision/plan9_b8_census_test.go",
+ "internal/provision/platform_mail_submission_census_test.go",
+ "internal/provision/region_ha_g2_fixes_census_test.go",
+ "internal/provision/regional_domains_447_census_test.go",
+ "internal/provision/retire_app_lock_407_census_test.go",
+ "internal/provision/retire_window_415_census_test.go",
+ "internal/provision/rootfs_apps_4_census_test.go",
+ "internal/provision/self_serve_moves1_census_test.go",
+ "internal/provision/stateless_placement_census_test.go",
+ "internal/provision/stateless_replicas_4_drill1_census_test.go",
+ "internal/provision/team_scoped_credentials_census_test.go",
+}
diff --git a/scripts/gitleaks-gate/selftest.go b/scripts/gitleaks-gate/selftest.go
new file mode 100644
index 000000000..311af191c
--- /dev/null
+++ b/scripts/gitleaks-gate/selftest.go
@@ -0,0 +1,295 @@
+package main
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+)
+
+// The self-test runs inside the gitleaks step because it needs the binary.
+// It plants keys generated at run time, so none is ever committed.
+//
+// Each single-file case is scanned twice:
+//
+// - with gitleaks' default rules alone, the control: the planted value has
+// to be found there, or the case proves nothing;
+// - with the real config: the planted key must still be reported.
+//
+// Then a whole repository is built and put through scanTree, the path the
+// real scan takes, to prove what is and is not scanned (trackedTest).
+const ordinaryFile = "internal/widgets/pump.go"
+
+// selfCase is one file to scan and the value that must be reported on line.
+type selfCase struct {
+ name string
+ file string
+ body string
+ line int
+ secret string
+}
+
+func selfTest(ctx context.Context, bin, config string) error {
+ cases := selfCases()
+
+ control, err := os.MkdirTemp("", "gitleaks-gate-control-")
+ if err != nil {
+ return err
+ }
+ defer os.RemoveAll(control)
+ defaults := filepath.Join(control, "defaults.toml")
+ if err := os.WriteFile(defaults, []byte("[extend]\nuseDefault = true\n"), 0o600); err != nil {
+ return err
+ }
+
+ results := make([]error, len(cases))
+ slots := make(chan struct{}, 4)
+ var wg sync.WaitGroup
+ for i, c := range cases {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ slots <- struct{}{}
+ defer func() { <-slots }()
+ results[i] = c.run(ctx, bin, defaults, config)
+ }()
+ }
+ wg.Wait()
+
+ var failed []error
+ planted := 0
+ for i, c := range cases {
+ verdict := "reported"
+ if results[i] != nil {
+ failed = append(failed, fmt.Errorf("%s: %w", c.name, results[i]))
+ verdict = "FAILED"
+ } else {
+ planted++
+ }
+ fmt.Printf("self-test: %-8s %s\n", verdict, c.name)
+ }
+ tracked, err := trackedTest(ctx, bin, config, control)
+ if err != nil {
+ failed = append(failed, fmt.Errorf("tracked files: %w", err))
+ }
+ closed, err := failClosed(ctx, bin, config, control)
+ if err != nil {
+ failed = append(failed, err)
+ }
+ if len(failed) > 0 {
+ return errors.Join(failed...)
+ }
+ fmt.Printf("self-test: %d planted keys reported, %d tracked files judged, %d broken setups refused\n",
+ planted, tracked, closed)
+ return nil
+}
+
+func (c selfCase) run(ctx context.Context, bin, defaults, config string) error {
+ dir, err := os.MkdirTemp("", "gitleaks-gate-case-")
+ if err != nil {
+ return err
+ }
+ defer os.RemoveAll(dir)
+ path := filepath.Join(dir, filepath.FromSlash(c.file))
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ return err
+ }
+ if err := os.WriteFile(path, []byte(c.body), 0o600); err != nil {
+ return err
+ }
+
+ found, err := scan(ctx, bin, defaults, dir)
+ if err != nil {
+ return fmt.Errorf("control scan: %w", err)
+ }
+ if !c.reported(found) {
+ return fmt.Errorf("the default rules do not flag line %d, so this case proves nothing", c.line)
+ }
+ if found, err = scan(ctx, bin, config, dir); err != nil {
+ return err
+ }
+ if !c.reported(found) {
+ return errors.New("THE PLANTED KEY WAS HIDDEN")
+ }
+ return nil
+}
+
+// reported says whether findings include this case's value on its line.
+func (c selfCase) reported(findings []finding) bool {
+ for _, f := range findings {
+ if f.File == c.file && f.StartLine == c.line && strings.Contains(f.Secret, c.secret) {
+ return true
+ }
+ }
+ return false
+}
+
+// trackedTest builds a git repository and scans it with scanTree, as the
+// real scan does, to prove three things:
+//
+// - a tracked file named gitleaks-gate-sentinel.env, the sentinel's old
+// fixed name, is scanned and its key reported: the sentinel cannot
+// replace or hide a tracked file;
+// - every file notScanned names is left out, and nothing else: the same
+// key under a near miss of each name (another directory above it, a
+// suffix, a prefix on the file name) is reported, as is one in a census
+// file the list does not name;
+// - a list entry that git does not track is refused.
+//
+// It returns how many tracked files it judged.
+func trackedTest(ctx context.Context, bin, config, scratch string) (int, error) {
+ repo := filepath.Join(scratch, "repo")
+ if err := os.MkdirAll(repo, 0o700); err != nil {
+ return 0, err
+ }
+ want := map[string]string{} // file: the key that must be reported in it
+ hidden := map[string]bool{} // files whose key must not be reported
+ plant := func(file string) (string, error) {
+ key := newKey(40)
+ target := filepath.Join(repo, filepath.FromSlash(file))
+ if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
+ return "", err
+ }
+ return key, os.WriteFile(target, []byte("api_key = \""+key+"\"\n"), 0o600)
+ }
+ expect := func(file string) error {
+ key, err := plant(file)
+ want[file] = key
+ return err
+ }
+
+ if err := expect("gitleaks-gate-sentinel.env"); err != nil {
+ return 0, err
+ }
+ if err := expect("internal/provision/zz_planted_census_test.go"); err != nil {
+ return 0, err
+ }
+ for _, p := range notScanned {
+ if _, err := plant(p); err != nil {
+ return 0, err
+ }
+ hidden[p] = true
+ dir, base := path.Split(p)
+ for _, near := range []string{"x/" + p, p + ".orig", dir + "zz_" + base} {
+ if err := expect(near); err != nil {
+ return 0, err
+ }
+ }
+ }
+ if err := git(ctx, repo, "init", "-q"); err != nil {
+ return 0, err
+ }
+ if err := git(ctx, repo, "add", "-A"); err != nil {
+ return 0, err
+ }
+
+ tree, err := scanTree(ctx, bin, config, repo)
+ if err != nil {
+ return 0, err
+ }
+ if tree.skipped != len(notScanned) {
+ return 0, fmt.Errorf("%d files left out, want the %d notscanned.go names", tree.skipped, len(notScanned))
+ }
+ got := map[string]bool{}
+ for _, f := range tree.standing {
+ switch {
+ case hidden[f.File]:
+ return 0, fmt.Errorf("%s is listed in notscanned.go but was scanned", f.File)
+ case want[f.File] == "" || f.Secret != want[f.File] || f.StartLine != 1:
+ return 0, fmt.Errorf("unexpected finding at %s:%d", f.File, f.StartLine)
+ }
+ got[f.File] = true
+ }
+ var missed []string
+ for file := range want {
+ if !got[file] {
+ missed = append(missed, file)
+ }
+ }
+ sort.Strings(missed)
+ if len(missed) > 0 {
+ return 0, fmt.Errorf("THE PLANTED KEY WAS HIDDEN in %s", strings.Join(missed, ", "))
+ }
+ fmt.Printf("self-test: %-8s a tracked file named gitleaks-gate-sentinel.env\n", "reported")
+ fmt.Printf("self-test: %-8s %d near misses of the names notscanned.go lists\n", "reported", len(want)-1)
+ fmt.Printf("self-test: %-8s the %d files notscanned.go lists\n", "skipped", len(hidden))
+
+ // Untrack one listed file: the list now names a path git does not
+ // track, which must be refused.
+ if err := git(ctx, repo, "rm", "-q", "--cached", notScanned[0]); err != nil {
+ return 0, err
+ }
+ if _, _, err := copyTracked(ctx, repo, filepath.Join(scratch, "stale")); err == nil {
+ return 0, fmt.Errorf("a notscanned.go entry git does not track (%s) was not refused", notScanned[0])
+ }
+ fmt.Printf("self-test: %-8s a notscanned.go entry git does not track\n", "refused")
+ return len(want) + len(hidden), nil
+}
+
+// git runs git in repo with no inherited repository settings, so it can
+// only act on repo.
+func git(ctx context.Context, repo string, args ...string) error {
+ cmd := exec.CommandContext(ctx, "git", args...)
+ cmd.Dir = repo
+ for _, kv := range os.Environ() {
+ if !strings.HasPrefix(kv, "GIT_") {
+ cmd.Env = append(cmd.Env, kv)
+ }
+ }
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
+
+// failClosed checks that a setup that cannot scan is an error, never a pass.
+func failClosed(ctx context.Context, bin, config, scratch string) (int, error) {
+ dir := filepath.Join(scratch, "tree")
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return 0, err
+ }
+ broken := filepath.Join(scratch, "broken.toml")
+ if err := os.WriteFile(broken, []byte("[[allowlists]\nregexes = ["), 0o600); err != nil {
+ return 0, err
+ }
+ setups := []struct{ name, bin, config string }{
+ {"a config that does not parse", bin, broken},
+ {"a config that does not exist", bin, filepath.Join(scratch, "missing.toml")},
+ {"a missing gitleaks binary", filepath.Join(scratch, "missing-gitleaks"), config},
+ }
+ for _, s := range setups {
+ if _, err := scan(ctx, s.bin, s.config, dir); err == nil {
+ return 0, fmt.Errorf("%s did not fail the scan", s.name)
+ }
+ fmt.Printf("self-test: %-8s %s\n", "refused", s.name)
+ }
+ if err := checkBinary(filepath.Join(scratch, "missing-gitleaks"), "v0.0.0"); err == nil {
+ return 0, errors.New("a missing gitleaks binary passed the version check")
+ }
+ return len(setups), nil
+}
+
+func selfCases() []selfCase {
+ key, digest := newKey(40), newDigest()
+ ordinary := func(name, line, secret string) selfCase {
+ body := "package widgets\n\n" + line + "\n"
+ return selfCase{name: name, file: ordinaryFile, body: body, line: 3, secret: secret}
+ }
+ return []selfCase{
+ ordinary("source file: a key", `const apiKey = "`+key+`"`, key),
+ ordinary("source file: a 64-hex key", `const signingSecret = "`+digest+`"`, digest),
+ ordinary("source file: a census-shaped entry", `{"internal/console/auth.go", "Pump.Start", "nonrecord", "key:RecordKey", "`+digest+`"},`, digest),
+ ordinary("source file: a key marked gitleaks:allow", `const apiKey = "`+key+`" // gitleaks:allow`, key),
+ ordinary("source file: a test's fake value outside tests", `const token = "tok-`+`flagship-2"`, "tok-"+"flagship-2"),
+ {
+ name: "allowed file: another key beside its allowed value", file: "internal/console/testdata/configseal_vectors.json",
+ body: "{\n \"note\": \"vectors\",\n \"api_key\": \"" + key + "\"\n}\n", line: 3, secret: key,
+ },
+ }
+}