ci: gitleaks step that can only accept approved digests (#1251)
80-gitleaks runs make gitleaks: v8.30.1, pinned, over the tracked files. Digests are judged by scripts/gitleaks-gate and not allowed in .gitleaks.toml. A gitleaks allowance tests the line or the reported secret, never both, so a census-shaped line could hide a key in its unit field. The gate accepts a finding only when the whole line is a well-formed entry, each field limited to what the census can write, and the reported secret is that entry's digest field. Every other allowance is an exact, anchored value, including the one digest fragment a chunk boundary cuts in plan9_b8_census_test.go, which is scoped to that file. Before each scan the gate plants keys generated at run time in every census field, the JSON checklist, a chunk boundary and ordinary source, and requires each to be reported. Each case is also scanned with the default rules alone, so one those rules would miss fails. Well-formed new entries must pass. A missing binary, wrong version, broken config or unreadable report fails the step.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+1,064
−4
.amadan/README.md+46 −3.amadan/ci.d/80-gitleaks+27 −0.gitleaks.toml+143 −0AGENTS.md+8 −0Makefile+19 −1scripts/gitleaks-gate/judge.go+149 −0scripts/gitleaks-gate/main.go+315 −0scripts/gitleaks-gate/selftest.go+357 −0
CI cancelled — superseded by a newer push — run details
Intent
diff --git a/.amadan/README.md b/.amadan/README.md| index 622b31f8a..d06cbb31c 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, 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 |
| @@ -147,6 +148,48 @@ 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: |
| + |
| +- a finding is not an approved digest and `.gitleaks.toml` does not allow |
| + its exact value; |
| +- a planted key goes unreported, or a well-formed census entry is refused |
| + (the self-test, below); |
| +- 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. |
| + |
| +**Digests are judged by the gate, not allowed in the config.** The census |
| +tests and `implementation/always-awake-consumers.json` pin sha256 digests, |
| +and gitleaks' generic rule reads those as keys. A gitleaks allowance can |
| +test a line or the reported secret, but not both, so a census-shaped line |
| +could hide a key in its unit field. `scripts/gitleaks-gate/judge.go` accepts |
| +a finding only when the whole line is a well-formed entry, every field |
| +holding what the census can write, and the reported secret is that entry's |
| +digest. The one exception is the start of a digest that a gitleaks chunk |
| +boundary cuts in `plan9_b8_census_test.go`, allowed by exact value in that |
| +file alone. |
| + |
| +A 64-character lowercase hex value in the digest field is accepted as a |
| +digest, because nothing in its shape can tell the two apart. |
| + |
| +**The self-test runs first, on every scan.** It generates keys at run time |
| +and plants them in each field of a census entry, in the checklist, at a |
| +chunk boundary and in ordinary source. Each case is also scanned with |
| +gitleaks' default rules alone, so a case the rules would never flag fails |
| +instead of passing for free. It checks that well-formed new entries pass |
| +and that a broken config or a missing binary fails the scan. |
| + |
| +If a new census class, method or key name turns the step red, add it to the |
| +lists in `judge.go`. 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..101cff399 |
| --- /dev/null |
| +++ b/.amadan/ci.d/80-gitleaks |
| @@ -0,0 +1,27 @@ |
| +#!/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. |
| +# |
| +# 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 well-formed census |
| +# entry was refused (scripts/gitleaks-gate/selftest.go); |
| +# - 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..ceea7c3df |
| --- /dev/null |
| +++ b/.gitleaks.toml |
| @@ -0,0 +1,143 @@ |
| +# 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. |
| +# |
| +# Source digests are NOT allowed here. An allowance can test the line or the |
| +# reported secret but not both, so it cannot tell a census entry's digest |
| +# from a key in another field of the same line. scripts/gitleaks-gate/judge.go |
| +# decides those, and its self-test plants keys to prove it. |
| +# |
| +# 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 |
| + |
| +# The start of one census digest. gitleaks reads a big file in chunks, and in |
| +# this file one chunk ends inside a digest, so what it reports is the digest's |
| +# first 59 characters, which no whole-entry check can recognise. Older census |
| +# layers are frozen, so that boundary does not move. The self-test finds this |
| +# value here and checks it is honoured in this file and nowhere else. |
| +[[allowlists]] |
| +description = "digest fragment at a chunk boundary in the 9B8 census" |
| +targetRules = ["generic-api-key"] |
| +condition = "AND" |
| +paths = ['''^internal/provision/plan9_b8_census_test\.go$'''] |
| +regexes = ['''^c635b439ae4bec54933118a8ff983251d47b81b40d1bb42663e881b55a6$'''] |
| + |
| +# 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 94cd29d99..d78d41e56 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -304,6 +304,14 @@ anything. |
| `captureLogBuffer`), never a plain `bytes.Buffer`, and a goroutine a |
| test starts ends before the test does. `internal/activator` and |
| `internal/lease` are 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. Census and checklist digests are |
| + judged by `scripts/gitleaks-gate/judge.go`, so a new census class, method |
| + or key name is added to its lists. `.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..f976f66eb 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,24 @@ 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. 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/scripts/gitleaks-gate/judge.go b/scripts/gitleaks-gate/judge.go| new file mode 100644 |
| index 000000000..8577d55e3 |
| --- /dev/null |
| +++ b/scripts/gitleaks-gate/judge.go |
| @@ -0,0 +1,149 @@ |
| +package main |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| +) |
| + |
| +// What an approved digest looks like. gitleaks' generic rule reads a source |
| +// digest as a key whenever the field before it names one (key:RecordKey), so |
| +// the digests the repository pins have to be accepted somewhere. |
| +// |
| +// They are accepted here and not in .gitleaks.toml because an allowlist |
| +// cannot say what has to be true. A gitleaks allowance tests the line or the |
| +// reported secret, never both at once, and a line can be a perfect census |
| +// entry while the secret reported on it is another field: a bare key in the |
| +// unit field, after a file named auth.go, is a valid-looking unit name. So |
| +// approve holds the two together: the whole line must be a well-formed entry |
| +// AND the reported secret must be that entry's digest field. |
| +// |
| +// Every field below is limited to what censusParse |
| +// (internal/provision/plan9_b8_census_test.go) can write. A census change that |
| +// adds a class, a method or a key name turns the gate red here until the |
| +// lists catch up, which is the safe direction. |
| +const ( |
| + goIdent = `[A-Za-z_][A-Za-z0-9_]*` |
| + |
| + // A repository-relative Go file: no separators a key=value needs. |
| + entryFile = `(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*\.go` |
| + |
| + // censusParse's unit names: Func, Recv.Method (? when the receiver has |
| + // no name), "var name", "var#1" for a grouped declaration, and #N on a |
| + // name seen twice in one file. |
| + entryUnit = `(?:` + |
| + `(?:(?:` + goIdent + `|\?)\.)?` + goIdent + `(?:#[0-9]+)?` + |
| + `|(?:var|const|type) ` + goIdent + `(?:#[0-9]+)?` + |
| + `|(?:var|const|type)#[0-9]+(?:#[0-9]+)?` + |
| + `)` |
| + |
| + // censusClasses. |
| + entryClass = `(?:record-primitive|record-writer|record-writer-raw|record-transport` + |
| + `|versioned-transport|foreign-recordkey|nonrecord|key-site|reference|testsupport)` |
| + |
| + // censusMethods. |
| + censusMethod = `(?:Put|PutFrom|PutIfAbsent|PutIfAbsentVersioned|PutIfAbsentVersionedAt` + |
| + `|PutObjectFrom|PutReplace|CopyVersion|CopyVersioned|CopyVersionedAt)` |
| + |
| + // censusKeyIdent: censusKeySuffixes, then censusKeyExact. |
| + censusKeyName = `(?:[A-Za-z0-9_]*(?i:recordkey|recordsprefix|sidecarsprefix|sidecarkey` + |
| + `|sidecarmanifestkey|writerecord|sequencedrecord)` + |
| + `|(?i:createrecord|updaterecord|setrecordregion|setrecordmove|setrecordrun` + |
| + `|setrecordinteractive|setrecordseed|setrecordfleetbox|setrecordfirstfleetbox` + |
| + `|setrecordcoordinator|setrecordreplicarelease|setrecordreplicaassignment` + |
| + `|recordreplicaretired|clearrecordreplicaassignment|haltrecordreplicadeploy` + |
| + `|setrecordreplicadeploy|requestrecordreplicaretry|requestreplicaretries` + |
| + `|setrecordassetgen|mintrecordassetgen|createsidecarrecord|claimrawupdaterecord))` |
| + |
| + entryKind = `(?:(?:def|id|sel|str):` + censusMethod + |
| + `|key:` + censusKeyName + |
| + `|lit:(?:instances|sidecars))` |
| + |
| + sha256Hex = `[0-9a-f]{64}` |
| +) |
| + |
| +const ( |
| + categoryCensus = "census entry digests" |
| + categoryChecklist = "design checklist digests" |
| + |
| + checklistFile = "implementation/always-awake-consumers.json" |
| +) |
| + |
| +var ( |
| + censusFile = regexp.MustCompile(`^internal/provision/[^/]+_census_test\.go$`) |
| + |
| + // {"file.go", "unit", "class", "kind,kind", "digest"}, or the }) that |
| + // closes a layer built with append. |
| + censusEntry = regexp.MustCompile(`^[ \t]*(?:censusEntry)?\{"` + entryFile + `", "` + entryUnit + |
| + `", "` + entryClass + `", "` + entryKind + `(?:,` + entryKind + `)*", "(` + sha256Hex + `)"\}\)?,?[ \t]*$`) |
| + |
| + // "file.go": "digest", inside source_hashes. |
| + checklistEntry = regexp.MustCompile(`^[ \t]*"` + entryFile + `": "(` + sha256Hex + `)",?[ \t]*$`) |
| +) |
| + |
| +// finding is the part of gitleaks' JSON report the gate reads. |
| +type finding struct { |
| + RuleID string |
| + File string |
| + Secret string |
| + StartLine int |
| + EndLine int |
| + Tags []string |
| +} |
| + |
| +// judge decides findings against the files of one scanned tree. |
| +type judge struct { |
| + dir string |
| + lines map[string][]string |
| +} |
| + |
| +func newJudge(dir string) *judge { |
| + return &judge{dir: dir, lines: map[string][]string{}} |
| +} |
| + |
| +// approve names the category a finding is approved under, or returns "" for |
| +// a finding that stands. It reads the line from the scanned file because |
| +// gitleaks' JSON report leaves the line out. |
| +func (j *judge) approve(f finding) string { |
| + if f.RuleID != "generic-api-key" || f.StartLine != f.EndLine { |
| + return "" |
| + } |
| + for _, tag := range f.Tags { |
| + if strings.HasPrefix(tag, "decoded:") { |
| + return "" |
| + } |
| + } |
| + var pattern *regexp.Regexp |
| + var category string |
| + switch { |
| + case censusFile.MatchString(f.File): |
| + pattern, category = censusEntry, categoryCensus |
| + case f.File == checklistFile: |
| + pattern, category = checklistEntry, categoryChecklist |
| + default: |
| + return "" |
| + } |
| + m := pattern.FindStringSubmatch(j.line(f.File, f.StartLine)) |
| + if m == nil || m[1] != f.Secret { |
| + return "" |
| + } |
| + return category |
| +} |
| + |
| +// line returns line n (from 1) of a scanned file, or "" if there is none, |
| +// which no pattern accepts. |
| +func (j *judge) line(file string, n int) string { |
| + lines, ok := j.lines[file] |
| + if !ok { |
| + data, err := os.ReadFile(filepath.Join(j.dir, filepath.FromSlash(file))) |
| + if err == nil { |
| + lines = strings.Split(string(data), "\n") |
| + } |
| + j.lines[file] = lines |
| + } |
| + if n < 1 || n > len(lines) { |
| + return "" |
| + } |
| + return strings.TrimSuffix(lines[n-1], "\r") |
| +} |
diff --git a/scripts/gitleaks-gate/main.go b/scripts/gitleaks-gate/main.go| new file mode 100644 |
| index 000000000..47e1f58fc |
| --- /dev/null |
| +++ b/scripts/gitleaks-gate/main.go |
| @@ -0,0 +1,315 @@ |
| +// 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 a finding means, as |
| +// scripts/govulncheck-gate does for govulncheck: the only findings it can |
| +// accept are source digests (judge.go says exactly which). |
| +// |
| +// 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 |
| + |
| + sentinelFile = "gitleaks-gate-sentinel.env" |
| +) |
| + |
| +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 copies the tracked files into a scratch directory, scans them |
| +// with a sentinel key beside them, and fails on every finding not approved. |
| +func scanTracked(ctx context.Context, bin, config string) error { |
| + dir, err := os.MkdirTemp("", "gitleaks-gate-tree-") |
| + if err != nil { |
| + return err |
| + } |
| + defer os.RemoveAll(dir) |
| + |
| + files, err := copyTracked(ctx, dir) |
| + if err != nil { |
| + return err |
| + } |
| + sentinel := newKey(40) |
| + body := fmt.Sprintf("api_key = \"%s\"\n", sentinel) |
| + if err := os.WriteFile(filepath.Join(dir, sentinelFile), []byte(body), 0o600); err != nil { |
| + return err |
| + } |
| + |
| + findings, err := scan(ctx, bin, config, dir) |
| + if err != nil { |
| + return err |
| + } |
| + j := newJudge(dir) |
| + approved := map[string]int{} |
| + var standing []finding |
| + sawSentinel := false |
| + for _, f := range findings { |
| + if f.File == sentinelFile { |
| + sawSentinel = sawSentinel || f.Secret == sentinel |
| + continue |
| + } |
| + if category := j.approve(f); category != "" { |
| + approved[category]++ |
| + continue |
| + } |
| + standing = append(standing, f) |
| + } |
| + if !sawSentinel { |
| + return errors.New("the scan did not report the key planted beside the tracked files") |
| + } |
| + |
| + fmt.Printf("gitleaks: scanned %d tracked files; approved %d %s and %d %s\n", |
| + files, approved[categoryCensus], categoryCensus, approved[categoryChecklist], categoryChecklist) |
| + if len(standing) == 0 { |
| + fmt.Println("gitleaks: clean") |
| + return nil |
| + } |
| + sort.Slice(standing, func(a, b int) bool { |
| + if standing[a].File != standing[b].File { |
| + return standing[a].File < standing[b].File |
| + } |
| + return standing[a].StartLine < standing[b].StartLine |
| + }) |
| + for _, f := range 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(standing)) |
| +} |
| + |
| +// copyTracked copies every tracked regular file into dir and returns how |
| +// many. 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. |
| +func copyTracked(ctx context.Context, dir string) (int, error) { |
| + out, err := exec.CommandContext(ctx, "git", "ls-files", "-z", "--stage").Output() |
| + if err != nil { |
| + return 0, fmt.Errorf("list tracked files: %w", err) |
| + } |
| + copied := 0 |
| + 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, 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 |
| + } |
| + info, err := os.Lstat(path) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + continue // deleted in the working tree: nothing left to scan |
| + } |
| + if err != nil { |
| + return 0, err |
| + } |
| + if !info.Mode().IsRegular() { |
| + continue |
| + } |
| + data, err := os.ReadFile(path) |
| + if err != nil { |
| + return 0, err |
| + } |
| + target := filepath.Join(dir, filepath.FromSlash(path)) |
| + if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil { |
| + return 0, err |
| + } |
| + if err := os.WriteFile(target, data, 0o600); err != nil { |
| + return 0, err |
| + } |
| + copied++ |
| + } |
| + if copied == 0 { |
| + return 0, errors.New("git lists no tracked files to scan") |
| + } |
| + return copied, 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/selftest.go b/scripts/gitleaks-gate/selftest.go| new file mode 100644 |
| index 000000000..64219c712 |
| --- /dev/null |
| +++ b/scripts/gitleaks-gate/selftest.go |
| @@ -0,0 +1,357 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "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, and scans |
| +// each case 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 and the judge: a planted key must still stand, |
| +// and a well-formed entry must pass. |
| +const ( |
| + plantedCensus = "internal/provision/zz_planted_census_test.go" |
| + ordinaryFile = "internal/widgets/pump.go" |
| + boundaryFile = "internal/provision/plan9_b8_census_test.go" |
| + |
| + // gitleaks reads 100,000 bytes and then up to 25,000 more looking for |
| + // a blank line, so a file with no blank line is cut at this offset. |
| + // The boundary cases fail if a new gitleaks moves it. |
| + chunkBoundary = 125_000 |
| +) |
| + |
| +var knownFragment = regexp.MustCompile(`'''\^([0-9a-f]{59})\$'''`) |
| + |
| +// selfCase is one file to scan. A planted case names the line and the value |
| +// that must be reported; a passing case (passes) names the lines the default |
| +// rules flag and the judge must accept. |
| +type selfCase struct { |
| + name string |
| + file string |
| + body string |
| + lines []int |
| + secret string |
| + exact bool // the reported value must be secret itself, not contain it |
| + passes bool |
| +} |
| + |
| +func selfTest(ctx context.Context, bin, config string) error { |
| + raw, err := os.ReadFile(config) |
| + if err != nil { |
| + return err |
| + } |
| + m := knownFragment.FindSubmatch(raw) |
| + if m == nil { |
| + return fmt.Errorf("%s names no 59-character digest fragment", config) |
| + } |
| + cases := selfCases(string(m[1])) |
| + |
| + 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, passing := 0, 0 |
| + for i, c := range cases { |
| + verdict := "reported" |
| + if c.passes { |
| + verdict = "passes" |
| + } |
| + if results[i] != nil { |
| + failed = append(failed, fmt.Errorf("%s: %w", c.name, results[i])) |
| + verdict = "FAILED" |
| + } else if c.passes { |
| + passing++ |
| + } else { |
| + planted++ |
| + } |
| + fmt.Printf("self-test: %-8s %s\n", verdict, c.name) |
| + } |
| + 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 well-formed cases passed, %d broken setups refused\n", |
| + planted, passing, 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) |
| + } |
| + for _, line := range c.lines { |
| + if !c.reported(found, line) { |
| + return fmt.Errorf("the default rules do not flag line %d, so this case proves nothing", line) |
| + } |
| + } |
| + |
| + found, err = scan(ctx, bin, config, dir) |
| + if err != nil { |
| + return err |
| + } |
| + j := newJudge(dir) |
| + var standing []finding |
| + for _, f := range found { |
| + if j.approve(f) == "" { |
| + standing = append(standing, f) |
| + } |
| + } |
| + if c.passes { |
| + if len(standing) > 0 { |
| + return fmt.Errorf("%d findings stand against a well-formed entry, the first on line %d", len(standing), standing[0].StartLine) |
| + } |
| + return nil |
| + } |
| + if !c.reported(standing, c.lines[0]) { |
| + return errors.New("THE PLANTED KEY WAS HIDDEN") |
| + } |
| + return nil |
| +} |
| + |
| +// reported says whether findings include this case's value on line. |
| +func (c selfCase) reported(findings []finding, line int) bool { |
| + for _, f := range findings { |
| + if f.File != c.file || f.StartLine != line { |
| + continue |
| + } |
| + switch { |
| + case c.secret == "": |
| + return true |
| + case c.exact && f.Secret == c.secret: |
| + return true |
| + case !c.exact && strings.Contains(f.Secret, c.secret): |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// 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 |
| +} |
| + |
| +// entry writes one census entry from its five fields. |
| +func entry(file, unit, class, kinds, digest string) string { |
| + return fmt.Sprintf(`{"%s", "%s", "%s", "%s", "%s"},`, file, unit, class, kinds, digest) |
| +} |
| + |
| +// censusBody puts lines into a census test file; the first is on line 4. |
| +func censusBody(lines ...string) string { |
| + return "package provision\n\nvar inventory = []censusEntry{\n\t" + strings.Join(lines, "\n\t") + "\n}\n" |
| +} |
| + |
| +// checklistBody puts one line into the checklist's shape, on line 3. |
| +func checklistBody(line string) string { |
| + return "{\n \"source_hashes\": {\n " + line + "\n }\n}\n" |
| +} |
| + |
| +// boundaryBody places line so that the first chunk ends cut bytes into it, |
| +// and returns the file with the line's number. |
| +func boundaryBody(line string, cut int) (string, int) { |
| + var b strings.Builder |
| + b.WriteString("package provision\n") |
| + n := 1 |
| + target := chunkBoundary - cut |
| + for ; target-b.Len() >= 128; n++ { |
| + b.WriteString("//" + strings.Repeat(" ", 61) + "\n") |
| + } |
| + b.WriteString("//" + strings.Repeat(" ", target-b.Len()-3) + "\n") |
| + n++ |
| + b.WriteString(line + "\n") |
| + for range 40 { |
| + b.WriteString("// the rest of the layer\n") |
| + } |
| + return b.String(), n + 1 |
| +} |
| + |
| +func selfCases(fragment string) []selfCase { |
| + const ( |
| + file = "internal/widgets/pump.go" |
| + auth = "internal/console/auth.go" |
| + unit = "Pump.Start" |
| + class = "nonrecord" |
| + kinds = "key:RecordKey" |
| + ) |
| + key, digest := newKey(40), newDigest() |
| + |
| + census := func(name, line, secret string) selfCase { |
| + return selfCase{name: name, file: plantedCensus, body: censusBody(line), lines: []int{4}, secret: secret} |
| + } |
| + checklist := func(name, line, secret string) selfCase { |
| + return selfCase{name: name, file: checklistFile, body: checklistBody(line), lines: []int{3}, secret: secret} |
| + } |
| + ordinary := func(name, line, secret string) selfCase { |
| + body := "package widgets\n\n" + line + "\n" |
| + return selfCase{name: name, file: ordinaryFile, body: body, lines: []int{3}, secret: secret} |
| + } |
| + boundary := func(name, path, line string, cut int, secret string, passes bool) selfCase { |
| + body, n := boundaryBody(line, cut) |
| + return selfCase{name: name, file: path, body: body, lines: []int{n}, secret: secret, exact: true, passes: passes} |
| + } |
| + |
| + prefix := "\t" + `{"` + file + `", "` + unit + `", "key-site", "` + kinds + `", "` |
| + otherFragment := newDigest()[:len(fragment)] |
| + longKey := newKey(80) |
| + const keyPrefix = `api_key = "` |
| + |
| + return []selfCase{ |
| + // Field 1: the file. |
| + census("census field 1 (file): key=value", entry("internal/widgets/api_key="+key+".go", unit, class, kinds, digest), key), |
| + census("census field 1 (file): key after a colon", entry("internal/widgets/token:"+key+".go", unit, class, kinds, digest), key), |
| + |
| + // Field 2: the unit. The last two are valid unit names, so only |
| + // tying the finding to the digest field reports them. |
| + census("census field 2 (unit): key=value", entry(file, "api_key="+key, class, kinds, digest), key), |
| + census("census field 2 (unit): password: value", entry(file, "password: "+key, class, kinds, digest), key), |
| + census("census field 2 (unit): bare key after a key-named file", entry(auth, key, class, kinds, digest), key), |
| + census("census field 2 (unit): Recv.key after a key-named file", entry(auth, "Zq."+key, class, kinds, digest), key), |
| + |
| + // Field 3: the class. |
| + census("census field 3 (class): key=value", entry(file, unit, "token="+key, kinds, digest), key), |
| + census("census field 3 (class): bare key after a key-named unit", entry(file, "rotateApiKey", key, kinds, digest), key), |
| + |
| + // Field 4: the kinds. |
| + census("census field 4 (kinds): key=value after a real kind", entry(file, unit, class, "key:RecordKey,api_key="+key, digest), key), |
| + census("census field 4 (kinds): bare key as a key name", entry(file, unit, class, "key:"+key, digest), key), |
| + census("census field 4 (kinds): secret=value", entry(file, unit, class, "secret="+key, digest), key), |
| + |
| + // Field 5: the digest. |
| + census("census field 5 (digest): a key in place of the digest", entry(file, unit, class, kinds, key), key), |
| + census("census field 5 (digest): uppercase hex", entry(file, unit, class, kinds, strings.ToUpper(digest)), strings.ToUpper(digest)), |
| + census("census field 5 (digest): 63 hex characters", entry(file, unit, class, kinds, digest[:63]), digest[:63]), |
| + census("census field 5 (digest): digest followed by key=value", entry(file, unit, class, kinds, digest+" api_key="+key), key), |
| + |
| + // Around an entry, and on other lines of a census file. |
| + census("census line: key=value after a whole entry", entry(file, unit, class, kinds, digest)+" // api_key="+key, key), |
| + census("census line: key=value before a whole entry", `var api_key = "`+key+`"; `+entry(file, unit, class, kinds, digest), key), |
| + census("census file: 64-hex value assigned to a key", `api_key = "`+digest+`"`, digest), |
| + census("census file: 64-hex value in a short entry", `{"auth", "`+digest+`"},`, digest), |
| + |
| + // Text no rule flags still voids the entry: the digest on that line |
| + // is reported, so every field has to hold what a census can write. |
| + census("malformed entry: other text in field 1", entry("internal/widgets/note="+key+".go", unit, class, kinds, digest), digest), |
| + census("malformed entry: other text in field 2", entry(file, "note="+key, class, kinds, digest), digest), |
| + census("malformed entry: other text in field 3", entry(file, unit, "note="+key, kinds, digest), digest), |
| + census("malformed entry: other text in field 4", entry(file, unit, class, "note="+key+","+kinds, digest), digest), |
| + census("malformed entry: other text after the entry", entry(file, unit, class, kinds, digest)+" // note="+key, digest), |
| + |
| + // The JSON checklist. |
| + checklist("checklist: a key in place of the digest", `"`+auth+`": "`+key+`",`, key), |
| + checklist("checklist: 64-hex value under a key name", `"api_key": "`+digest+`",`, digest), |
| + checklist("checklist: key=value in the file name", `"token=`+key+`.go": "`+digest+`",`, key), |
| + checklist("checklist: digest followed by key=value", `"`+auth+`": "`+digest+` api_key=`+key+`",`, key), |
| + { |
| + name: "checklist: a well-formed line in another file", file: "implementation/other.json", |
| + body: checklistBody(`"` + auth + `": "` + digest + `",`), lines: []int{3}, secret: digest, |
| + }, |
| + |
| + // A chunk boundary: gitleaks reports the cut-off start of a value. |
| + boundary("chunk boundary: another digest fragment in the known file", boundaryFile, |
| + prefix+otherFragment+"abcde\"},", len(prefix)+len(otherFragment), otherFragment, false), |
| + boundary("chunk boundary: the known fragment in another census file", plantedCensus, |
| + prefix+fragment+"abcde\"},", len(prefix)+len(fragment), fragment, false), |
| + boundary("chunk boundary: a key cut in half", boundaryFile, |
| + keyPrefix+longKey+`"`, len(keyPrefix)+40, longKey[:40], false), |
| + |
| + // Ordinary source files. |
| + ordinary("source file: a key", `const apiKey = "`+key+`"`, key), |
| + ordinary("source file: a 64-hex key", `const signingSecret = "`+digest+`"`, digest), |
| + ordinary("source file: a whole census entry", entry(auth, unit, class, kinds, 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", lines: []int{3}, secret: key, |
| + }, |
| + |
| + // What has to keep passing, with no change to any config. |
| + { |
| + name: "well-formed new census entries", file: "internal/provision/new_layer_census_test.go", |
| + body: censusBody( |
| + entry("internal/brandnew/store.go", "Store.WriteThing", "record-writer", "sel:Put,key:RecordKey", newDigest()), |
| + entry("internal/brandnew/store.go", "writeSomethingNew", "key-site", "def:PutFrom,key:RecordKey", newDigest()), |
| + entry("internal/brandnew/store.go", "var recordNames", "reference", "lit:instances,key:RecordKey", newDigest()), |
| + entry("internal/brandnew/store.go", "const#2", "nonrecord", "str:Put,key:RecordKey", newDigest()), |
| + "censusEntry"+strings.TrimSuffix(entry("internal/brandnew/store.go", "Store.Close#2", "testsupport", "id:CopyVersion,key:RecordKey", newDigest()), ",")+")", |
| + ), |
| + lines: []int{4, 5, 6, 7, 8}, passes: true, |
| + }, |
| + { |
| + name: "a well-formed new checklist line", file: checklistFile, |
| + body: checklistBody(`"` + auth + `": "` + digest + `",`), lines: []int{3}, secret: digest, passes: true, |
| + }, |
| + boundary("the known digest fragment at its boundary", boundaryFile, |
| + prefix+fragment+"abcde\"},", len(prefix)+len(fragment), fragment, true), |
| + } |
| +} |