fix(885): a detector that knows ONE spelling is one an added job writes around

`secrets['REGISTRY_PASSWORD']` is the same reference to the expression evaluator as
`secrets.REGISTRY_PASSWORD`, and the guard shipped here could see only the dot form. Measured
2026-09-05 against the predecessor of this commit, a `pull_request`-route job whose `env:` read
`"${{ secrets['REGISTRY_PASSWORD'] }}"` produced `stored_secret_faults(...) == []` AND
`walk_versus_text_faults(...) == []` — the text cross-check cannot report the gap, because both of
its halves resolve references through the one pattern, so a spelling it does not know is a shared
blind spot they agree at zero on rather than a disagreement they name
(`proof-sharing-with-subject-proves-nothing`).

The file enumerated four other blind spots it has — composite actions, reusable workflows, nested
directories, both directions of the comment strip — and not this one, which is what made the
omission read as coverage.

`secret_refs` is now the single entry point for both halves, and it matches the dot form, both index
forms and a case-varied context, then counts the RESIDUE: any `secrets` token inside a `${{ }}` span
that yielded no literal name is reported under the sentinel `secrets.*`. Counting the residue rather
than pattern-matching `toJSON(secrets)` and a computed index is what makes it exhaustive over the
grammar — a spelling nobody has written yet still faults, in the fail-closed direction. The bare word
is read as the context only inside an expression, because in prose it is ordinary English; this file
and four workflows discuss "secrets" in comments.

`test_the_collector_sees_every_SPELLING_of_a_secret_reference` drives the six spellings through the
collector and the cross-check and asserts each is invisible to the real predecessor, so reverting the
widening reddens it. Whether act_runner resolves each spelling against this instance was not probed
from here (that needs a live run); the direction makes that acceptable — a spelling the runner does
not support costs a spurious demand on a job nobody has written, the omission cost a live
write-capable credential on the head-authored route.

Decisions-Edit: yes
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015QqCpYFsKgnAnx6jVwrKiV
This commit is contained in:
2026-09-05 15:15:42 +02:00
co-authored by Claude Fable 5.1
parent 433e8f81c8
commit 383171dfa4
3 changed files with 141 additions and 11 deletions
@@ -342,7 +342,62 @@ INJECTED_SECRETS = frozenset({"GITEA_TOKEN"})
PULL_REQUEST = "pull_request"
_SECRET_REF = re.compile(r"secrets\.([A-Za-z_][A-Za-z0-9_]*)")
# The name a WHOLE-CONTEXT reference is reported under. It cannot collide with a real secret: a
# secret name is `[A-Za-z_][A-Za-z0-9_]*`, so no stored name can contain `.` or `*`.
WHOLE_SECRETS_CONTEXT = "secrets.*"
# Every spelling of a `secrets` reference the expression grammar admits — NOT just `secrets.NAME`.
# `secrets['NAME']` is the same reference to the evaluator (GitHub's expression syntax, which Gitea's
# runner implements, defines `[]` as the index operator alongside `.`), and context names are matched
# case-insensitively, so `Secrets.NAME` is one too. Recognising only the dot spelling made this a
# detector an added job could step around by writing a different one — and the cross-check below
# cannot report that, because BOTH of its halves read through this same function: a spelling neither
# half knows is a SHARED blind spot they agree at zero on, not a disagreement
# (`proof-sharing-with-subject-proves-nothing`, ersatztv#819). Measured 2026-09-05 against the
# predecessor of this commit, an `env:` of `"${{ secrets['REGISTRY_PASSWORD'] }}"` on a synthetic
# `pull_request` job produced `stored_secret_faults(...) == []` AND `walk_versus_text_faults(...) == []`.
#
# The name is taken VERBATIM, not case-folded onto the store's uppercase spelling. Whether the
# evaluator resolves `secrets.gitea_token` to the stored `GITEA_TOKEN` was not probed from here, and
# the un-folded reading is the demanding one: an unrecognised spelling misses the one-member
# `INJECTED_SECRETS` allow-list and is reported, rather than being forgiven on an unmeasured claim.
_SECRET_REF = re.compile(
r"(?<![A-Za-z0-9_])secrets\s*(?:"
r"\.\s*([A-Za-z_][A-Za-z0-9_]*)" # secrets.NAME
r"|\[\s*'([^']*)'\s*\]" # secrets['NAME']
r"|\[\s*\"([^\"]*)\"\s*\]" # secrets["NAME"]
r")",
re.I,
)
# The residue: a `secrets` token inside a `${{ }}` expression that `_SECRET_REF` did NOT resolve to a
# literal name. Two shapes reach it, and both hand over more than one secret rather than fewer —
# `toJSON(secrets)` or a bare `secrets` passed as an action input, and an index whose subscript is
# COMPUTED (`secrets[format('{0}_TOKEN', x)]`), which no static reader resolves. Counting the residue
# rather than pattern-matching those two shapes is what makes the widening exhaustive over the
# grammar: any spelling of the context that does not yield a literal name is reported, including one
# nobody has written yet.
#
# Both patterns are confined to `${{ }}` spans, because a bare `secrets` is otherwise ordinary
# English — this file and four workflows discuss "secrets" in prose, and matching that would fault
# every job carrying a comment. Inside an expression the word is the context and nothing else.
_EXPRESSION = re.compile(r"\$\{\{(.*?)\}\}", re.S)
_SECRETS_TOKEN = re.compile(r"(?<![A-Za-z0-9_])secrets(?![A-Za-z0-9_])", re.I)
def secret_refs(text: str) -> list[str]:
"""Every `secrets` reference in one string — occurrences, not names.
The single entry point for both the document walk and the text cross-check, so that widening one
spelling widens both. A list rather than a set for the reason `secret_name_counts` is a Counter:
only the lossless direction can be narrowed afterwards.
"""
found = [next(group for group in m.groups() if group is not None) for m in _SECRET_REF.finditer(text)]
for expression in _EXPRESSION.findall(text):
unresolved = len(_SECRETS_TOKEN.findall(expression)) - len(_SECRET_REF.findall(expression))
found.extend([WHOLE_SECRETS_CONTEXT] * unresolved)
return found
# The ONLY job-level `if:` in this repo that takes a job OFF the `pull_request` route. This is a PIN,
# not an expression parser, and the direction is the point: an `if:` that is not in this set leaves
@@ -405,7 +460,7 @@ def pull_request_jobs(doc: object) -> list[tuple[str, dict]]:
def secret_name_counts(node: object) -> Counter:
"""Every `secrets.NAME` reachable anywhere in a subtree — keys and values, at any depth — COUNTED.
"""Every secret reference reachable anywhere in a subtree — keys and values, at any depth — COUNTED.
Deliberately structure-blind: the credential entered through `container.credentials`, a step
`env:`, and a job `env:` in this repo already, and naming those three places would be the
@@ -427,7 +482,7 @@ def secret_name_counts(node: object) -> Counter:
elif isinstance(item, list):
stack.extend(item)
elif isinstance(item, str):
found.update(_SECRET_REF.findall(item))
found.update(secret_refs(item))
return found
@@ -501,9 +556,7 @@ def walk_versus_text_faults(name: str, text: str) -> list[str]:
(`testing.guard-ships-with-mutation-proof`).
"""
walked = secret_name_counts(yaml.safe_load(text))
scanned = Counter(
_SECRET_REF.findall("\n".join(line for line in text.splitlines() if not line.lstrip().startswith("#")))
)
scanned = Counter(secret_refs("\n".join(line for line in text.splitlines() if not line.lstrip().startswith("#"))))
if walked == scanned:
return []
return [
@@ -546,6 +599,15 @@ def test_the_DOCUMENT_walk_finds_every_secret_reference_the_TEXT_does() -> None:
A YAML anchor/alias would also redden benignly (the walk visits the aliased node once per
reference, the text carries `*alias`); measured 2026-09-05 no tracked workflow uses one.
WHAT THIS CROSS-CHECK STRUCTURALLY CANNOT REPORT, since it is the reason `secret_refs` has to be
widened rather than leaned on: both halves read through that one function, so a spelling IT does
not recognise is invisible to both and they agree at zero. The dot/index/whole-context spellings
are covered there; what remains uncovered is a name the expression COMPUTES
(`secrets[format('{0}_TOKEN', x)]`), which no static reader resolves. That spelling still faults,
but as `secrets.*` — the whole-context sentinel — because the index contains no literal, which is
the fail-closed direction and is asserted in
`test_the_collector_sees_every_SPELLING_of_a_secret_reference`.
"""
disagreements: list[str] = []
total = Counter()
@@ -558,7 +620,7 @@ def test_the_DOCUMENT_walk_finds_every_secret_reference_the_TEXT_does() -> None:
"no workflow reached by this check names a single `secrets.*` reference. Two empty Counters "
"compare equal, so the loop above would agree having measured nothing — either every "
"reference really is gone (say so here and in `ci.pr-route-carries-no-stored-credential`) "
"or `workflow_files()`/`_SECRET_REF` has stopped matching."
"or `workflow_files()`/`secret_refs` has stopped matching."
)
@@ -594,7 +656,7 @@ def test_the_cross_check_COUNTS_locations_rather_than_collecting_NAMES() -> None
assert "REGISTRY_PASSWORD" in faults[0]
# A name-set comparison — the mechanism this replaced — reports NOTHING on that same input.
assert secret_names(yaml.safe_load(duplicated)) == set(_SECRET_REF.findall(duplicated)) == {"REGISTRY_PASSWORD"}
assert secret_names(yaml.safe_load(duplicated)) == set(secret_refs(duplicated)) == {"REGISTRY_PASSWORD"}
# Two references in ONE scalar count twice, which is the shape a hoisted
# `user:${{ secrets.X }}:${{ secrets.Y }}` line takes.
@@ -678,6 +740,61 @@ def test_the_stored_secret_collector_reports_a_pull_request_job_naming_ONE() ->
assert stored_secret_faults("synthetic.yml", off_route) == [], trigger
def test_the_collector_sees_every_SPELLING_of_a_secret_reference() -> None:
"""The spellings that are the SAME reference to the evaluator and were invisible to the detector.
Driven against the real predecessor (`dot_only` below is `_SECRET_REF` exactly as this branch
shipped it before this commit), because that is the mutation this test exists to catch: revert
the widening and every case here goes back to `faults == []`. It cannot be caught by the
text-versus-walk cross-check — both halves read through `secret_refs`, so a spelling it does not
know is a shared blind spot they agree at zero on rather than a disagreement
(`proof-sharing-with-subject-proves-nothing`). Measured 2026-09-05, the predecessor reported
`stored_secret_faults(...) == []` and `walk_versus_text_faults(...) == []` on the index spelling.
Whether act_runner resolves each of these against this instance was NOT probed from here — that
needs a live run. The direction is what makes that acceptable: a spelling the runner happens not
to support costs a spurious demand on a job nobody has written; the omission cost a live
write-capable credential on the head-authored route.
"""
dot_only = re.compile(r"secrets\.([A-Za-z_][A-Za-z0-9_]*)")
for expression, reported in (
("${{ secrets['REGISTRY_PASSWORD'] }}", "REGISTRY_PASSWORD"),
('${{ secrets["REGISTRY_PASSWORD"] }}', "REGISTRY_PASSWORD"),
("${{ secrets [ 'REGISTRY_PASSWORD' ] }}", "REGISTRY_PASSWORD"),
("${{ Secrets.REGISTRY_PASSWORD }}", "REGISTRY_PASSWORD"),
# Names NO secret and hands over ALL of them; and an index the expression COMPUTES, which no
# static reader resolves. Both are reported under the whole-context sentinel.
("${{ toJSON(secrets) }}", WHOLE_SECRETS_CONTEXT),
("${{ secrets[format('{0}_PASSWORD', 'REGISTRY')] }}", WHOLE_SECRETS_CONTEXT),
):
assert dot_only.findall(expression) == [], (
f"{expression!r} is supposed to be a spelling the dot-only predecessor could not see — "
"if it can, this row proves nothing about the widening."
)
assert secret_refs(expression) == [reported], expression
doc = {True: {"pull_request": None}, "jobs": {"j": {"env": {"A": expression}}}}
faults = stored_secret_faults("synthetic.yml", doc)
assert len(faults) == 1, (expression, faults)
assert reported in faults[0], (expression, faults)
# The workflow scope is judged through the same function, so it widens with it.
scoped = {True: {"pull_request": None}, "env": {"A": "${{ secrets['REGISTRY_PASSWORD'] }}"}, "jobs": {}}
assert len(stored_secret_faults("synthetic.yml", scoped)) == 1
# The cross-check now COUNTS these spellings on both sides rather than agreeing at zero.
indexed = "jobs:\n j:\n env:\n A: \"${{ secrets['REGISTRY_PASSWORD'] }}\"\n"
assert secret_name_counts(yaml.safe_load(indexed)) == Counter({"REGISTRY_PASSWORD": 1})
assert walk_versus_text_faults("synthetic.yml", indexed) == []
# The over-match direction, which is the cost of matching a bare `secrets` at all: the word is
# only a context reference INSIDE an expression. Ordinary prose and a longer identifier are not.
assert secret_refs("echo 'no secrets are used here'") == []
assert secret_refs("${{ env.mysecrets.REGISTRY_PASSWORD }}") == []
prose = {True: {"pull_request": None}, "jobs": {"j": {"steps": [{"run": "echo 'no secrets here'"}]}}}
assert stored_secret_faults("synthetic.yml", prose) == []
def test_the_collector_reports_a_WORKFLOW_SCOPE_reference_no_job_if_can_reach() -> None:
"""The workflow scope is judged even when every job is gated OFF the route.