agent-bios 0.19.4 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/DEPENDENCIES.md +20 -5
  2. package/README.md +14 -19
  3. package/claude/agents/frontier.md +1 -1
  4. package/claude/guides/claude-prompting.md +475 -234
  5. package/claude/guides/cli-multi-model-workflow.md +8 -7
  6. package/claude/guides/gpt-prompting.md +319 -144
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/agents/frontier.toml +1 -1
  10. package/codex/agents/reviewer.toml +1 -1
  11. package/codex/agents/workhorse.toml +1 -1
  12. package/codex/guides/claude-prompting.md +475 -234
  13. package/codex/guides/cli-multi-model-workflow.md +8 -7
  14. package/codex/guides/gpt-prompting.md +319 -144
  15. package/codex/guides/session-distill-workflow.md +93 -43
  16. package/codex/guides/tooling-gotchas.md +3 -1
  17. package/compose/assemble.py +4 -1
  18. package/compose/canary.sh +8 -6
  19. package/compose/host_platform.py +158 -15
  20. package/compose/instructions-state.py +183 -41
  21. package/compose/instructions_install.py +222 -27
  22. package/compose/instructions_session.py +250 -75
  23. package/compose/instructions_setup_cli.py +2 -36
  24. package/compose/instructions_store.py +160 -3
  25. package/compose/instructions_transaction.py +29 -5
  26. package/docs/advanced-launch.md +5 -1
  27. package/docs/releases/0.20.0.md +102 -0
  28. package/docs/releases/0.20.1.md +76 -0
  29. package/install.sh +42 -14
  30. package/launch/agent-launch.py +152 -18
  31. package/launch/agent-launch.toml +28 -16
  32. package/launch/agent-launch.zsh +104 -13
  33. package/launch/claude_subcommands.py +179 -0
  34. package/launch/shell_integration.py +7 -1
  35. package/learn/collect-learning.py +60 -9
  36. package/learn/migrate-learnings.py +70 -4
  37. package/learn/redact.py +2 -1
  38. package/package.json +36 -3
  39. package/provenance.json +1 -1
  40. package/session-cost.py +80 -9
  41. package/session-distill/coverage.json +6 -0
  42. package/session-distill/distill.py +2575 -0
  43. package/session-distill/grammar/__init__.py +0 -0
  44. package/session-distill/grammar/owner_lines.py +874 -0
  45. package/session-distill/originators.json +9 -0
  46. package/session-distill/packets/cross_review.md +31 -0
  47. package/session-distill/packets/form.md +86 -0
  48. package/session-distill/packets/judge.md +81 -0
  49. package/session-distill/packets/placement_contract.md +90 -0
  50. package/session-distill/packets/propose.md +124 -0
  51. package/session-distill/packets/read.md +57 -0
  52. package/session-distill/packets/reconsider.md +53 -0
  53. package/session-distill/packets/s7b.md +65 -0
  54. package/session-distill/packets/s9b.md +39 -0
  55. package/session-distill/packets/stitch.md +35 -0
  56. package/session-distill/packets/sweep.md +33 -0
  57. package/session-distill/runlib/__init__.py +0 -0
  58. package/session-distill/runlib/bound.py +1102 -0
  59. package/session-distill/runlib/breaker.py +467 -0
  60. package/session-distill/runlib/census.py +2347 -0
  61. package/session-distill/runlib/claims.py +420 -0
  62. package/session-distill/runlib/controls.py +902 -0
  63. package/session-distill/runlib/coverage.py +881 -0
  64. package/session-distill/runlib/declare.py +888 -0
  65. package/session-distill/runlib/delivery_evidence.py +1145 -0
  66. package/session-distill/runlib/derive.py +812 -0
  67. package/session-distill/runlib/destinations.py +3072 -0
  68. package/session-distill/runlib/dispatch.py +7940 -0
  69. package/session-distill/runlib/drift.py +1077 -0
  70. package/session-distill/runlib/entry.py +401 -0
  71. package/session-distill/runlib/evidence.py +890 -0
  72. package/session-distill/runlib/exposure.py +1162 -0
  73. package/session-distill/runlib/gate.py +2727 -0
  74. package/session-distill/runlib/gitread.py +79 -0
  75. package/session-distill/runlib/inventory.py +19624 -0
  76. package/session-distill/runlib/journal.py +1919 -0
  77. package/session-distill/runlib/ledger.py +3210 -0
  78. package/session-distill/runlib/ledger_compat.py +101 -0
  79. package/session-distill/runlib/ledger_migration.py +190 -0
  80. package/session-distill/runlib/lifecycle_intake.py +693 -0
  81. package/session-distill/runlib/lineage.py +454 -0
  82. package/session-distill/runlib/measures.py +249 -0
  83. package/session-distill/runlib/monitor.py +1180 -0
  84. package/session-distill/runlib/operations.py +522 -0
  85. package/session-distill/runlib/packet.py +838 -0
  86. package/session-distill/runlib/placement.py +1769 -0
  87. package/session-distill/runlib/projection.py +4090 -0
  88. package/session-distill/runlib/ranking.py +740 -0
  89. package/session-distill/runlib/receipts.py +200 -0
  90. package/session-distill/runlib/records.py +1965 -0
  91. package/session-distill/runlib/search.py +249 -0
  92. package/session-distill/runlib/sequencing.py +829 -0
  93. package/session-distill/runlib/sources.py +641 -0
  94. package/session-distill/runlib/stage_adjudicate.py +845 -0
  95. package/session-distill/runlib/stage_apply.py +1378 -0
  96. package/session-distill/runlib/stage_approvals.py +758 -0
  97. package/session-distill/runlib/stage_close.py +1220 -0
  98. package/session-distill/runlib/stage_confirm.py +929 -0
  99. package/session-distill/runlib/stage_delivery.py +3080 -0
  100. package/session-distill/runlib/stage_form.py +2576 -0
  101. package/session-distill/runlib/stage_judge.py +4248 -0
  102. package/session-distill/runlib/stage_propose.py +3307 -0
  103. package/session-distill/runlib/stage_read.py +5179 -0
  104. package/session-distill/runlib/stage_render.py +2739 -0
  105. package/session-distill/runlib/stage_retrieve.py +924 -0
  106. package/session-distill/runlib/stage_review_korean.py +1002 -0
  107. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  108. package/session-distill/runlib/stagelock.py +412 -0
  109. package/session-distill/runlib/stop.py +1061 -0
  110. package/session-distill/runlib/targets.py +809 -0
  111. package/session-distill/runlib/usage.py +280 -0
  112. package/session-distill/runlib/validate.py +319 -0
  113. package/session-distill/runlib/views.py +4327 -0
  114. package/session-distill/schemas/adjudication.schema.json +35 -0
  115. package/session-distill/schemas/approval.schema.json +35 -0
  116. package/session-distill/schemas/census.schema.json +128 -0
  117. package/session-distill/schemas/checks.schema.json +207 -0
  118. package/session-distill/schemas/claim.schema.json +16 -0
  119. package/session-distill/schemas/confirmation.schema.json +24 -0
  120. package/session-distill/schemas/coverage.schema.json +66 -0
  121. package/session-distill/schemas/cross_review.schema.json +24 -0
  122. package/session-distill/schemas/event.schema.json +20 -0
  123. package/session-distill/schemas/evidence.schema.json +20 -0
  124. package/session-distill/schemas/expected_observation.schema.json +18 -0
  125. package/session-distill/schemas/form.schema.json +103 -0
  126. package/session-distill/schemas/intake.schema.json +71 -0
  127. package/session-distill/schemas/inventory.schema.json +872 -0
  128. package/session-distill/schemas/judge.schema.json +77 -0
  129. package/session-distill/schemas/ledger.schema.json +313 -0
  130. package/session-distill/schemas/observation.schema.json +16 -0
  131. package/session-distill/schemas/propose.schema.json +555 -0
  132. package/session-distill/schemas/read.schema.json +76 -0
  133. package/session-distill/schemas/reconsider.schema.json +122 -0
  134. package/session-distill/schemas/run.schema.json +150 -0
  135. package/session-distill/schemas/s7b.schema.json +200 -0
  136. package/session-distill/schemas/s9b.schema.json +28 -0
  137. package/session-distill/schemas/stitch.schema.json +25 -0
  138. package/session-distill/schemas/sweep.schema.json +25 -0
  139. package/session-distill/seats.json +149 -0
  140. package/session-distill/tables/allowed_pairs.json +257 -0
  141. package/session-distill/tables/controls.json +30 -0
  142. package/session-distill/tables/delivery_evidence.json +36 -0
  143. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  144. package/session-distill/tables/destinations.json +684 -0
  145. package/session-distill/tables/drift_layers.json +68 -0
  146. package/session-distill/tables/exposure_rules.json +192 -0
  147. package/session-distill/tables/placement_rules.json +148 -0
  148. package/session-distill/tables/propose_fixtures.json +154 -0
  149. package/session-distill/tables/ranking.json +194 -0
  150. package/session-distill/tables/redundancy.json +10 -0
  151. package/session-distill/tables/structural_rules.json +44 -0
  152. package/session-distill/tables/transition_fixtures.json +398 -0
  153. package/session-distill/tables/transitions.json +69 -0
  154. package/session-distill/tables/unit_outcome.json +67 -0
  155. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  156. package/wrappers/claude-run.sh +481 -33
  157. package/wrappers/claude_hermetic_evidence.py +1423 -0
  158. package/wrappers/codex-helm.sh +46 -15
  159. package/wrappers/codex-run.sh +183 -20
  160. package/wrappers/codex_frame_filter.py +1199 -0
  161. package/wrappers/codex_protocol.py +737 -0
  162. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,4090 @@
1
+ #!/usr/bin/env python3
2
+ """The versioned redaction projection: the one text a window, a search hit or a quote is built from (design §5.4, §5.5).
3
+
4
+ `project(value, version)` takes a **content block** - a string, or any JSON value, since a tool call's
5
+ arguments are an object - and gives the characters the block projects to. A locator (`line`,
6
+ `json_pointer`, `char_span`) names those characters, so every reader resolves a quote the same way.
7
+
8
+ **A key is recognised in the structure, never in the serialisation.** The floor's own patterns read
9
+ `key=value` and `key: value`; a serialised object puts a closing quote between the key and the colon, so
10
+ `{"password": "x"}` handed to the floor as text keeps its secret, and `json.dumps` doubles a path's
11
+ backslashes past the Windows pattern. The rules below follow from that, and their order is the order they
12
+ run in:
13
+
14
+ 1. **The structure is walked before anything is serialised** (`walk`). Every string and every key is
15
+ projected, and the value of any key the floor treats as the name of a secret is replaced whole.
16
+ `secret_key` asks the floor - does it redact `<key>=<a value>` - rather than copying its key list, so
17
+ a name the floor learns about later is covered here with no edit and no second authority.
18
+ 2. **A string that is itself a serialised structure is parsed and walked** (`embedded`), at up to
19
+ `MAX_EMBEDDED` removes, because a tool result prints a JSON body whose own members then arrive as text
20
+ with escaped quotes. The walked form replaces the text only when a secret was actually masked, so a
21
+ JSON document a person reads keeps its own formatting unless it held a credential.
22
+ 3. **The floor runs over every string** (`learn/redact.py::redact`, the repository's single secret floor,
23
+ loaded by path and never changed here), followed by the keyed values the floor cannot see, anchored on
24
+ the floor's own **name** (`_KEYED`): nothing before the name is required, so a fragment that begins
25
+ mid-string is read like any other text, and the name must be followed by an optional closing quote and
26
+ then the separator, which IS the floor's rule - `openai_api_key=` is a secret and `input_tokens=` is
27
+ not. The value's extent is then **scanned, never described**: a string in any of its three spellings
28
+ however long and whatever it holds, or a bare token; or, when the value opens a
29
+ structure, found by decoding it from that point (exact, and it reaches a fragment
30
+ of a document where parsing the whole string cannot; a structure that never closes is one a view
31
+ clipped, so the rest of the text goes, while one that closes without decoding is another notation and
32
+ stays).
33
+ 4. **Text that is one level of JSON string escaping** is projected through its own unescaped form and
34
+ escaped back (`unescaped`). That encoding is a bijection, so this is exact, and it is the only way the
35
+ rules above reach a member whose value opens a structure in escaped text, where decoding cannot run and
36
+ counting brackets cannot tell a string's delimiter from an escaped quote. Like rule 2 it replaces the
37
+ text only when a secret was masked, so prose keeps its own escaping byte for byte.
38
+ 5. **Local paths are masked.** An absolute path that begins at a person's home (`/Users/<name>`,
39
+ `/home/<name>`, `C:\\Users\\<name>`) becomes `<HOME>` plus the rest, so a view shows where a file was
40
+ without saying whose account it was; this process's own home is masked wherever it stands.
41
+ `/Users/Shared` is a shared directory, not a home, and stays.
42
+
43
+ Everything past rule 1 exists because the live run of 2026-10-21 was swept for members whose key the floor
44
+ itself calls a secret and whose value was not masked. Each sweep found the next shape: 11,045 when the name
45
+ was read as a key's prefix, 3,117 at one or two removes of serialisation, 277 whose value opened a
46
+ structure, 27 whose structure the view's own clipping had cut off. A pattern per spelling is what that
47
+ progression is; the structure is where the question has one answer, and each rule here either walks a
48
+ structure or recovers one.
49
+
50
+ Then the sweep itself moved (`sweep`, `--sweep <run-dir>`). It had been a byte scan over the files, and so
51
+ it judged a different text from the one the projection judges: where it reported 24 members, the decoded
52
+ strings - the text a model actually receives - held 63. Thirteen of those were **scalars**, which no story
53
+ about a structure's extent explains: the pattern had required the key's own opening quote, capped the key's
54
+ prefix at 64 characters and the value's at 4,096, and allowed no quote or backslash inside a value. Each of
55
+ those four assumptions hid members of a kind the floor would have masked in prose. Rule 3 anchors on the
56
+ name and scans for the end because of them, and the sweep now reads what the projection wrote rather than
57
+ the bytes that hold it, so the two cannot drift apart again.
58
+
59
+ What remains for the design to decide, not this module: a secret-named key whose value opens a structure
60
+ inside escaped text that is not a complete JSON string body - a fragment beginning mid-string, where one
61
+ level of unescaping has no exact inverse and no rule here can read the structure's extent. Masking to the
62
+ end of such a fragment would swallow what followed it, which rule 3's own look-alike control forbids.
63
+
64
+ The projection is a pure function of the value and the version: the same block projects to the same
65
+ characters on every run, which is what lets a quote be checked against it later (`evidence.verify`).
66
+
67
+ Every projection carries its `redaction_version`. A change to either half is a new version: `r2`
68
+ supersedes `r1`, which was the text-only projection of commit 5ea5c3a. A superseded version is **not**
69
+ left registered - a projection known to under-redact that anything can still call is a hazard, and
70
+ design §5.5 needs only that an old quote fail by name (`REDACTION_VERSION_MISMATCH`) and be made again
71
+ from the source, which an unregistered version does.
72
+
73
+ projection.py --self-test
74
+ projection.py --sweep <run-dir>
75
+ """
76
+ import importlib.util
77
+ import collections
78
+ import hashlib
79
+ import threading
80
+ import types
81
+ import unicodedata
82
+ import random
83
+ import contextlib
84
+ import io
85
+ import json
86
+ import os
87
+ import pathlib
88
+ import re
89
+ import sys
90
+ import tempfile
91
+
92
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
93
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
94
+ from runlib import records
95
+
96
+ REPO = pathlib.Path(__file__).resolve().parents[2]
97
+ # The version is the masking's identity, so it advances whenever the masking changes - not when the module
98
+ # does. `r22` is ONE monotone pass in the original text's own coordinates, VERIFIED on the way out: every source of masking - the
99
+ # floor, a secret-named key's whole value, the owner's home paths, and whatever only decoding reveals,
100
+ # mapped back at literal or structure granularity - answers in the same coordinates, and the union of their
101
+ # extents is masked once. There is no decoded candidate and no fallback, because the gap between those two
102
+ # paths is what leaked in four consecutive rounds, each new rule closing one side and opening the other
103
+ # (`design/session-distill/2026-10-21T1740--5efadbf--projection-single-pass.md`). Behind the pass stands an
104
+ # independent verifier, which does no mapping at all and blanks a block whose output still discloses
105
+ # anything or which it could not fully read
106
+ # (`design/session-distill/2026-10-21T1937--b8c83d2--projection-verified-invariants.md`).
107
+ # A window built under one
108
+ # version cannot be read under another, and no superseded version is registered: a projection known to mask
109
+ # less that anything can still call is a hazard, and §5.5 asks only that an old artifact fail by name and be
110
+ # made again from the source.
111
+ CURRENT = "r22"
112
+ HOME_MASK = "<HOME>"
113
+ MAX_DEPTH = 64 # deeper than any real tool argument; past it the value is projected as its text
114
+ MAX_EMBEDDED = 8 # how many times a string may itself be a serialised structure before the text stands as it is
115
+
116
+
117
+ class FloorUnreadable(Exception):
118
+ """The floor is not the shape this projection reads its secret key names out of."""
119
+
120
+
121
+ def _load_floor():
122
+ """`learn/redact.py`, loaded by path: it is the owner of the secret patterns, shipped, and imported here (never copied)."""
123
+ spec = importlib.util.spec_from_file_location("agent_bios_secret_floor", REPO / "learn" / "redact.py")
124
+ module = importlib.util.module_from_spec(spec)
125
+ spec.loader.exec_module(module)
126
+ return module
127
+
128
+
129
+ FLOOR_PATH = REPO / "learn" / "redact.py"
130
+ FLOOR = _load_floor()
131
+ # the segment after the home marker runs to the first character that cannot be part of a user name
132
+ _SEGMENT = r"""[^/\\\s"'`<>()\[\]{},;:|*?]+"""
133
+ # What may stand before another person's home for it to be a path of its own, rather than the tail of a
134
+ # relative one (`src/Users/alice.py` is not a home path). A transcript carries tool arguments as JSON, so a
135
+ # line break often reaches the text as the two characters `\` and `n`, and that is a boundary, not a segment:
136
+ # before this was allowed for, a live run left 8,536 owner paths in the projection with `n` in front of them.
137
+ _BOUNDARY = r"(?:(?<=\\n)|(?<=\\t)|(?<=\\r)|(?<![\w.~-]))"
138
+ _PATTERNS = (
139
+ re.compile(rf"{_BOUNDARY}/(?:Users|home)/(?!Shared(?![\w.-]))({_SEGMENT})"),
140
+ # one or more backslashes per separator: `json.dumps` doubles them, and a Windows home path that
141
+ # reached the floor through a serialised tool argument used to pass with `C:\\Users\\carol`
142
+ # ... and case-insensitively: `c:\users\Carol` is the same directory as `C:\Users\carol` on the system
143
+ # it came from, so a projection that reads one spelling and not the other masks by luck.
144
+ re.compile(rf"{_BOUNDARY}[A-Za-z]:\\+Users\\+({_SEGMENT})", re.IGNORECASE),
145
+ )
146
+ _WINDOWS_HOME = re.compile(r"^[A-Za-z]:[\\/]") # which spelling a declared home is, so its own pattern matches alike
147
+ _PROBE = "Zq7probevalue0123456789" # matched by no pattern of the floor on its own; the self-test proves that
148
+
149
+
150
+ def floor_key_alternation():
151
+ """The alternation of secret key names, read out of the floor's own first pattern so this module keeps no
152
+ second list of them. A floor whose first pattern no longer leads with that group is a named failure, never
153
+ a silently empty list - an empty alternation would match every key or none."""
154
+ first = FLOOR.SECRET_RE[0].pattern
155
+ match = re.match(r"\(\?i\)\(([^()]+)\)\\s\*\[:=\]", first)
156
+ if not match or not match.group(1).strip():
157
+ raise FloorUnreadable(f"REDACTION_FLOOR_UNREADABLE learn/redact.py SECRET_RE[0]: its leading key-name group is "
158
+ f"not where this projection reads it from ({first[:60]!r}); re-derive the JSON-keyed pattern")
159
+ return match.group(1)
160
+
161
+
162
+ # The JSON-keyed form of a secret, which the floor's `key=value` and `key: value` patterns cannot see because a
163
+ # serialised object puts a closing quote between the key and the colon. The value - a JSON string, number,
164
+ # boolean or null - is replaced; the key is kept, so a reader still sees that a credential stood there.
165
+ #
166
+ # The key may carry any prefix, and the name must END it, because that is exactly the floor's own rule: its
167
+ # pattern needs the separator straight after the name, so `openai_api_key=` is a secret and `input_tokens=` is
168
+ # not. Reading the name as a prefix instead left 11,045 members unmasked in the live run of 2026-10-21 -
169
+ # `user_authorization`, `x-api-key`, `page_token`, `google_client_secret` - every one of them a key the floor
170
+ # itself calls a secret. `secret_key` asks the floor the same question for the structural half, so the two
171
+ # halves answer alike.
172
+ _Q = r'\\?"' # a quote, or one a serialisation escaped: a fragment of a document carries both spellings
173
+ # The anchor is the NAME, not a whole key, and nothing before it is required. A pattern that demanded the
174
+ # key's opening quote could not see a member in a fragment that begins mid-string (`password": "..."`), and
175
+ # one that capped the key's prefix or the value's length could not see a long key or a long value at all:
176
+ # thirteen members of the live run of 2026-10-21 were scalars of exactly those shapes, unmasked.
177
+ #
178
+ # The name must be followed by an optional closing quote and then the separator, which IS the floor's own
179
+ # rule - its separator comes straight after the name - so `openai_api_key=` is a secret and `input_tokens=`
180
+ # is not, with no prefix to measure.
181
+ _KEYED = re.compile(rf'(?i)(?:{floor_key_alternation()})(?:\\?["\'])?[ \t]*[:=][ \t]*')
182
+ # The value's extent is scanned rather than described: a string in any of its three spellings, however long
183
+ # and whatever it contains, or a bare token. A structure is not scanned - `keyed_spans` decodes it, because
184
+ # its extent is a decoding question, not a delimiter one.
185
+ _VALUE = re.compile(r'\\"(?:(?!\\").)*\\"' # a string whose quotes a serialisation escaped
186
+ r'|"(?:[^"\\]|\\.)*"' # a plain JSON string
187
+ r"|'(?:[^'\\]|\\.)*'" # a repr's string
188
+ # an unquoted value, which may be several words: a header's credential is `Bearer <token>`
189
+ # and the floor masks both words, so a scan that stopped at the first space would hand the
190
+ # floor a text it no longer recognises and the token would stand. It stops at a separator
191
+ # or the end of the line, never crossing into the next member.
192
+ r'|[^\s,}\]]+(?:[ \t]+[^\s,}\]]+)*',
193
+ re.DOTALL)
194
+ _COMMENT = re.compile(r'(?:\s|/\*.*?\*/)*', re.DOTALL)
195
+
196
+
197
+ def secret_key(name):
198
+ """Whether the floor treats `name` as the name of a secret: it does, exactly when the floor **changes**
199
+ `name=<a value>`. Asked of the floor rather than copied from it, so a key name the floor learns about
200
+ later is covered here with no edit and no second authority.
201
+
202
+ The question is whether the floor changed the string, not whether the placeholder is in the answer: a
203
+ key whose own name already carries the placeholder - an address the floor masked a moment earlier -
204
+ contains it before the floor is asked, and asking the wrong question called every one of those a
205
+ secret (175 of the 205 the live sweep of 2026-10-21 still reported)."""
206
+ if not isinstance(name, str) or not name.strip():
207
+ return False
208
+ probe = f"{name}={_PROBE}"
209
+ return FLOOR.redact(probe) != probe
210
+
211
+
212
+ def home_patterns(home=None):
213
+ """The masking patterns: the two general forms, each needing a boundary before it, and this process's own
214
+ home, which is masked wherever it stands. The owner's path is the one a view must never carry, and prose,
215
+ an escape sequence or a relative prefix may abut it with no separator at all; a longer directory name that
216
+ merely begins with the home is still not the home (the trailing lookahead)."""
217
+ home = os.path.expanduser("~") if home is None else home
218
+ patterns = list(_PATTERNS)
219
+ if home not in ("", "/", "~"):
220
+ # a Windows home is matched case-insensitively, a POSIX one exactly: each follows its own filesystem
221
+ flags = re.IGNORECASE if _WINDOWS_HOME.match(home) else 0
222
+ patterns.append(re.compile(rf"{re.escape(home.rstrip('/'))}(?![\w.-])", flags))
223
+ return patterns
224
+
225
+
226
+ def unterminated(text, start):
227
+ """Whether the structure opening at `start` never closes in `text`, counting brackets outside strings. The
228
+ question is only yes or no, which is why counting is enough here: an extent would have to survive every
229
+ escaping, a decision does not."""
230
+ depth, in_string, i = 0, False, start
231
+ while i < len(text):
232
+ ch = text[i]
233
+ if in_string:
234
+ if ch == "\\":
235
+ i += 2
236
+ continue
237
+ if ch == '"':
238
+ in_string = False
239
+ elif ch == '"':
240
+ in_string = True
241
+ elif ch in "{[":
242
+ depth += 1
243
+ elif ch in "}]":
244
+ depth -= 1
245
+ if depth == 0:
246
+ return False
247
+ i += 1
248
+ return True
249
+
250
+
251
+ # ---- the spans every rule would mask, and the one masking over their union ------------------------
252
+ #
253
+ # The rules do not run in sequence any more, and that is the point. Composing maskers by substitution
254
+ # trades one bypass for another: the floor's replacement is destructive, so reading a key after it loses
255
+ # the key (`Authorization: "Bearer <v>"` -> `<REDACTED> <v>"`), and reading the key first hands the floor a
256
+ # text whose own match it no longer recognises (`Authorization: Bearer\nopaque...` -> the scheme masked and
257
+ # the credential left, because the floor's scheme pattern crosses the newline and a scan for a bare value
258
+ # does not). r2 fixed the first and opened the second.
259
+ #
260
+ # So every rule now answers the same question about the SAME input text - which spans would you mask? - and
261
+ # the union is masked once. A span any rule claims is masked to its full extent, so no rule can shrink
262
+ # another's, and a rule reading the original text cannot be shown a text another rule has rewritten.
263
+ SECRET_SPAN, HOME_SPAN = 1, 0 # on an overlap the stronger replacement wins: a secret hides a path's tail
264
+
265
+
266
+ def floor_patterns():
267
+ """The floor's own compiled patterns, read from `learn/redact.py` and never copied.
268
+
269
+ `redact` substitutes, which tells us what it masked but not where. The patterns tell us where, and they
270
+ are the floor's property: a pattern it gains covers the projection with no edit here. A floor that does
271
+ not expose them usably fails by name rather than silently masking less."""
272
+ patterns = getattr(FLOOR, "SECRET_RE", None)
273
+ if not isinstance(patterns, (list, tuple)) or not patterns:
274
+ raise FloorUnreadable(f"REDACTION_FLOOR_UNREADABLE {FLOOR_PATH}: SECRET_RE is not a non-empty list of "
275
+ "compiled patterns, so the spans the floor would mask cannot be read")
276
+ for pattern in patterns:
277
+ if not hasattr(pattern, "finditer") or not hasattr(pattern, "pattern"):
278
+ raise FloorUnreadable(f"REDACTION_FLOOR_UNREADABLE {FLOOR_PATH}: {pattern!r} is not a compiled "
279
+ "pattern, so the spans the floor would mask cannot be read")
280
+ return patterns
281
+
282
+
283
+ def floor_spans(text):
284
+ """Every span the floor's patterns match, each masked whole as `redact` masks it.
285
+
286
+ The floor applies its patterns in sequence, so a later pattern sees an earlier one's output; these spans
287
+ are all read from the original text, which can only cover more, never less."""
288
+ return [(match.start(), match.end(), FLOOR.PLACEHOLDER, SECRET_SPAN)
289
+ for pattern in floor_patterns() for match in pattern.finditer(text)]
290
+
291
+
292
+ def keyed_spans(text):
293
+ """Every span a secret-named key's value occupies: a scalar by scan, a structure by decoding.
294
+
295
+ The value's own quotes stay outside the span, so the quoting comes back exactly as it was without
296
+ re-emitting it - and a structure, which has no quotes of its own, carries them in its replacement."""
297
+ spans, decoder = [], json.JSONDecoder()
298
+ for match in _KEYED.finditer(text):
299
+ at = _COMMENT.match(text, match.end()).end()
300
+ if at < len(text) and text[at] in "{[":
301
+ try:
302
+ _value, end = decoder.raw_decode(text, at)
303
+ except ValueError:
304
+ if not unterminated(text, at):
305
+ continue # it closes without decoding: a repr or another notation, left to the other rules
306
+ end = len(text) # a structure a view clipped: its extent is absent, so the rest of the text goes
307
+ # A structure holding nothing but this module's own masks needs no masking: masking it again
308
+ # replaces the structure with one placeholder, so a second projection of the same text would
309
+ # differ from the first and the projection would not be idempotent. The test is over the
310
+ # CHARACTERS, not over a decode, because the same structure can arrive escaped - where no decode
311
+ # succeeds and the old check silently did not apply.
312
+ if not mask_free(text[at:end]).replace("\x00", "").strip(" \t\r\n\"'[]{},:\\"):
313
+ continue
314
+ spans.append((at, end, f'"{FLOOR.PLACEHOLDER}"', SECRET_SPAN))
315
+ continue
316
+ found = _VALUE.match(text, at)
317
+ if found is None:
318
+ continue
319
+ value, inner = found.group(0), None
320
+ for quote in ('\\"', '"', "'"):
321
+ if value.startswith(quote) and value.endswith(quote) and len(value) >= 2 * len(quote):
322
+ inner = (found.start() + len(quote), found.end() - len(quote))
323
+ break
324
+ if inner is None:
325
+ # An unquoted value stops at a separator, and a value standing at the end of a literal has the
326
+ # closing quote next: the scan took it, and masking it broke the syntax and made a second
327
+ # projection read the orphaned opening quote as a bare value of its own.
328
+ begin, finish = found.start(), found.end()
329
+ while finish > begin and text[finish - 1] in '"\'}],':
330
+ finish -= 1
331
+ # A number, a boolean or a null carries no quotes of its own, so replacing it with a bare mask
332
+ # left a document that no longer parsed. The replacement supplies the quotes the value never had.
333
+ bare, readable = None, True
334
+ try:
335
+ bare = json.loads(text[begin:finish])
336
+ except (ValueError, RecursionError):
337
+ readable = False
338
+ # a sentinel rather than `is not None`: `null` parses TO None, and reading that as "did not
339
+ # parse" left the bare mask standing where a document needed a quoted one
340
+ if readable and not isinstance(bare, str):
341
+ spans.append((begin, finish, f'"{FLOOR.PLACEHOLDER}"', SECRET_SPAN))
342
+ continue
343
+ inner = (begin, finish)
344
+ spans.append((*inner, FLOOR.PLACEHOLDER, SECRET_SPAN))
345
+ return spans
346
+
347
+
348
+ def literal_ranges(text):
349
+ """The inner range of every string literal in `text`, in both spellings: a plain `"..."` and a
350
+ serialisation's `\"...\"`. The ranges are what a replacement may touch without taking a delimiter
351
+ with it."""
352
+ ranges, decoder, index = [], json.JSONDecoder(), 0
353
+ while index < len(text):
354
+ if text[index] == '"':
355
+ try:
356
+ value, end = decoder.raw_decode(text, index)
357
+ except ValueError:
358
+ index += 1
359
+ continue
360
+ if isinstance(value, str):
361
+ ranges.append((index + 1, end - 1))
362
+ index = end
363
+ continue
364
+ index += 1
365
+ continue
366
+ if text.startswith('\\"', index):
367
+ close = text.find('\\"', index + 2)
368
+ if close == -1:
369
+ break
370
+ ranges.append((index + 2, close))
371
+ index = close + 2
372
+ continue
373
+ index += 1
374
+ return ranges
375
+
376
+
377
+ def within_literals(text, start, end):
378
+ """One floor extent, normalised to the boundaries of whatever holds it, as `(start, end, replacement)`.
379
+
380
+ The floor's patterns are greedy over characters, not over syntax: `token=def"}` is one match, and
381
+ replacing it took the closing quote and brace with it. The document then no longer parsed, and a second
382
+ projection read the orphaned opening quote as a bare value and masked differently - so the projection was
383
+ not idempotent either.
384
+
385
+ One literal holding the extent gives that literal's INNER range, so its quotes survive at whatever
386
+ escaping level they were written. An extent reaching across two or more literals is a claim no single
387
+ value holds, and the unit is then the smallest structure that encloses it - masked whole, quotes and
388
+ all - because the delimiters in between are the ones that would otherwise be eaten. Failing both, the
389
+ extent is the floor's own and stands as it is."""
390
+ touched = [(inner_start, inner_end) for inner_start, inner_end in literal_ranges(text)
391
+ if inner_start < end and inner_end > start]
392
+ if len(touched) == 1:
393
+ return [(touched[0][0], touched[0][1], FLOOR.PLACEHOLDER)]
394
+ if len(touched) > 1:
395
+ enclosing = [(begin, finish) for begin, finish, _value in structures_in(text)
396
+ if begin <= touched[0][0] and finish >= touched[-1][1]]
397
+ if enclosing:
398
+ begin, finish = min(enclosing, key=lambda pair: pair[1] - pair[0])
399
+ return [(begin, finish, f'"{FLOOR.PLACEHOLDER}"')]
400
+ return [(touched[0][0], touched[-1][1], FLOOR.PLACEHOLDER)]
401
+ return [(start, end, FLOOR.PLACEHOLDER)]
402
+
403
+
404
+ def floor_spans_normalised(text):
405
+ """`floor_spans`, with every extent normalised to the delimiters that enclose it."""
406
+ return [(a, b, replacement, rank)
407
+ for start, end, _replacement, rank in floor_spans(text)
408
+ for a, b, replacement in within_literals(text, start, end)]
409
+
410
+
411
+ def visible_secret_keys(text):
412
+ """The secret-named keys the RAW rules can see here - the ones whose value `keyed_spans` locates by its
413
+ own extent. A key the raw rules cannot see has no locatable value, whatever else the text happens to
414
+ contain."""
415
+ names = set()
416
+ for match in _KEYED.finditer(text):
417
+ name = re.sub(r'[\s:="\'\\]+$', "", match.group(0)).strip().strip('"\'').lower()
418
+ if name:
419
+ names.add(name.lstrip('\\"\''))
420
+ return names
421
+
422
+
423
+ def path_spans(text, home=None):
424
+ """Every span a local home path occupies - the home itself, never the rest of the path, so a view still
425
+ shows where a file was without saying whose account it was."""
426
+ return [(match.start(), match.end(), HOME_MASK, HOME_SPAN)
427
+ for pattern in home_patterns(home) for match in pattern.finditer(text)]
428
+
429
+
430
+ PARTIAL_SURVIVAL = 8 # characters of a credential that may not stand together in the output
431
+
432
+
433
+ def secret_part(match):
434
+ """The credential inside one floor match - not the key that named it.
435
+
436
+ The floor's header pattern matches `Authorization: Bearer <v>` whole, so asking whether the MATCH
437
+ survives asks about the word `Authorization` too, and the keyed rule keeps that word on purpose. What may
438
+ not survive is the credential: the match's tail after the key and its separator, and after any scheme
439
+ word, which is the last whitespace-separated run of that tail. For every other pattern the match IS the
440
+ credential. Nothing here enumerates the floor's scheme words - the shape "optional words, then the
441
+ credential" is what is read."""
442
+ whole = match.group(0)
443
+ if match.re.groups and match.group(1) is not None:
444
+ tail = whole[match.end(1) - match.start(0):].lstrip(" \t\r\n:=")
445
+ parts = tail.split()
446
+ return parts[-1] if parts else ""
447
+ return whole
448
+
449
+
450
+ def mask_free(text):
451
+ """`text` with this module's own mask tokens replaced by a character no transcript holds.
452
+
453
+ A credential and the output can SHARE the mask: an input that already carried `<REDACTED>` next to a
454
+ secret puts those characters inside the obligation, and the projection's own masking puts them in the
455
+ output, so a comparison of runs reports a survival that is the mask agreeing with itself. The separator
456
+ keeps the fragments apart, so removing a mask cannot join two pieces into a run that was never there."""
457
+ return text.replace(FLOOR.PLACEHOLDER, "\x00").replace(HOME_MASK, "\x00")
458
+
459
+
460
+ def survives(secret, out):
461
+ """Whether `secret` survives in `out` - WHOLLY OR IN PART.
462
+
463
+ Asking only whether the whole string is still there passes the very shape this module was fixed for: an
464
+ output that drops `Authorization: Bearer` and keeps the credential after it no longer contains the whole
465
+ match, and the credential is what mattered. Any run of PARTIAL_SURVIVAL characters of a credential is
466
+ enough to be one, so that is the unit; a credential shorter than that is asked about whole - but only
467
+ when it is the whole credential, never when it is a fragment left by removing a mask."""
468
+ if not secret:
469
+ return False
470
+ swept = mask_free(out)
471
+ pieces = [piece for piece in mask_free(secret).split("\x00") if piece]
472
+ if not pieces:
473
+ return False # the value was nothing but this module's own mask
474
+ entire = len(pieces) == 1 and pieces[0] == secret
475
+ for piece in pieces:
476
+ if entire and len(piece) <= PARTIAL_SURVIVAL:
477
+ return piece in swept
478
+ if len(piece) >= PARTIAL_SURVIVAL and any(piece[i:i + PARTIAL_SURVIVAL] in swept
479
+ for i in range(len(piece) - PARTIAL_SURVIVAL + 1)):
480
+ return True
481
+ return False
482
+
483
+
484
+ def floor_survivors(raw, out):
485
+ """Every credential the unchanged floor claims in `raw` that still stands in `out`, wholly or in part.
486
+
487
+ This is the oracle the projection is judged by, and the one it consults before trusting its own decoded
488
+ result. It is independent of how the masking is done: it reads the floor's own patterns over the RAW
489
+ text and asks a question about the OUTPUT."""
490
+ return [secret for pattern in floor_patterns() for match in pattern.finditer(raw)
491
+ for secret in [secret_part(match)] if survives(secret, out)]
492
+
493
+
494
+ def relaxed_decode(text):
495
+ r"""`text` read as the body of a JSON string, or None: what a `\u` escape, an escaped slash and an
496
+ escaped backslash spell when decoded.
497
+
498
+ `escaped_form` asks for an escaped QUOTE before it tries, because its job is to re-emit the text in the
499
+ same escaping. This one asks nothing: a value can be spelled in escapes without ever quoting anything,
500
+ and that spelling is the one a reader of the decoded layer sees."""
501
+ if not text or "\\" not in text:
502
+ return None
503
+ try:
504
+ decoded = json.loads(f'"{text}"')
505
+ except ValueError:
506
+ return None
507
+ return decoded if isinstance(decoded, str) and decoded != text else None
508
+
509
+
510
+ def spellings(value):
511
+ """Every form `value` can take through the decodings this projection applies: itself, the serialisation
512
+ and the string leaves of any structure it holds, one level of JSON string escaping, and the plain text
513
+ its escapes spell - repeated to the depth the projection decodes.
514
+
515
+ This closes a class rather than a case. A check written in one spelling and a value surviving in another
516
+ is the same defect four times over: the obligation `[ "\u0061bcd..." ]` disappears from the output not
517
+ because it was masked but because the output spells it decoded, and a comparison of raw strings reads
518
+ that as masked. An obligation is a VALUE, not a string, so every form of it is asked about."""
519
+ out, seen, pending = [], set(), [(value, 0)]
520
+ while pending:
521
+ text, depth = pending.pop()
522
+ if not isinstance(text, str) or not text or text in seen or depth > MAX_EMBEDDED:
523
+ continue
524
+ seen.add(text)
525
+ out.append(text)
526
+ for _start, _end, decoded in structures_in(text):
527
+ # the structure's SERIALISATION, not its leaves: every run of eight characters of a leaf is a
528
+ # run of the serialisation too, while a short leaf inside a larger obligation is not itself an
529
+ # obligation - asking about it asks about a character or two, which any output answers by chance
530
+ pending.append((serialise(decoded), depth + 1))
531
+ for inner in (escaped_form(text, depth), relaxed_decode(text)):
532
+ if inner is not None:
533
+ pending.append((inner, depth + 1))
534
+ return out
535
+
536
+
537
+ def is_mask(value):
538
+ """Whether this value is ENTIRELY this projection's own mask.
539
+
540
+ A projected text is a valid input: `{"password":"<REDACTED>"}` has a secret-named key, so the keyed rule
541
+ names its value, and that value is the placeholder. Counting it as a surviving credential discarded the
542
+ decoded result of every text that had already been masked and flattened the structure - the projection
543
+ stopped being idempotent, which is a contract, not a nicety.
544
+
545
+ The test is exact equality, and that is the point: a mask standing NEXT to, inside, or around a
546
+ credential exempts nothing. `{"token":"<REDACTED>","v":"abcdefghij"}` is not a mask, and reading it as
547
+ one is how a literal placeholder in the input bought acceptance for the value beside it."""
548
+ return value in (FLOOR.PLACEHOLDER, HOME_MASK)
549
+
550
+
551
+ def obligations(text):
552
+ """Every value the original text obliges this module to mask, each with all of its spellings - the
553
+ AUDIT's question, not the pass's.
554
+
555
+ The pass does not consult this: it masks extents, and an extent cannot be half-masked. What this answers
556
+ is whether a finished projection still READS a value the original obliged - which is the question a
557
+ control asks, and the one a reviewer asks. A value standing in the projection in any spelling it has is
558
+ the failure; the mask itself is not a value."""
559
+ spans = []
560
+ for pattern in floor_patterns():
561
+ for match in pattern.finditer(text):
562
+ secret = secret_part(match)
563
+ if secret:
564
+ spans.append((match.end() - len(secret), match.end()))
565
+ spans += [(start, end) for start, end, _replacement, _rank in keyed_spans(text)]
566
+ outer = [(a, b) for a, b in spans
567
+ if not any(c <= a and b <= d and (c, d) != (a, b) for c, d in spans)]
568
+ out = []
569
+ for a, b in sorted(set(outer)):
570
+ value = text[a:b]
571
+ if not value:
572
+ continue
573
+ forms = spellings(value)
574
+ if any(is_mask(form) for form in forms):
575
+ continue
576
+ out.append(forms)
577
+ return out
578
+
579
+
580
+ def readable_survivors(raw, out):
581
+ """Every original-text obligation of `raw` whose value still READS in `out` - in any spelling it has,
582
+ wholly or in any run of PARTIAL_SURVIVAL characters. This is the audit question: what is still there."""
583
+ return [forms[0] for forms in obligations(raw) if any(survives(form, out) for form in forms)]
584
+
585
+
586
+ def floor_leftovers(text, home=None):
587
+ """What the unchanged floor claims in `text` and the projection does NOT mask: the differential this
588
+ module is judged by.
589
+
590
+ The projection may mask more than the floor and never less. That direction is not a matter of taste -
591
+ the floor is the repository's single secret floor and every other caller relies on it - so it is asked
592
+ as a question about the output, through the oracle above."""
593
+ return floor_survivors(text, project_text(text, home))
594
+
595
+
596
+ def spans_of(text, home=None):
597
+ """Every span any rule would mask in `text`."""
598
+ return floor_spans(text) + keyed_spans(text) + path_spans(text, home)
599
+
600
+
601
+ def mask_one(text, home=None):
602
+ """`text` with ONE rule's spans applied - the home paths. The self-test uses it to state what that rule
603
+ alone does; the projection always masks the union, never one rule's spans."""
604
+ return mask_spans(text, path_spans(text, home))
605
+
606
+
607
+ def mask_spans(text, spans):
608
+ """`text` with every span masked, overlapping spans merged and each merged span masked to its FULL
609
+ extent. The strongest replacement wins an overlap: a secret's placeholder hides a path's tail, which
610
+ masks more than either rule alone asked for and never less."""
611
+ if not spans:
612
+ return text
613
+ merged = []
614
+ for span in sorted(spans, key=lambda s: (s[0], -s[1])):
615
+ start, end, replacement, rank = span
616
+ if start >= end:
617
+ continue
618
+ if merged and start <= merged[-1][1]:
619
+ prev = merged[-1]
620
+ merged[-1] = (prev[0], max(prev[1], end),
621
+ replacement if rank > prev[3] else prev[2], max(rank, prev[3]))
622
+ else:
623
+ merged.append((start, end, replacement, rank))
624
+ out, pos = [], 0
625
+ for start, end, replacement, _rank in merged:
626
+ out.append(text[pos:start])
627
+ out.append(replacement)
628
+ pos = end
629
+ out.append(text[pos:])
630
+ return "".join(out)
631
+
632
+
633
+ STATS = collections.Counter() # counts only: how often the decoded result was discarded, and why
634
+
635
+
636
+ def structures_in(text):
637
+ """Every serialised structure the text holds, as `(start, end, value)`, outermost and non-overlapping.
638
+
639
+ A block's text is not always a structure whole: a line of prose can carry one, and the credential may be
640
+ inside it. Asking only whether the stripped text begins with a brace missed every such block, which is
641
+ how a value behind a floor match that crosses the structure's syntax reached a window."""
642
+ decoder, out, pos = json.JSONDecoder(), [], 0
643
+ while pos < len(text):
644
+ nxt = min((i for i in (text.find("{", pos), text.find("[", pos)) if i >= 0), default=-1)
645
+ if nxt < 0:
646
+ break
647
+ try:
648
+ value, end = decoder.raw_decode(text, nxt)
649
+ except ValueError:
650
+ pos = nxt + 1
651
+ continue
652
+ if isinstance(value, (dict, list)):
653
+ out.append((nxt, end, value))
654
+ pos = end
655
+ else:
656
+ pos = nxt + 1
657
+ return out
658
+
659
+
660
+ def escaped_form(text, depth):
661
+ """`text` read as one level of JSON string escaping, or None. Exact, because JSON string encoding is a
662
+ bijection - and the only way the rules reach a member whose value opens a structure in escaped text."""
663
+ if depth > MAX_EMBEDDED or '\\"' not in text:
664
+ return None
665
+ try:
666
+ return json.loads(f'"{text}"')
667
+ except ValueError:
668
+ return None # a raw quote or control character: not one level of escaping
669
+
670
+
671
+ def undecodable_claim(text, depth):
672
+ """Whether this text names a secret key in some spelling and NOTHING here can decode it.
673
+
674
+ Read with every escape collapsed, the text says a credential stands in it; read as it is, no decoding
675
+ succeeds, so no rule can find that value's extent and no result can be shown to have masked it. That is
676
+ the same fail-closed position as an unprovable obligation, and it is a closing rule rather than another
677
+ spelling: nothing here enumerates how the escaping was written, only that it cannot be undone."""
678
+ flat = text.replace("\\", "")
679
+ if flat == text:
680
+ return False
681
+ # a claim whose value is already this module's mask hides nothing; a text where every claim is masked is
682
+ # a text this projection has already produced, and firing on it would make the projection non-idempotent
683
+ pending = [match for match in _KEYED.finditer(flat)
684
+ if not flat[match.end():].lstrip(" \t\r\n\"'").startswith((FLOOR.PLACEHOLDER, HOME_MASK))]
685
+ if not pending:
686
+ return False
687
+ return not (structures_in(text) or escaped_form(text, depth) is not None
688
+ or relaxed_decode(text) is not None)
689
+
690
+
691
+ def escape_map(text):
692
+ """For each character of `text` read as one level of JSON string escaping, the RAW span of `text` that
693
+ produced it - or None when `text` is not one level of such escaping, or when a decoded character has no
694
+ single span of its own.
695
+
696
+ This is what lets a finding in a decoded text be masked in the original's coordinates without
697
+ re-serialising anything: a span of the decoded text maps to the span of the raw text between the first
698
+ escape's start and the last escape's end, so a mask never lands inside an escape sequence."""
699
+ spans, index = [], 0
700
+ while index < len(text):
701
+ char = text[index]
702
+ if char != "\\":
703
+ spans.append((index, index + 1))
704
+ index += 1
705
+ continue
706
+ if index + 1 >= len(text):
707
+ return None
708
+ kind = text[index + 1]
709
+ if kind == "u":
710
+ if index + 6 > len(text):
711
+ return None
712
+ spans.append((index, index + 6))
713
+ index += 6
714
+ continue
715
+ if kind in '"\\/bfnrt':
716
+ spans.append((index, index + 2))
717
+ index += 2
718
+ continue
719
+ return None
720
+ decoded = relaxed_decode(text)
721
+ if decoded is None or len(decoded) != len(spans):
722
+ return None # a surrogate pair, or something this scanner does not model: not mappable
723
+ return spans
724
+
725
+
726
+ def holds_secret(value, home=None, depth=0):
727
+ """Whether a DECODED value is, or holds, a secret: a credential the floor claims, a secret-named key
728
+ whose value is not already the mask, or the owner's home path - at any depth this module decodes.
729
+
730
+ This is the question asked of what decoding reveals. It answers about the value; where that value came
731
+ from in the original text is a separate question, and `decoded_extents` answers that one."""
732
+ if depth > MAX_EMBEDDED:
733
+ return True # no further look is possible, so the honest answer is the closed one
734
+ if isinstance(value, str):
735
+ if is_mask(value):
736
+ return False
737
+ if any(pattern.search(value) for pattern in floor_patterns()):
738
+ return True
739
+ if any(pattern.search(value) for pattern in home_patterns(home)):
740
+ return True
741
+ if any(not is_mask(value[start:end]) for start, end, _replacement, _rank in keyed_spans(value)):
742
+ return True
743
+ for _start, _end, inner in structures_in(value):
744
+ if holds_secret(inner, home, depth + 1):
745
+ return True
746
+ for deeper in (escaped_form(value, depth), relaxed_decode(value)):
747
+ if deeper is not None and deeper != value and holds_secret(deeper, home, depth + 1):
748
+ return True
749
+ return False
750
+ if isinstance(value, dict):
751
+ for key, item in value.items():
752
+ if secret_key(key) and not (isinstance(item, str) and is_mask(item)) and item not in (None, "", {}, []):
753
+ return True
754
+ if holds_secret(key, home, depth + 1) or holds_secret(item, home, depth + 1):
755
+ return True
756
+ return False
757
+ if isinstance(value, (list, tuple)):
758
+ return any(holds_secret(item, home, depth + 1) for item in value)
759
+ return False
760
+
761
+
762
+ def encoded_secret_keys(value, home=None, depth=0):
763
+ """Every secret-named key inside a decoded value whose own member is not already masked."""
764
+ found = []
765
+ if isinstance(value, dict):
766
+ for key, item in value.items():
767
+ if isinstance(key, str) and secret_key(key) \
768
+ and not (isinstance(item, str) and is_mask(item)) and item not in (None, "", {}, []):
769
+ found.append(key)
770
+ if depth < MAX_EMBEDDED:
771
+ found += encoded_secret_keys(item, home, depth + 1)
772
+ elif isinstance(value, (list, tuple)) and depth < MAX_EMBEDDED:
773
+ for item in value:
774
+ found += encoded_secret_keys(item, home, depth + 1)
775
+ elif isinstance(value, str) and depth < MAX_EMBEDDED:
776
+ for _start, _end, inner in structures_in(value):
777
+ found += encoded_secret_keys(inner, home, depth + 1)
778
+ return found
779
+
780
+
781
+ def decoded_extents(text, home=None, depth=0):
782
+ """The extents of `text` that only DECODING shows to hold a secret, in `text`'s own coordinates.
783
+
784
+ Granularity is the literal: a finding at any decode depth marks the whole outermost raw string literal
785
+ it came from, because a mask inside an encoded literal is a mask in a text nobody reads, and because a
786
+ partial mask of an encoded value is how the last four rounds each leaked. A literal whose decoded content
787
+ equals its raw content is left to the rules above - they read it exactly as it stands, and masking it
788
+ whole would take a sentence for the sake of a path inside it.
789
+
790
+ An escaped text is handled in the same coordinates through `escape_map`; when that mapping cannot be
791
+ built and the decoded text holds a secret, the extent is the whole block."""
792
+ found, decoder, index = [], json.JSONDecoder(), 0
793
+ while index < len(text):
794
+ if text[index] != '"':
795
+ index += 1
796
+ continue
797
+ try:
798
+ value, end = decoder.raw_decode(text, index)
799
+ except ValueError:
800
+ index += 1
801
+ continue
802
+ if isinstance(value, str) and value != text[index + 1:end - 1] \
803
+ and holds_secret(value, home, depth + 1):
804
+ found.append((index + 1, end - 1, FLOOR.PLACEHOLDER, SECRET_SPAN))
805
+ index = max(end, index + 1)
806
+ # A structure whose secret-named KEY is written encoded. The keyed rule reads a key it can see and masks
807
+ # that key's value exactly; a key spelled `\u0070assword` it cannot see, and the value it names has no
808
+ # locatable extent of its own - so the structure that holds it is the unit, which is the granularity rule
809
+ # 1 names for a finding no literal explains.
810
+ for begin, finish, value in structures_in(text):
811
+ # Whether the raw rules can SEE the key, not whether its name appears somewhere in the structure.
812
+ # `{"note":"password","\u0070assword":"..."}` has the word in an unrelated value, and reading that
813
+ # as coverage left the encoded member's credential standing.
814
+ visible = visible_secret_keys(text[begin:finish])
815
+ hidden = [key for key in encoded_secret_keys(value, home) if key.lower() not in visible]
816
+ if hidden:
817
+ STATS["encoded_secret_key"] += 1
818
+ found.append((begin, finish, f'"{FLOOR.PLACEHOLDER}"', SECRET_SPAN))
819
+
820
+ # The ESCAPED spelling, over the region that carries it rather than over the whole block. Requiring the
821
+ # whole text to be one level of escaping let a decodable part elsewhere excuse an undecodable claim: a
822
+ # plain structure followed by an escaped `"password": "..."` was read by nothing at all.
823
+ for begin, finish in escaped_regions(text):
824
+ region = text[begin:finish]
825
+ decoded = relaxed_decode(region)
826
+ if decoded is None or not holds_secret(decoded, home, depth + 1):
827
+ continue
828
+ mapping = escape_map(region)
829
+ if not mapping:
830
+ STATS["unmappable_escape"] += 1
831
+ found.append((begin, finish, FLOOR.PLACEHOLDER, SECRET_SPAN))
832
+ continue
833
+ # EVERY extent the decoded level yields, not the deepest set alone: `decoded_extents(...) or
834
+ # mask_extents(...)` dropped the decoded level's own floor, keyed and path spans whenever a deeper
835
+ # extent existed, so a plain home path beside an encoded token was left for a second projection.
836
+ inner = list(mask_extents(decoded, home, depth + 1))
837
+ for start, end, replacement, rank in inner:
838
+ if end <= len(mapping) and start < end:
839
+ found.append((begin + mapping[start][0], begin + mapping[end - 1][1], replacement, rank))
840
+ return found
841
+
842
+
843
+ def escaped_regions(text):
844
+ """The regions of `text` to read as one level of JSON string escaping, as `(start, end)`.
845
+
846
+ The whole text is a region whenever it decodes as one - which does NOT require an escaped quote in it.
847
+ Keying this on `\\"` meant `sk\\u002dabcdefghijklmnopqrst` and an encoded home path were examined by
848
+ nothing at all: no raw rule matches the escaped spelling, no literal scanner finds a quote, and the
849
+ closing rule finds no keyed claim. Where escaped quotes are present they also give their own region, from
850
+ the first to the last, so a block that is plain in one part and escaped in another is read in both and
851
+ neither part excuses the other."""
852
+ regions = []
853
+ if relaxed_decode(text) is not None:
854
+ regions.append((0, len(text)))
855
+ if '\\"' in text:
856
+ first, last = text.index('\\"'), text.rindex('\\"') + 2
857
+ region = (first, max(last, first + 2))
858
+ if region not in regions:
859
+ regions.append(region if relaxed_decode(text[region[0]:region[1]]) is not None else (0, len(text)))
860
+ return regions
861
+
862
+
863
+ def mask_extents(text, home=None, depth=0):
864
+ """Every extent of `text` that must be masked, in `text`'s own coordinates: what the floor claims, the
865
+ whole value of every secret-named key, the owner's home paths, and whatever only decoding reveals."""
866
+ return (floor_spans_normalised(text) + keyed_spans(text) + path_spans(text, home)
867
+ + decoded_extents(text, home, depth))
868
+
869
+
870
+ VERIFY_DEPTH = 16 # decode layers the verifier descends - comfortably past MAX_EMBEDDED
871
+ VERIFY_BUDGET = 4096 # strings it will examine for one block, so a pathological input cannot hang a run
872
+
873
+
874
+ class Reach:
875
+ """What one verification traversal was able to look at.
876
+
877
+ It carries the budget because the honest answer to "is this output clean" depends on whether the whole
878
+ output was read. A traversal that stopped early has not verified anything, and `exhausted` is how it
879
+ says so instead of returning a clean-looking list."""
880
+
881
+ def __init__(self):
882
+ self.budget, self.exhausted, self.seen = VERIFY_BUDGET, False, set()
883
+ self.reason = None # the strict closure's own words for WHY it stopped
884
+
885
+
886
+ HIGH_SURROGATE = range(0xD800, 0xDC00)
887
+ LOW_SURROGATE = range(0xDC00, 0xE000)
888
+ _HEX4 = re.compile(r"[0-9a-fA-F]{4}")
889
+
890
+
891
+ def vf_pair(text, index):
892
+ """`(scalar, consumed)` for the `\\uXXXX` escape at `index` - or `(None, 0)` when it cannot be read.
893
+
894
+ A surrogate PAIR is one character. Reading the halves separately produced two lone surrogates, which no
895
+ normalisation maps: a compatibility name written in mathematical-alphanumeric letters arrived as
896
+ unmappable halves and the floor was never asked about the name it spells. A lone surrogate is therefore
897
+ not a character this reader can produce - it says so instead, and on the strict side that refuses the
898
+ quote."""
899
+ if _HEX4.fullmatch(text[index + 2:index + 6]) is None:
900
+ return None, 0
901
+ code = int(text[index + 2:index + 6], 16)
902
+ if code in HIGH_SURROGATE:
903
+ if text[index + 6:index + 8] == "\\u" and _HEX4.fullmatch(text[index + 8:index + 12]):
904
+ low = int(text[index + 8:index + 12], 16)
905
+ if low in LOW_SURROGATE:
906
+ return chr(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00)), 12
907
+ return None, 0 # a lone high surrogate
908
+ if code in LOW_SURROGATE:
909
+ return None, 0 # a lone low surrogate
910
+ return chr(code), 6
911
+
912
+
913
+ def vf_unescape(text):
914
+ """One layer of JSON string escaping, undone by the VERIFIER's own reader.
915
+
916
+ Written here rather than borrowed so the backstop does not share a decoder with the thing it checks: a
917
+ mistake in the projection's reading of an escape is exactly what this is here to catch. Returns None
918
+ when `text` is not one layer of such escaping - which includes a lone surrogate, since this reader
919
+ produces characters and a lone surrogate is not one."""
920
+ out, index = [], 0
921
+ while index < len(text):
922
+ char = text[index]
923
+ if char != "\\":
924
+ out.append(char)
925
+ index += 1
926
+ continue
927
+ if index + 1 >= len(text):
928
+ return None
929
+ kind = text[index + 1]
930
+ if kind == "u":
931
+ if index + 6 > len(text):
932
+ return None
933
+ scalar, consumed = vf_pair(text, index)
934
+ if scalar is None:
935
+ return None
936
+ out.append(scalar)
937
+ index += consumed
938
+ continue
939
+ simple = {'"': '"', "\\": "\\", "/": "/", "b": "\b", "f": "\f",
940
+ "n": "\n", "r": "\r", "t": "\t"}
941
+ if kind not in simple:
942
+ return None
943
+ out.append(simple[kind])
944
+ index += 2
945
+ return "".join(out)
946
+
947
+
948
+ def vf_relax(text):
949
+ """`text` with every `\\uXXXX` escape resolved where this reader can resolve it, surrogate pairs
950
+ included, for text that is not one clean layer of escaping throughout."""
951
+ out, index = [], 0
952
+ while index < len(text):
953
+ if text.startswith("\\u", index):
954
+ scalar, consumed = vf_pair(text, index)
955
+ if scalar is not None:
956
+ out.append(scalar)
957
+ index += consumed
958
+ continue
959
+ if text.startswith("\\/", index):
960
+ out.append("/")
961
+ index += 2
962
+ continue
963
+ out.append(text[index])
964
+ index += 1
965
+ return "".join(out)
966
+
967
+
968
+ class Members(list):
969
+ """A decoded JSON object as its members IN ORDER, duplicates kept.
970
+
971
+ `json.loads` keeps the last value for a repeated key, and a repeated secret-named key standing behind a
972
+ masked one is exactly the shape that got through: the verifier would have seen one `password` member,
973
+ already masked, and never the second."""
974
+
975
+
976
+ def vf_load(text):
977
+ """`text` read as a JSON document by the VERIFIER, with every member preserved - or None."""
978
+ try:
979
+ return json.loads(text, object_pairs_hook=Members)
980
+ except (ValueError, RecursionError):
981
+ return None
982
+
983
+
984
+ def vf_structures(text):
985
+ """Every JSON document embedded in `text`, decoded by the verifier's own scan, members preserved."""
986
+ found, decoder, index = [], json.JSONDecoder(object_pairs_hook=Members), 0
987
+ while index < len(text):
988
+ if text[index] not in "{[":
989
+ index += 1
990
+ continue
991
+ try:
992
+ value, end = decoder.raw_decode(text, index)
993
+ except (ValueError, RecursionError):
994
+ index += 1
995
+ continue
996
+ found.append(value)
997
+ index = max(end, index + 1)
998
+ return found
999
+
1000
+
1001
+ # The verifier's own reading of a keyed fragment in TEXT. Written here, with its own patterns, because the
1002
+ # question is what a READER sees - a name, a separator a few characters later, a value - and not where a
1003
+ # value's extent begins and ends. The mapping's scanner answers the second question and is the thing being
1004
+ # checked; a fragment in decoded mixed text (`"\u0070assword":"canary"` after a plain structure) is read by
1005
+ # neither the floor nor the member rule, and that is the gap this closes.
1006
+ # A name token, matched WHOLE. The cap of 41 characters split a long key into two tokens, neither of which
1007
+ # the floor claims - `xxxxxxxx...password` became `...pas` and `sword`, and the fragment went through. The
1008
+ # boundary is the one a key name has: a run of name characters, however long.
1009
+ VF_NAME = re.compile(r"[^\W\d][\w.-]*", re.UNICODE)
1010
+
1011
+
1012
+ # Whitespace, quotes and escape characters that may stand between a key and its separator - newlines
1013
+ # included. A quoted key followed by a newline and then the colon is one association a reader sees and the
1014
+ # per-line scan could not: the key's line had no separator on it at all.
1015
+ VF_GAP = re.compile(r"[\s\"'\\]*")
1016
+
1017
+
1018
+ def vf_region(text, after):
1019
+ """The value region beginning at `after`: everything to the end of that line, or the next non-empty line
1020
+ when the line ends at the separator.
1021
+
1022
+ The unit is the logical line because every bounded unit tried before it - a token, a span of so many
1023
+ characters - had a next bound for the following round to find. A line has no number in it.
1024
+
1025
+ One exception, and it is not a bound: a value that OPENS a structure is read from the whole text rather
1026
+ than from the line, because a structure's extent is a decoding question and a line cut through it left
1027
+ `[` alone - which then read as a structure this verifier cannot parse, and so as the owner-pending
1028
+ class. A structure that spans lines has a complete readable extent, and this is how it keeps it."""
1029
+ opening = text[after:].lstrip()
1030
+ if opening[:1] in ("{", "[", '"', "'"):
1031
+ # A quoted scalar and a structure both have an extent a scanner decides, not a line: the scalar's
1032
+ # own content is read to its closing quote wherever that stands, and what follows it has to be read
1033
+ # too, since a member's separator may sit on the next line. A line cut through either of them left
1034
+ # `[` alone - read as unparseable, and so as the owner-pending class - or cut the continuation that
1035
+ # tells packaging from content.
1036
+ return text[after:]
1037
+ end = text.find("\n", after)
1038
+ region = text[after:] if end < 0 else text[after:end]
1039
+ if region.strip():
1040
+ return region
1041
+ for later in text[end + 1:].split("\n") if end >= 0 else []:
1042
+ if later.strip():
1043
+ return later
1044
+ return region
1045
+
1046
+
1047
+ def vf_keyed(text):
1048
+ """Every `(name, value region)` fragment of `text` whose name the floor treats as a secret's.
1049
+
1050
+ Two readings, and a fragment either matches gives a region. The first is the line rule: a secret-named
1051
+ token, then a `:` or `=` anywhere later ON THE SAME LINE, any distance. The second crosses whitespace,
1052
+ quotes and escape characters from the token to the separator even over a newline, because
1053
+ `"password"\\n: "canary"` is an association a reader makes and the line rule reads as two lines, one
1054
+ with no separator on it."""
1055
+ found = []
1056
+ for match in VF_NAME.finditer(text):
1057
+ if not secret_key(match.group(0)):
1058
+ continue
1059
+ line_end = text.find("\n", match.end())
1060
+ line_rest = text[match.end():] if line_end < 0 else text[match.end():line_end]
1061
+ positions = [at for at in (line_rest.find(":"), line_rest.find("=")) if at >= 0]
1062
+ if positions:
1063
+ found.append((match.group(0), vf_region(text, match.end() + min(positions) + 1)))
1064
+ continue
1065
+ gap = VF_GAP.match(text, match.end())
1066
+ at = gap.end() if gap else match.end()
1067
+ if at < len(text) and text[at] in ":=":
1068
+ found.append((match.group(0), vf_region(text, at + 1)))
1069
+ return found
1070
+
1071
+
1072
+ def vf_scalar(region):
1073
+ """`(content, end)` for the quoted scalar `region` begins with - or `(None, 0)`.
1074
+
1075
+ A scanner, not a pattern: it tracks the opening quote and the escapes, so a comma, a brace or a newline
1076
+ INSIDE the scalar belongs to the scalar. It also returns where the scalar ENDED, because what follows a
1077
+ scalar is not the scalar's: replacing the region with the content alone discarded a suffix, and
1078
+ `"<REDACTED>"suffix_canary` passed as masked. None means this scanner could not read the scalar to its
1079
+ close, which is itself a finding rather than a pass."""
1080
+ text = region.lstrip()
1081
+ offset = len(region) - len(text)
1082
+ if not text or text[0] not in "\"'":
1083
+ return None, 0
1084
+ quote, index, out = text[0], 1, []
1085
+ while index < len(text):
1086
+ character = text[index]
1087
+ if character == "\\":
1088
+ if index + 1 >= len(text):
1089
+ return None, 0 # an escape with nothing behind it
1090
+ out.append(text[index + 1])
1091
+ index += 2
1092
+ continue
1093
+ if character == quote:
1094
+ return "".join(out), offset + index + 1
1095
+ out.append(character)
1096
+ index += 1
1097
+ return None, 0 # a scalar that never closes
1098
+
1099
+
1100
+ def vf_packaging(remainder):
1101
+ """Whether what follows a value is the value's PACKAGING, or the start of a further member of the
1102
+ structure the value sat in.
1103
+
1104
+ Packaging is whitespace, a comma or semicolon, and the brackets that close the structure. Content is
1105
+ anything else - and content directly after a masked scalar is what `"<REDACTED>"suffix_canary` hid
1106
+ behind, which is why the remainder is validated at all.
1107
+
1108
+ A remainder that BEGINS a further member is neither: `, "other": "x"}` is the rest of the object, and
1109
+ the member rule reads those members as members. Treating it as content made every one-line JSON object
1110
+ with a masked member a finding, and the member rule is the better reader of exactly that shape - it
1111
+ sees each member's key with its own value, which is what this text rule exists to approximate when
1112
+ nothing can be parsed at all."""
1113
+ text = remainder.strip()
1114
+ if all(character in " \t\r\n,;}])" for character in text):
1115
+ return True
1116
+ # the brackets that close the structures the value sat in, and then the rest of an enclosing one
1117
+ while text and text[0] in " \t\r\n}])":
1118
+ text = text[1:].lstrip()
1119
+ if not text:
1120
+ return True
1121
+ if text[0] not in ",;":
1122
+ return False
1123
+ # ... and what follows the comma must BE a further member - something with a separator of its own. Any
1124
+ # comma-prefixed text used to pass, so `"<REDACTED>",v15suffix` was read as packaging and the suffix
1125
+ # belonged to nobody: the member rule owns members, and that was not one.
1126
+ rest = text[1:]
1127
+ # the whole remainder, not its first line: a member's separator may stand on the next one, which is
1128
+ # exactly the shape `"password"\n: "..."` has
1129
+ return not rest.strip() or ":" in rest or "=" in rest
1130
+
1131
+
1132
+ def vf_leaves(value):
1133
+ """Every leaf VALUE of a decoded value, so each one can be held against the mask.
1134
+
1135
+ A key is not one. A key names a value; it is read by the member rule and by the detectors over the text,
1136
+ and counting it as a leaf made `{"password":{"a":"<REDACTED>"}}` a finding because `a` is not the
1137
+ mask."""
1138
+ if isinstance(value, Members):
1139
+ found = []
1140
+ for _key, item in value:
1141
+ found += vf_leaves(item)
1142
+ return found
1143
+ if isinstance(value, (list, tuple)):
1144
+ found = []
1145
+ for item in value:
1146
+ found += vf_leaves(item)
1147
+ return found
1148
+ return [value]
1149
+
1150
+
1151
+ def vf_exempt(region):
1152
+ """Whether a value region holds the mask and nothing else.
1153
+
1154
+ Three shapes, and each is read as what it is rather than stripped into submission:
1155
+
1156
+ * a quoted scalar - read with the scanner, its CONTENT compared exactly with the mask, and whatever
1157
+ follows the closing quote validated separately as packaging;
1158
+ * a structure whose extent this verifier can read - every leaf of it compared with the mask, so the key
1159
+ association survives. The owner-pending exemption is for a structure whose extent genuinely cannot be
1160
+ read, not for anything that merely begins with a bracket: a complete readable array held an ordinary
1161
+ string and was exempted on its opening character alone;
1162
+ * anything else - packaging removed from the OUTSIDE only, and what remains compared exactly.
1163
+ """
1164
+ text = region.strip()
1165
+ if not text:
1166
+ return True
1167
+ if text[0] in ('"', "'"):
1168
+ content, end = vf_scalar(text)
1169
+ if content is None:
1170
+ return False
1171
+ return content in ("", FLOOR.PLACEHOLDER, HOME_MASK) and vf_packaging(text[end:])
1172
+ decoder = json.JSONDecoder(object_pairs_hook=Members)
1173
+ if text[0] in "{[":
1174
+ try:
1175
+ value, end = decoder.raw_decode(text)
1176
+ except (ValueError, RecursionError):
1177
+ return True # an extent this verifier cannot read: the owner-pending class, unchanged
1178
+ if not vf_packaging(text[end:]):
1179
+ return False
1180
+ return all(leaf is None or isinstance(leaf, str) and leaf in ("", FLOOR.PLACEHOLDER, HOME_MASK)
1181
+ for leaf in vf_leaves(value))
1182
+ # a bare JSON scalar - a number, a boolean, a null - read as ONE value, so the members after it on the
1183
+ # same line are not swept into this one's region
1184
+ try:
1185
+ value, end = decoder.raw_decode(text)
1186
+ except (ValueError, RecursionError):
1187
+ value, end = None, -1
1188
+ if end >= 0 and not isinstance(value, (dict, list, Members)):
1189
+ return value is None and vf_packaging(text[end:])
1190
+ previous = None
1191
+ while text != previous:
1192
+ previous = text
1193
+ text = text.strip().rstrip(",;").rstrip()
1194
+ while text and text[-1] in "}])":
1195
+ text = text[:-1].rstrip(",;").rstrip()
1196
+ return text in ("", FLOOR.PLACEHOLDER, HOME_MASK)
1197
+
1198
+
1199
+ def vf_unfinished(text):
1200
+ r"""Whether an escape run in `text` STARTS and no reading of this verifier consumes it.
1201
+
1202
+ Asked per run, and of this string alone: an unrelated plain structure elsewhere in the block used to
1203
+ answer for a run nothing had read. A run is consumed when it is a valid JSON escape, or when the lenient
1204
+ reading can drop its backslash - which it cannot do before an actual newline, since that reading does
1205
+ not cross one. So three runs are unfinished: a backslash at the very end, a backslash before a real
1206
+ newline or carriage return, and a `\u` with fewer than four hex digits behind it. A Windows path is none
1207
+ of them."""
1208
+ index = 0
1209
+ while index < len(text):
1210
+ if text[index] != "\\":
1211
+ index += 1
1212
+ continue
1213
+ if index + 1 >= len(text):
1214
+ return True
1215
+ following = text[index + 1]
1216
+ if following == "\\":
1217
+ index += 2
1218
+ continue
1219
+ if following in "\r\n":
1220
+ return True
1221
+ if following == "u":
1222
+ scalar, consumed = vf_pair(text, index)
1223
+ if scalar is None:
1224
+ return True # too few hex digits, or a lone surrogate: a run nothing here can read
1225
+ index += consumed
1226
+ continue
1227
+ index += 2
1228
+ return False
1229
+
1230
+
1231
+ JSON_ESCAPE_TABLE = set('"\\/bfnrtu')
1232
+
1233
+
1234
+ def vf_outside_table(text):
1235
+ r"""The first backslash sequence in `text` that the JSON escape table does not define - or None.
1236
+
1237
+ The STRICT side's own reading, and the whole table: `\" \\ \/ \b \f \n \r \t` and `\uXXXX` with a
1238
+ surrogate pair joined. Anything else - `\x41`, `\q`, `\U0001D5C9`, a short `\u12`, a trailing lone
1239
+ backslash - is a sequence this reader does not define, so it cannot say what the text spells.
1240
+
1241
+ Deliberately NOT the lenient reading. That reading drops a backslash before anything at all, which is
1242
+ useful for finding what a careless reader recovers and useless for deciding what a text IS: it made
1243
+ `\x41` read as `x41`, nothing reported a layer left undone, and an unsupported escape passed strict
1244
+ admission. A Windows path is refused here for the same reason, which is the conservative direction on
1245
+ the side that stores text for sharing."""
1246
+ index = 0
1247
+ while index < len(text):
1248
+ if text[index] != "\\":
1249
+ index += 1
1250
+ continue
1251
+ if index + 1 >= len(text):
1252
+ return "\\" # a trailing lone backslash
1253
+ following = text[index + 1]
1254
+ if following not in JSON_ESCAPE_TABLE:
1255
+ return text[index:index + 2]
1256
+ if following == "u":
1257
+ scalar, consumed = vf_pair(text, index)
1258
+ if scalar is None:
1259
+ return text[index:index + 6] # short, or a lone surrogate
1260
+ index += consumed
1261
+ continue
1262
+ index += 2
1263
+ return None
1264
+
1265
+
1266
+ def vf_undecodable(value, depth=0, seen=None):
1267
+ """The first sequence outside the JSON escape table that the STRICT traversal reaches - or None.
1268
+
1269
+ At any decode depth: a quote may carry an unsupported escape behind a layer of escaping, or inside a
1270
+ JSON structure it spells. The traversal decodes with the table alone (`vf_unescape`, `vf_relax`,
1271
+ `vf_load`, `vf_structures`) and tracks the answer itself, so the lenient reading is never asked."""
1272
+ seen = set() if seen is None else seen
1273
+ if isinstance(value, Members):
1274
+ for key, item in value:
1275
+ for part in (key, item):
1276
+ found = vf_undecodable(part, depth + 1, seen)
1277
+ if found is not None:
1278
+ return found
1279
+ return None
1280
+ if isinstance(value, dict):
1281
+ return vf_undecodable(Members(value.items()), depth, seen)
1282
+ if isinstance(value, (list, tuple)):
1283
+ for item in value:
1284
+ found = vf_undecodable(item, depth + 1, seen)
1285
+ if found is not None:
1286
+ return found
1287
+ return None
1288
+ if not isinstance(value, str) or value in seen or depth > VERIFY_DEPTH:
1289
+ return None
1290
+ seen.add(value)
1291
+ outside = vf_outside_table(value)
1292
+ if outside is not None:
1293
+ return outside
1294
+ deeper = [form for form in (vf_unescape(value), vf_relax(value), vf_load(value))
1295
+ if form is not None and form != value] + list(vf_structures(value))
1296
+ for form in deeper:
1297
+ found = vf_undecodable(form, depth + 1, seen)
1298
+ if found is not None:
1299
+ return found
1300
+ return None
1301
+
1302
+
1303
+ def all_mask(value):
1304
+ """Whether a value is the mask and nothing else - for a structure, every leaf of it.
1305
+
1306
+ This is the verifier's own test of a secret-named member. It asks nothing about what the projection did
1307
+ or did not locate; it asks what the value IS. An absent value - null, empty text, an empty structure -
1308
+ discloses nothing and is not a secret."""
1309
+ if value is None or value == "" or value == [] or isinstance(value, Members) and not value:
1310
+ return True
1311
+ if isinstance(value, str):
1312
+ return is_mask(value)
1313
+ if isinstance(value, Members):
1314
+ return all(all_mask(item) for _key, item in value)
1315
+ if isinstance(value, (list, tuple)):
1316
+ return all(all_mask(item) for item in value)
1317
+ return False # a number, a boolean: not the mask, so a secret-named key still holds its value
1318
+
1319
+
1320
+ def vf_members(value):
1321
+ """The `(key, value)` members of one decoded object, duplicates and order preserved.
1322
+
1323
+ One object, not its nested ones: `every_spelling` hands every object it reaches to `discloses` as a form
1324
+ of its own, so recursing here would only ask the same question twice - and a second reader of the same
1325
+ rule is a place for the two to disagree."""
1326
+ return [(key, item) for key, item in value] if isinstance(value, Members) else []
1327
+
1328
+
1329
+ def every_spelling(value, depth=0, reach=None):
1330
+ """Every string and every decoded value the VERIFIER can reach from `value`, by its own decoder.
1331
+
1332
+ Returns `(forms, reach)`. A form is a string to run the detectors over, or a `Members` object whose
1333
+ members are checked as key/value pairs - the association is what matters, and flattening keys and values
1334
+ into one list of strings is what lost it. `reach.exhausted` is set when the traversal stopped with
1335
+ something still to decode: its depth limit, its budget, or a layer that starts and cannot be read."""
1336
+ reach = Reach() if reach is None else reach
1337
+ out = []
1338
+ if isinstance(value, Members):
1339
+ out.append(value)
1340
+ for key, item in value:
1341
+ out += every_spelling(key, depth, reach)[0] + every_spelling(item, depth, reach)[0]
1342
+ return out, reach
1343
+ if isinstance(value, dict):
1344
+ for key, item in value.items():
1345
+ out += every_spelling(key, depth, reach)[0] + every_spelling(item, depth, reach)[0]
1346
+ return out, reach
1347
+ if isinstance(value, (list, tuple)):
1348
+ for item in value:
1349
+ out += every_spelling(item, depth, reach)[0]
1350
+ return out, reach
1351
+ if not isinstance(value, str):
1352
+ return out, reach
1353
+ if value in reach.seen:
1354
+ return out, reach
1355
+ if reach.budget <= 0:
1356
+ reach.exhausted = True
1357
+ return out, reach
1358
+ reach.budget -= 1
1359
+ reach.seen.add(value)
1360
+ out.append(value)
1361
+
1362
+ deeper = []
1363
+ parsed = vf_load(value)
1364
+ if parsed is not None and not isinstance(parsed, (str, int, float, bool)):
1365
+ deeper.append(parsed)
1366
+ plain = vf_unescape(value)
1367
+ if plain is not None and plain != value:
1368
+ deeper.append(plain)
1369
+ # a hand-relaxed unescaping, for text that is not one clean layer throughout: an encoded run inside
1370
+ # ordinary prose is the shape that defeated a whole-body decode
1371
+ relaxed = vf_relax(value)
1372
+ if relaxed != value:
1373
+ deeper.append(relaxed)
1374
+ # ... and a fully lenient reading, where a backslash before anything at all is dropped. Six layers of
1375
+ # `\u005c` decode down to `sk\-abcdefghijklmnopqrst`: no further layer is valid JSON escaping, the floor
1376
+ # does not match the backslash, and the credential stood there in a form any careless reader recovers.
1377
+ lenient = re.sub(r"\\(.)", r"\1", value)
1378
+ if lenient != value and lenient != relaxed:
1379
+ deeper.append(lenient)
1380
+ deeper += vf_structures(value)
1381
+
1382
+ # An escape run that starts and cannot be read is a layer this traversal did not finish - asked per
1383
+ # run, and of this string alone. Testing it as "and nothing else decoded" let an unrelated plain
1384
+ # structure elsewhere in the block answer for the run.
1385
+ if vf_unfinished(value):
1386
+ reach.exhausted = True
1387
+
1388
+ if deeper and depth >= VERIFY_DEPTH:
1389
+ reach.exhausted = True
1390
+ return out, reach
1391
+ for item in deeper:
1392
+ out += every_spelling(item, depth + 1, reach)[0]
1393
+ return out, reach
1394
+
1395
+
1396
+ def discloses_uncached(text, home=None):
1397
+ """What a projected block still discloses, named by the detector that found it - or None.
1398
+
1399
+ `discloses` is this, remembered; this is the verifier itself, and what the cache's controls compare it with.
1400
+
1401
+ Three rules, each LOCAL and TOTAL - they ask what the output contains, never what the projection did
1402
+ with it:
1403
+
1404
+ * a floor match in any spelling the verifier can reach;
1405
+ * the owner's home path in any spelling;
1406
+ * a secret-named key whose value is not exactly the mask, for EVERY member of every decoded object,
1407
+ duplicates included and whatever whitespace stands around the colon.
1408
+
1409
+ The third used to be asked through the projection's own textual scanner, which reads a key only where it
1410
+ can locate its value, and whose mapping had already declared the key "covered" by NAME - so a duplicate
1411
+ member, or one with a newline before its colon, was skipped by both. A backstop that consults the
1412
+ mapping cannot catch the mapping. `self_test` holds that structurally: these functions call nothing of
1413
+ the mapping."""
1414
+ forms, reach = every_spelling(text)
1415
+ # The member rule first, over every decoded object: when a block is a document, that is the reading that
1416
+ # names what was found, and the text rule below would otherwise answer for it with a coarser name.
1417
+ for form in forms:
1418
+ if isinstance(form, Members):
1419
+ for key, item in vf_members(form):
1420
+ if isinstance(key, str) and secret_key(key) and not all_mask(item):
1421
+ return "secret-named key"
1422
+ for form in forms:
1423
+ if isinstance(form, Members):
1424
+ continue
1425
+ if any(pattern.search(form) for pattern in floor_patterns()):
1426
+ return "floor"
1427
+ if any(pattern.search(form) for pattern in home_patterns(home)):
1428
+ return "home path"
1429
+ if any(not vf_exempt(value) for _name, value in vf_keyed(form)):
1430
+ return "keyed fragment"
1431
+ return "verifier-limit" if reach.exhausted else None
1432
+
1433
+
1434
+ # ---- the verifier's answers, remembered ------------------------------------------------------------
1435
+ #
1436
+ # One run asks the verifier the same question many times over: the inventory's self-test made 10,769,881
1437
+ # calls over 21,291 distinct (text, home) inputs, and spent 191.3 of its 192.6 seconds in the verifier on
1438
+ # inputs it had already asked about (2026-10-30, f506ef0). An answer depends on three things and nothing
1439
+ # else - the text, the home it is judged against, and the rules in force - so it is remembered under all
1440
+ # three. The rules are not a list kept here: they are every module-level name `discloses_uncached` reaches,
1441
+ # followed through this module's own functions and classes (`DISCLOSURE_RULE_NAMES`, derived at the end of
1442
+ # the module, once every name exists), and every member of the floor. A rule replaced while the module runs - a self-test plants one - starts a new generation, and an
1443
+ # answer of an older generation is never returned for it.
1444
+ #
1445
+ # The text itself is not kept: its sha256 is, so the bound is a bound on memory whatever the texts' length.
1446
+ DISCLOSES_CACHE_MAX = 65536 # answers remembered at most; past it the oldest is forgotten first
1447
+ DISCLOSES_CACHE_STATS = collections.Counter() # hits, misses, evicted, cleared, bypassed - updated under the lock
1448
+ _DISCLOSES_CACHE = {} # (sha256 of the text, the resolved home, the generation) -> the answer
1449
+ _DISCLOSES_STATE = {"rules": None, "generation": 0}
1450
+ _DISCLOSES_LOCK = threading.Lock()
1451
+
1452
+
1453
+ def disclosure_rules():
1454
+ """The rules in force NOW, as one comparable value: the current value of every name the verifier reaches,
1455
+ and every member of the floor - a list read as its items, because the floor's patterns are changed in
1456
+ place as well as rebound. It is compared, never hashed: a rule is the same when it is the same object."""
1457
+ floor = tuple((name, tuple(value) if isinstance(value, list) else value)
1458
+ for name, value in vars(FLOOR).items() if not name.startswith("__"))
1459
+ return tuple(map(globals().get, DISCLOSURE_RULE_NAMES)), floor
1460
+
1461
+
1462
+ def discloses(text, home=None):
1463
+ """`discloses_uncached`, remembered under the text, the home and the rules in force.
1464
+
1465
+ The home is resolved here, once, and the verifier is asked with exactly the home the key holds: `None`
1466
+ means this process's home as it stands at the call, so a changed `HOME` is a different key. Anything but
1467
+ a plain string text and home is asked of the verifier directly. An exception is never remembered."""
1468
+ resolved = os.path.expanduser("~") if home is None else home
1469
+ if type(text) is not str or type(resolved) is not str:
1470
+ with _DISCLOSES_LOCK:
1471
+ DISCLOSES_CACHE_STATS["bypassed"] += 1
1472
+ return discloses_uncached(text, resolved)
1473
+ rules = disclosure_rules()
1474
+ digest = hashlib.sha256(text.encode("utf-8", "surrogatepass")).digest()
1475
+ with _DISCLOSES_LOCK:
1476
+ if rules != _DISCLOSES_STATE["rules"]:
1477
+ if _DISCLOSES_STATE["rules"] is not None:
1478
+ DISCLOSES_CACHE_STATS["cleared"] += 1
1479
+ _DISCLOSES_STATE["rules"] = rules
1480
+ _DISCLOSES_STATE["generation"] += 1
1481
+ _DISCLOSES_CACHE.clear()
1482
+ key = (digest, resolved, _DISCLOSES_STATE["generation"])
1483
+ if key in _DISCLOSES_CACHE:
1484
+ DISCLOSES_CACHE_STATS["hits"] += 1
1485
+ return _DISCLOSES_CACHE[key]
1486
+ answer = discloses_uncached(text, resolved)
1487
+ with _DISCLOSES_LOCK:
1488
+ DISCLOSES_CACHE_STATS["misses"] += 1
1489
+ while _DISCLOSES_CACHE and len(_DISCLOSES_CACHE) >= DISCLOSES_CACHE_MAX:
1490
+ del _DISCLOSES_CACHE[next(iter(_DISCLOSES_CACHE))]
1491
+ DISCLOSES_CACHE_STATS["evicted"] += 1
1492
+ _DISCLOSES_CACHE[key] = answer
1493
+ return answer
1494
+
1495
+
1496
+ def _reached_names(start):
1497
+ """The module-level names `start` reaches, `start` included: every name its code reads, followed into this
1498
+ module's own functions and into the methods of its own classes, nested code included - a helper three calls
1499
+ down is as much the verifier as its entry point is."""
1500
+ namespace = globals()
1501
+ names, pending = {start}, [namespace[start]]
1502
+ while pending:
1503
+ value = pending.pop()
1504
+ if isinstance(value, types.FunctionType) and value.__module__ == __name__:
1505
+ codes = [value.__code__]
1506
+ elif isinstance(value, type) and value.__module__ == __name__:
1507
+ codes = [member.__code__ for member in vars(value).values() if isinstance(member, types.FunctionType)]
1508
+ else:
1509
+ continue
1510
+ while codes:
1511
+ code = codes.pop()
1512
+ codes += [constant for constant in code.co_consts if isinstance(constant, types.CodeType)]
1513
+ for name in code.co_names:
1514
+ if name in namespace and name not in names:
1515
+ names.add(name)
1516
+ pending.append(namespace[name])
1517
+ return tuple(sorted(names))
1518
+
1519
+
1520
+ def spellings_of(value):
1521
+ """Just the forms `every_spelling` reaches - for a caller sweeping artifacts, where the traversal's own
1522
+ reach is reported by the projection that produced them rather than asked again here."""
1523
+ return [form for form in every_spelling(value)[0] if isinstance(form, str)]
1524
+
1525
+
1526
+ # A name token, Unicode-aware. `\w` is Unicode in Python 3, so a name written in any script is one token;
1527
+ # the ASCII class this used to carry split `paſſword` into `pa` and `word` and the floor's own matching never
1528
+ # saw the name at all.
1529
+ VF_TOKEN = re.compile(r"[\w.-]+", re.UNICODE)
1530
+
1531
+
1532
+ # AB#0: the categories whose characters render nothing of their own - the three mark categories, the
1533
+ # format characters, and the unassigned points, which have no glyph at all and are where a tag block's
1534
+ # holes live.
1535
+ VF_INVISIBLE_CATEGORIES = ("Mn", "Mc", "Me", "Cf", "Cn")
1536
+
1537
+ # ... and the characters NO category names. The variation selectors, their supplement, the Mongolian
1538
+ # U+180B..U+180F run and the tag block are all covered above, so listing them would be lines no revert
1539
+ # can make fail; the control asserts this list holds nothing a category covers, which is what keeps that
1540
+ # true as Unicode assigns new characters.
1541
+ VF_IGNORABLE = frozenset([0x115F, 0x1160, 0x3164, 0xFFA0]) # Hangul and halfwidth fillers: ordinary
1542
+ # letters (Lo) that render nothing
1543
+
1544
+
1545
+ def vf_invisible(character):
1546
+ """Whether `character` renders nothing of its own, or only modifies the character beside it.
1547
+
1548
+ A skeleton that drops only `Mn` closed accents and left every other invisible character standing, so
1549
+ `pass<ZWSP>word` tokenised as two names and the floor was asked about neither. The test is the property
1550
+ rather than a list of attacks: all three mark categories (`Mn`, `Mc`, `Me`), the format characters
1551
+ (`Cf` - zero-width space, joiner and non-joiner, soft hyphen, the bidi controls, the word joiner, the
1552
+ tag characters), the unassigned points (`Cn`), which have no glyph at all, and the fillers listed
1553
+ above, which are ordinary letters to Unicode and render nothing to a reader.
1554
+
1555
+ This is the strict side, where over-refusal costs a quote and under-refusal ships a credential. It is
1556
+ NOT a confusable mapping: a Cyrillic or Greek lookalike renders a character of its own, and the owner
1557
+ placed those outside the strict rule's scope on 2026-10-22. The rule covers spelling variants - the
1558
+ escape table, Unicode normalisation, and characters that render nothing - and stops there."""
1559
+ return (unicodedata.category(character) in VF_INVISIBLE_CATEGORIES
1560
+ or ord(character) in VF_IGNORABLE)
1561
+
1562
+
1563
+ def vf_skeletons(text):
1564
+ """The spellings of `text` the strict rule asks the floor about.
1565
+
1566
+ A union rather than one canonical form, because no single normalisation preserves every name the floor
1567
+ recognises. Casefolding `APİ_KEY` (U+0130) inserts a combining dot and the floor's `api[_-]?key` no
1568
+ longer matches it; NFKC alone leaves a fullwidth `secret` unmatched; and a combining acute over an
1569
+ `o` hides `password` from both. So the floor is asked about all of them:
1570
+
1571
+ * the text as it stands, which is what the floor itself would see;
1572
+ * NFKC, which folds compatibility spellings;
1573
+ * casefold, which folds case across scripts;
1574
+ * NFKC of the casefold of NFKC, which folds the two in the order that settles U+0130;
1575
+ * a skeleton - NFKD, every character that renders nothing of its own dropped, casefolded, NFKC -
1576
+ which folds accents away and closes `pass<ZWSP>word` with them.
1577
+
1578
+ Over-refusal is acceptable here: a refused quote is simply not stored, and the caller quotes a span
1579
+ that names nothing. Under-refusal is a credential in a shared record."""
1580
+ bare = "".join(character for character in unicodedata.normalize("NFKD", text)
1581
+ if not vf_invisible(character))
1582
+ return list(dict.fromkeys([
1583
+ text,
1584
+ unicodedata.normalize("NFKC", text),
1585
+ text.casefold(),
1586
+ unicodedata.normalize("NFKC", unicodedata.normalize("NFKC", text).casefold()),
1587
+ unicodedata.normalize("NFKC", bare.casefold()),
1588
+ ]))
1589
+
1590
+
1591
+ def vf_name_in(text):
1592
+ """The first complete name token in THIS ONE string that the floor treats as a secret's - or None.
1593
+
1594
+ `vf_secret_name` is this asked about each of `vf_skeletons`. The split exists so strict admission can
1595
+ hand all three of its detectors the same string: when the name detector expanded the spellings itself
1596
+ and the other two did not, only names were judged in normalised form (AC#0)."""
1597
+ for match in VF_TOKEN.finditer(text):
1598
+ if secret_key(match.group(0)):
1599
+ return match.group(0)
1600
+ return None
1601
+
1602
+
1603
+ # AD#0 / AD#1: the strict side's spelling set is a CLOSURE, not a pipeline. Two orders were missing when
1604
+ # the set was "each decode layer, expanded by the skeleton": invisible characters were stripped only in
1605
+ # the casefolded skeleton, so a case-sensitive owner path never saw a stripped, case-preserved spelling;
1606
+ # and an escape that normalisation REVEALS (a fullwidth backslash NFKC turns into `\`) was never decoded,
1607
+ # because decoding ran before normalising and never again.
1608
+ VF_CLOSURE_LIMIT = 256 # strings; a quote whose closure is larger is refused, never truncated
1609
+ VF_CLOSURE_ROUNDS = 12 # ... and so is one that is still growing after this many rounds
1610
+
1611
+
1612
+ def vf_transforms(text):
1613
+ """Every SINGLE-STEP transform the closure applies to one string.
1614
+
1615
+ One layer undone by the JSON escape table (strict and relaxed), NFKC, casefold, the invisible
1616
+ characters stripped, and NFKD. Each is one step and the closure composes them, so no order is
1617
+ privileged: `casefold then decode` is in the set exactly as `decode then casefold` is, and the
1618
+ skeleton of r20 is now one path through these rather than a form of its own."""
1619
+ out = []
1620
+ plain = vf_unescape(text)
1621
+ if plain is not None:
1622
+ out.append(plain)
1623
+ out.append(vf_relax(text))
1624
+ out.append(unicodedata.normalize("NFKC", text))
1625
+ out.append(unicodedata.normalize("NFKD", text))
1626
+ out.append(text.casefold())
1627
+ out.append("".join(character for character in text if not vf_invisible(character)))
1628
+ return [form for form in out if form and form != text]
1629
+
1630
+
1631
+ def vf_all_spellings(quote):
1632
+ """`(spellings, members, reach)` - the closure of `quote` under `vf_transforms`.
1633
+
1634
+ One function so the three triggers cannot diverge, and a closure so no composition of steps can be
1635
+ missing. Every string in the set has had every transform applied to it, and the result was already in
1636
+ the set, which the self-test asserts directly.
1637
+
1638
+ Bounded, and the bound REFUSES rather than truncates: `reach.exhausted` is set when the set would pass
1639
+ `VF_CLOSURE_LIMIT` strings, when it is still growing after `VF_CLOSURE_ROUNDS` rounds, or when any
1640
+ string in it holds a sequence the JSON escape table does not define. A truncated set would be a clean
1641
+ answer about a quote nobody finished reading."""
1642
+ spellings, members, reach = [], [], Reach()
1643
+ seen, pending, rounds = set(), [quote], 0
1644
+ while pending:
1645
+ rounds += 1
1646
+ if rounds > VF_CLOSURE_ROUNDS:
1647
+ reach.exhausted, reach.reason = True, f"its spellings were still growing after {rounds - 1} rounds"
1648
+ return [], [], reach
1649
+ following = []
1650
+ for text in pending:
1651
+ if not isinstance(text, str) or text in seen:
1652
+ continue
1653
+ if len(seen) >= VF_CLOSURE_LIMIT:
1654
+ reach.exhausted, reach.reason = True, f"it spells more than {VF_CLOSURE_LIMIT} strings"
1655
+ return [], [], reach
1656
+ seen.add(text)
1657
+ spellings.append(text)
1658
+ outside = vf_outside_table(text)
1659
+ if outside is not None:
1660
+ reach.exhausted = True
1661
+ reach.reason = f"one of its spellings holds {outside!r}, which the JSON escape table does " \
1662
+ f"not define"
1663
+ return [], [], reach
1664
+ following += vf_transforms(text)
1665
+ for structure in [vf_load(text)] + list(vf_structures(text)):
1666
+ following += vf_structure_strings(structure, members)
1667
+ pending = following
1668
+ return spellings, members, reach
1669
+
1670
+
1671
+ def vf_structure_strings(value, members):
1672
+ """The strings inside a decoded structure, collecting its member objects into `members` on the way."""
1673
+ strings, stack = [], [value]
1674
+ while stack:
1675
+ item = stack.pop()
1676
+ if isinstance(item, Members):
1677
+ members.append(item)
1678
+ for key, member in item:
1679
+ stack += [key, member]
1680
+ elif isinstance(item, dict):
1681
+ members.append(Members(item.items()))
1682
+ stack += list(item.keys()) + list(item.values())
1683
+ elif isinstance(item, (list, tuple)):
1684
+ stack += list(item)
1685
+ elif isinstance(item, str):
1686
+ strings.append(item)
1687
+ return strings
1688
+
1689
+
1690
+ # Self-test only: when this is a dict, admission records which strings each detector was asked about, so
1691
+ # a control can assert the three sets are identical rather than trusting that they are.
1692
+ SPELLING_PROBE = None
1693
+
1694
+
1695
+ def vf_probe(detector, spelling):
1696
+ if SPELLING_PROBE is not None:
1697
+ SPELLING_PROBE.setdefault(detector, []).append(spelling)
1698
+
1699
+
1700
+ def vf_secret_name(text):
1701
+ """The first complete name token in `text` that THE FLOOR treats as a secret's - or None.
1702
+
1703
+ Two properties, and the previous form of this gave up one for the other. The floor is asked directly,
1704
+ with its own pattern, its own end-of-name context and its own flags, so the strict rule cannot be
1705
+ narrower than the floor; and it is asked about whole TOKENS, so `input_tokens` and `tokenizer` are
1706
+ ordinary names rather than names that happen to contain one. An alternation scraped out of the floor's
1707
+ pattern had neither property: unanchored, it claimed every name containing `token`, and recompiled, it
1708
+ lost the recognition the floor's own flags give it."""
1709
+ for spelling in vf_skeletons(text):
1710
+ found = vf_name_in(spelling)
1711
+ if found is not None:
1712
+ return found
1713
+ return None
1714
+
1715
+
1716
+ def evidence_quote_admissible(quote, home=None):
1717
+ """Whether a quote may stand as evidence: it names no secret at all, in any spelling.
1718
+
1719
+ This is STRICTER than the projection's rule and deliberately so. The projection decides what a window
1720
+ may show, where a secret-named key with a masked value is a correct and useful thing to show. A quote is
1721
+ a different object: it is lifted out of its block and carried into a report, so the context that made
1722
+ `"password": "<REDACTED>"` safe to read does not travel with it. This refuses a quote that, in any
1723
+ spelling the verifier can reach, holds a secret-named token, a floor match, or the owner's home path -
1724
+ the key's NAME included, masked value or not.
1725
+
1726
+ Owner decision of 2026-10-21: the rule is strict and blocking for everything persisted for sharing.
1727
+ `evidence.make` and `evidence.append` both ask it."""
1728
+ # AA#0: the strict traversal decides undecodability itself, with the JSON escape table and nothing
1729
+ # else. Inheriting the lenient reading's treatment of an unsupported escape let `\x41` pass as `x41`.
1730
+ outside = vf_undecodable(quote)
1731
+ if outside is not None:
1732
+ return False, f"undecodable: the quote holds {outside!r}, which the JSON escape table does not define"
1733
+ spellings, members, reach = vf_all_spellings(quote)
1734
+ if reach.exhausted:
1735
+ # The strict side's principle, and it is a principle rather than a case: a valid surrogate pair
1736
+ # decodes to its scalar, and a lone surrogate, an invalid escape or any decoding this traversal
1737
+ # cannot complete refuses the quote. An encoding nobody here can finish reading is an encoding
1738
+ # whose content nobody here can rule out.
1739
+ return False, ("undecodable: " + (reach.reason or
1740
+ "the quote holds an encoding this verifier cannot finish reading"))
1741
+ for member in members:
1742
+ for key, _item in vf_members(member):
1743
+ if isinstance(key, str):
1744
+ named = vf_secret_name(key)
1745
+ if named:
1746
+ return False, f"the quote names the secret-named key {named!r}"
1747
+ # AC#0: one set, three detectors, one loop. The name detector used to expand the normalised spellings
1748
+ # inside itself while the floor's value patterns and the owner-path detector saw the decoded string
1749
+ # alone, so a fullwidth or zero-width-spaced owner path was judged by a narrower set than a name was.
1750
+ floors, homes = floor_patterns(), home_patterns(home)
1751
+ detectors = (
1752
+ ("floor", lambda text: "the quote holds a credential the floor claims"
1753
+ if any(pattern.search(text) for pattern in floors) else None),
1754
+ ("home", lambda text: "the quote holds the owner's home path"
1755
+ if any(pattern.search(text) for pattern in homes) else None),
1756
+ ("name", lambda text: (lambda named: f"the quote names the secret-named token {named!r}"
1757
+ if named is not None else None)(vf_name_in(text))),
1758
+ )
1759
+ for spelling in spellings:
1760
+ for detector, ask in detectors:
1761
+ vf_probe(detector, spelling)
1762
+ why = ask(spelling)
1763
+ if why is not None:
1764
+ return False, why
1765
+ return True, None
1766
+
1767
+
1768
+ BLANKED = collections.Counter() # run-scoped: how many BLANKING OPERATIONS the backstop ran, by detector
1769
+ BLOCKS = collections.Counter() # ... and how many CONTENT BLOCKS it blanked, counted once per block
1770
+ _OPEN_BLOCK = [] # the detectors seen while the current content block was projected
1771
+
1772
+
1773
+ def parses_as_json(text):
1774
+ """Whether this block is a JSON document."""
1775
+ try:
1776
+ json.loads(text)
1777
+ except (ValueError, RecursionError):
1778
+ return False
1779
+ return True
1780
+
1781
+
1782
+ def blank_for(original):
1783
+ """What a blanked block becomes: the mask, as a valid JSON string when the block itself was valid JSON.
1784
+
1785
+ Blanking a JSON document to a bare `<REDACTED>` left a block that no longer parsed, and a window a
1786
+ reader opens is read as JSON by everything downstream."""
1787
+ if not parses_as_json(original):
1788
+ return FLOOR.PLACEHOLDER
1789
+ return json.dumps(FLOOR.PLACEHOLDER, ensure_ascii=False)
1790
+
1791
+
1792
+ def emit(original, projected, home=None, masked=None):
1793
+ """THE EXIT. Every projected block this module returns leaves through here, and here it is verified.
1794
+
1795
+ One choke point rather than a call at each site: the structured path used to serialise its walk and
1796
+ return it unverified, so two leaves that were each clean on their own emitted a floor match across the
1797
+ member boundary between them - and a second projection then masked it, which is also how idempotence
1798
+ broke. What a reader, an index and an evidence quote all see is the FINAL emitted text, so that is the
1799
+ text the backstop reads. `self_test` holds this structurally: every `return` in the block-producing
1800
+ functions is a call to this one."""
1801
+ STATS["emitted"] += 1
1802
+ reason = discloses(projected, home)
1803
+ if not reason and parses_as_json(original) and not parses_as_json(projected):
1804
+ # valid JSON in, valid JSON out: a window a reader opens is read as JSON by everything downstream,
1805
+ # and a masking that breaks the syntax is a block nothing can quote from
1806
+ reason = "broken syntax"
1807
+ if reason:
1808
+ STATS[f"blanked:{reason}"] += 1
1809
+ BLANKED[reason] += 1 # one blanking operation; a block's leaves may each contribute one
1810
+ if _OPEN_BLOCK:
1811
+ _OPEN_BLOCK[-1].append(reason)
1812
+ projected = blank_for(original)
1813
+ return note_change(original, projected, "a masked span", masked)
1814
+
1815
+
1816
+ def project_text(text, home=None, depth=0, masked=None):
1817
+ """One string's projection: ONE monotone pass in the original text's own coordinates.
1818
+
1819
+ There is no decoded candidate and no fallback, because the gap between those two paths is what leaked in
1820
+ four consecutive rounds - each new rule closing one side and opening the other. Instead every source of
1821
+ masking answers in the SAME coordinates, the union of their extents is masked once, and nothing is
1822
+ re-serialised: a document a person reads keeps its formatting, with the masked extents replaced.
1823
+
1824
+ Masks only grow, so the pass is monotone, and a mask extent is never a secret - `is_mask` is exact - so
1825
+ projecting a projection changes nothing."""
1826
+ if undecodable_claim(text, depth):
1827
+ STATS["undecodable_claim"] += 1
1828
+ return emit(text, blank_for(text), home, masked)
1829
+ return emit(text, mask_spans(text, mask_extents(text, home, depth)), home, masked)
1830
+
1831
+
1832
+ def carrier_decision(carrier, home=None):
1833
+ """What this floor decides about a WHOLE carrier, for every span of it to inherit:
1834
+ `(extents, withheld)`.
1835
+
1836
+ `extents` are what it would mask, in the carrier's own coordinates — a credential's key and its
1837
+ value are one relationship, and a splitter that puts the two in different blocks breaks that
1838
+ relationship for anything reading a block alone.
1839
+
1840
+ `withheld` is the decision extents cannot express: the floor sometimes declines to return the
1841
+ carrier AT ALL — undecodable escaped text, an output that still discloses, a masking that broke
1842
+ the syntax. That decision is taken in `emit`, about the whole, and it is asked here by projecting
1843
+ the whole carrier THROUGH THAT ONE EXIT rather than by re-deriving its conditions, which would be
1844
+ a second authority on the same question.
1845
+
1846
+ Extents alone were the leak: for the Markdown carrier `api\\_key: "alpha\\nbravo\\n\\nshortpass"`
1847
+ `project` returns the mask, while the span path applied the undecodable decision only to the
1848
+ detached span and emitted `shortpass` from a later one."""
1849
+ whole = project(carrier, CURRENT, home)
1850
+ if whole == blank_for(carrier):
1851
+ return [], True
1852
+ return mask_extents(carrier, home, 0), False
1853
+
1854
+
1855
+ def carrier_extents(carrier, home=None):
1856
+ """The masked extents of a whole carrier. A caller wants `carrier_decision`: this omits the
1857
+ whole-carrier withholding decision, which is not expressible as an extent."""
1858
+ return mask_extents(carrier, home, 0)
1859
+
1860
+
1861
+ def project_span(carrier, start, end, home=None, decision=None):
1862
+ """The projection of `carrier[start:end]`, judged with the carrier INTACT.
1863
+
1864
+ Two things carry over from the whole carrier. A decision to WITHHOLD it withholds every span of
1865
+ it: a span of a carrier the floor refused to return is refused too, never projected on its own.
1866
+ Otherwise the carrier's extents are clipped to the span, UNION the span's own — the key three
1867
+ lines above the value still masks it, a credential straddling the span's start is masked for the
1868
+ part inside it, and nothing the span discloses alone is lost because the carrier's context
1869
+ suppressed a match. Masks only grow, which is what makes the union the safe direction.
1870
+
1871
+ This replaces a fixed window of preceding lines. Two nonblank lines do not preserve a carrier's
1872
+ structural context: for `api_key: [\\n "alpha",\\n\\n "bravo",\\n\\n "shortpass"\\n]` the key had
1873
+ fallen outside the window by the time the last element's block was projected, and the value was
1874
+ emitted with nothing to mark it."""
1875
+ span = carrier[start:end]
1876
+ extents, withheld = carrier_decision(carrier, home) if decision is None else decision
1877
+ if withheld or undecodable_claim(span, 0):
1878
+ STATS["carrier_withheld" if withheld else "undecodable_claim"] += 1
1879
+ return emit(span, blank_for(span), home)
1880
+ clipped = []
1881
+ for extent_start, extent_end, replacement, rank in extents:
1882
+ low, high = max(extent_start, start), min(extent_end, end)
1883
+ if low < high:
1884
+ clipped.append((low - start, high - start, replacement, rank))
1885
+ return emit(span, mask_spans(span, clipped + mask_extents(span, home, 0)), home)
1886
+
1887
+
1888
+ def note_change(before, after, what, masked):
1889
+ """`after`, recording that `what` changed the text when it did."""
1890
+ if masked is not None and after != before:
1891
+ masked.append(what)
1892
+ return after
1893
+
1894
+
1895
+ def walk(value, home=None, depth=0, masked=None):
1896
+ """`value` with every string projected, every key projected, and the value of every secret-named key
1897
+ replaced whole. The structure is walked before anything is serialised, which is what lets a key be
1898
+ recognised at all: once `json.dumps` has run, the floor sees `"password":"x"` and reads no key there.
1899
+ `masked` collects the key names whose values were replaced, so a caller can tell a walk that changed
1900
+ something from one that only re-projected what was already projected."""
1901
+ if depth > MAX_DEPTH:
1902
+ return project_text(serialise(value), home, depth, masked)
1903
+ if isinstance(value, str):
1904
+ return project_text(value, home, depth, masked)
1905
+ if isinstance(value, dict):
1906
+ out = {}
1907
+ for key, inner in value.items():
1908
+ # A KEY's own masking counts as a change too. It was projected with `masked` withheld - "a key's
1909
+ # own masking is not the member's" - so a decoded structure whose only secret stood in a key
1910
+ # looked unchanged to `embedded`, which handed the original encoded text back out. The member it
1911
+ # belongs to is still decided by `secret_key(key)` below; what is recorded here is only that the
1912
+ # projection changed something, which is the question the caller is asking.
1913
+ name = project_text(key, home, depth, masked) if isinstance(key, str) else key
1914
+ if secret_key(key):
1915
+ if masked is not None:
1916
+ masked.append(key)
1917
+ out[name] = FLOOR.PLACEHOLDER
1918
+ else:
1919
+ out[name] = walk(inner, home, depth + 1, masked)
1920
+ return out
1921
+ if isinstance(value, (list, tuple)):
1922
+ return [walk(item, home, depth + 1, masked) for item in value]
1923
+ return value
1924
+
1925
+
1926
+ def serialise(value):
1927
+ """The characters of a value: the string itself, or its compact JSON."""
1928
+ return value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, separators=(",", ":"))
1929
+
1930
+
1931
+ def project_r22(value, home=None):
1932
+ """The projection of one content block. A lone surrogate (JSON can carry one; UTF-8 cannot) becomes `?`,
1933
+ so the characters can be written and read back.
1934
+
1935
+ The walk projects each leaf, and then the SERIALISED result is verified: a claim can cross the boundary
1936
+ between two members that were each clean on their own, and the text a reader sees is this one."""
1937
+ text = serialise(walk(value, home)).encode("utf-8", "replace").decode("utf-8")
1938
+ return emit(text, text, home)
1939
+
1940
+
1941
+ # version -> projection. A new version is added here and CURRENT moves. A superseded version is removed
1942
+ # rather than kept: an old quote is made again from the source (§5.5), and a projection that under-redacts
1943
+ # must not stay callable by anything that happens to name it.
1944
+ VERSIONS = {"r22": project_r22}
1945
+
1946
+
1947
+ def project(value, version=CURRENT, home=None):
1948
+ """The characters one content block projects to. `home` names the home to mask instead of this process's,
1949
+ so a test can state the owner it means rather than depending on the account the run happens to use.
1950
+
1951
+ This is the content-block BOUNDARY, which is where a blanked block is counted. A structured block's
1952
+ leaves each pass through `emit`, so counting there counts operations rather than blocks - and a block
1953
+ with four masked leaves then read as four blanked blocks. Both figures are kept: `BLANKED` counts the
1954
+ operations, `BLOCKS` counts the blocks."""
1955
+ if version not in VERSIONS:
1956
+ raise KeyError(f"REDACTION_VERSION_MISMATCH {version!r}: no projection is registered under that version")
1957
+ _OPEN_BLOCK.append([])
1958
+ try:
1959
+ out = VERSIONS[version](value, home)
1960
+ finally:
1961
+ reasons = _OPEN_BLOCK.pop()
1962
+ if reasons and not _OPEN_BLOCK: # a nested call belongs to the block that opened, not to a new one
1963
+ BLOCKS[reasons[0]] += 1
1964
+ elif reasons:
1965
+ _OPEN_BLOCK[-1].extend(reasons)
1966
+ return out
1967
+
1968
+
1969
+
1970
+ # ---- the sweep ------------------------------------------------------------------------------------
1971
+
1972
+ # A run directory's own verification, and it reads the layer the projection wrote rather than the bytes of
1973
+ # the files holding it. The first sweep of this was a byte scan with one backslash of tolerance, and it
1974
+ # judged a different text from the one the projection judged: over the live run of 2026-10-21 it reported
1975
+ # 24 members where the decoded strings held 63, the thirteen worst of them scalars no structure story
1976
+ # explains. A verification that reads a different text than the thing it verifies cannot be its evidence.
1977
+ #
1978
+ # `inventory/` is swept for the same reason as the rest: S2's unit records carry the projection of every
1979
+ # carrier's fragments, the native layers among them, so the text a judge or the reconstruction author reads
1980
+ # is this layer and the sweep has to judge the same text (WP-07's record of 2026-10-22).
1981
+ #
1982
+ # `index/` is not scanned, and that is safe rather than convenient: a BM25 index's keys are the vocabulary
1983
+ # of already-projected text and its values are document numbers, so a posting named `token` means the word
1984
+ # occurred. Scanning it reported 2,794 members that were words. The sweep asserts that shape instead.
1985
+ # ---------------------------------------------------------------- a decoded document
1986
+
1987
+ DOCUMENT_SAFE_NAME = re.compile(r"^[A-Za-z][A-Za-z0-9_.-]{0,39}$")
1988
+
1989
+
1990
+ def document_members(document):
1991
+ """`[(key, value)]` of one decoded object, or None when the value is not one.
1992
+
1993
+ Two representations reach this module from outside: a plain `json.loads` result, whose objects are
1994
+ `dict`, and this module's own `Members`, which keeps duplicates and order. Both are objects, and a
1995
+ caller should not have to know which helper reads which."""
1996
+ if isinstance(document, Members):
1997
+ return [(key, item) for key, item in document]
1998
+ if isinstance(document, dict):
1999
+ return list(document.items())
2000
+ return None
2001
+
2002
+
2003
+ def as_members(value):
2004
+ """A decoded value in the representation this module's own walk uses: every object as `Members`.
2005
+
2006
+ `all_mask` reads an object as `Members` (that is how the structure walk hands it one) and answers
2007
+ "not the mask" for a plain `dict` whatever it holds. The conversion lives here, with the helper
2008
+ that needs it, rather than in every caller."""
2009
+ members = document_members(value)
2010
+ if members is not None:
2011
+ return Members([(key, as_members(item)) for key, item in members])
2012
+ if isinstance(value, (list, tuple)):
2013
+ return [as_members(item) for item in value]
2014
+ return value
2015
+
2016
+
2017
+ def document_location(parent, key, n, schema=()):
2018
+ """Where a member sits, named by a key the document's own schema declares or by its ordinal.
2019
+
2020
+ A key is untrusted text — a document can carry a credential AS a key, and `shortpass` is a
2021
+ perfectly ordinary word to find there. Syntax is not authority: the previous rule named any key
2022
+ that matched `DOCUMENT_SAFE_NAME` and that this floor had nothing to say about, which named the
2023
+ arbitrary nested key of `{"api_key": {"shortpass": {"token": "x"}}}` and repeated the secret in
2024
+ the refusal. So the name is used only when the code that owns the document declares it as a
2025
+ member name (`schema`), which is a set this floor is handed rather than one it infers.
2026
+
2027
+ A name missing from `schema` costs a readable location and nothing else — the member is reported
2028
+ by its ordinal — so the failure direction is toward saying less."""
2029
+ if isinstance(key, str) and key in schema and DOCUMENT_SAFE_NAME.match(key):
2030
+ return f"{parent}.{key}"
2031
+ return f"{parent}[key #{n}]"
2032
+
2033
+
2034
+ def document_disclosures(document, home=None, at="$", depth=0, schema=()):
2035
+ """Every place in a DECODED document that this floor objects to, as `location: what was found`.
2036
+
2037
+ This is the one entry point for "does this document disclose anything". It takes the document in
2038
+ either representation (plain `json.loads` output or `Members`) and converts internally, because
2039
+ the helpers underneath read different shapes: `all_mask` reads `Members`, `holds_secret` reads
2040
+ plain objects, and `discloses` reads a string. A caller that picked a helper per value had to
2041
+ know all three, and got one wrong in each direction — a masked nested member read as disclosed,
2042
+ and a credential-named member inside a plain object read as clean.
2043
+
2044
+ Three rules, every one of them this module's own:
2045
+
2046
+ * a credential-named member whose value is not the mask, for every member of every object at any
2047
+ depth, duplicates included;
2048
+ * a key that itself discloses something;
2049
+ * a string — value or key — that `discloses` still objects to, which covers a structure embedded
2050
+ in that string in any spelling it can reach.
2051
+
2052
+ A row names where it sits and which rule found it, never the value, never a path and never a
2053
+ hash of either. `schema` is the set of member names the code that owns the document declares;
2054
+ `document_location` names a key only when it is one of them, and reports every other key by its
2055
+ ordinal."""
2056
+ problems = []
2057
+ if depth > MAX_DEPTH:
2058
+ return [f"{at}: the document is nested deeper than this floor reads"]
2059
+ members = document_members(document)
2060
+ if members is not None:
2061
+ for n, (key, item) in enumerate(members):
2062
+ where = document_location(at, key, n, schema)
2063
+ if isinstance(key, str) and secret_key(key) and not all_mask(as_members(item)):
2064
+ problems.append(f"{where}: a credential-named member carries a value that is not the mask")
2065
+ if isinstance(key, str):
2066
+ found = discloses(key, home)
2067
+ if found is not None:
2068
+ problems.append(f"{where}: a key discloses a {found}")
2069
+ problems += document_disclosures(item, home, where, depth + 1, schema)
2070
+ return problems
2071
+ if isinstance(document, (list, tuple)):
2072
+ for n, item in enumerate(document):
2073
+ problems += document_disclosures(item, home, f"{at}[{n}]", depth + 1, schema)
2074
+ return problems
2075
+ if isinstance(document, str):
2076
+ found = discloses(document, home)
2077
+ if found is not None:
2078
+ problems.append(f"{at}: the string discloses a {found}")
2079
+ return problems
2080
+
2081
+
2082
+ WITHHELD = ("DIAGNOSTIC_WITHHELD: the message still disclosed something after projection, "
2083
+ "so it is not printed")
2084
+
2085
+
2086
+ def diagnostic(text, home=None, schema=()):
2087
+ """One line a command prints, as the floor permits it to be printed.
2088
+
2089
+ A diagnostic is an artifact: a person reads it and whatever captured the terminal stores it, so
2090
+ printing a line the write boundary would refuse is the same leak by another route. The line is
2091
+ projected and then asked the same question every written document is asked, through the same one
2092
+ entry point; a line that still discloses is replaced by the refusal rather than raised, because
2093
+ this runs ON the error path and a diagnostic that raises loses the diagnosis as well as the
2094
+ secret."""
2095
+ projected = project(str(text), CURRENT, home)
2096
+ return WITHHELD if document_disclosures(projected, home, schema=schema) else projected
2097
+
2098
+
2099
+ SWEPT = ("redacted", "views", "evidence", "inventory")
2100
+
2101
+
2102
+ _KEY_TAIL = re.compile(r'[\w.-]+\Z')
2103
+
2104
+
2105
+ def key_at(text, name_start, name):
2106
+ """The whole key a floor name ends, for the report: the name plus the run of key characters before it.
2107
+ `_KEYED` anchors on the name alone, so the name is all a match carries - and `token` tells a reader far
2108
+ less than `page_token` about where to look."""
2109
+ before = _KEY_TAIL.search(text[:name_start])
2110
+ return (before.group(0) if before else "") + name
2111
+
2112
+
2113
+ def already_masked(text, start):
2114
+ """Whether the value at `start` is already the placeholder. One recognition, used by the masker and by
2115
+ the sweep: when the two kept their own, the keyed rule wrote a repr's `\'<REDACTED>\'` and the sweep,
2116
+ which stripped only double quotes, reported the projection's own output as residual."""
2117
+ return text[start:].lstrip('\\"\'').startswith(FLOOR.PLACEHOLDER)
2118
+
2119
+
2120
+ def residual_in(text):
2121
+ """The key name of every member of `text` whose key the floor calls a secret and whose value the
2122
+ projection did not replace. The same `_KEYED` the projection masks with, so the two cannot drift: a hit
2123
+ is a key the projection should have masked and did not."""
2124
+ out = []
2125
+ for match in _KEYED.finditer(text):
2126
+ start = _COMMENT.match(text, match.end()).end()
2127
+ if already_masked(text, start):
2128
+ continue
2129
+ name = match.group(0).rstrip(" \t:=").rstrip('"\'').rstrip("\\")
2130
+ out.append(key_at(text, match.start(), name))
2131
+ return out
2132
+
2133
+
2134
+ def strings_of(value, depth=0):
2135
+ """Every string inside a parsed structure - the decoded layer, which is what a model receives."""
2136
+ if depth > MAX_DEPTH:
2137
+ return
2138
+ if isinstance(value, str):
2139
+ yield value
2140
+ elif isinstance(value, dict):
2141
+ for key, item in value.items():
2142
+ yield key
2143
+ yield from strings_of(item, depth + 1)
2144
+ elif isinstance(value, list):
2145
+ for item in value:
2146
+ yield from strings_of(item, depth + 1)
2147
+
2148
+
2149
+ class Unswept(Exception):
2150
+ """A subject the sweep could not judge. It is raised rather than skipped, because a sweep that skips what
2151
+ it cannot read reports zero for the files it never looked at - and a window file is pretty-printed, so
2152
+ reading every file line by line skipped every window in the run while printing a clean result."""
2153
+
2154
+
2155
+ def documents_in(path):
2156
+ """Every JSON document in one file: a `.json` file holds one, a `.jsonl` file one per line."""
2157
+ if path.suffix == ".jsonl":
2158
+ for number, raw in enumerate(records.jsonl_read(path, errors="replace"), 1):
2159
+ if not raw.strip():
2160
+ continue
2161
+ try:
2162
+ yield json.loads(raw)
2163
+ except ValueError as exc:
2164
+ raise Unswept(f"UNSWEPT_RECORD {path}:{number}: {exc}") from exc
2165
+ return
2166
+ try:
2167
+ yield json.loads(path.read_text(encoding="utf-8", errors="replace"))
2168
+ except ValueError as exc:
2169
+ raise Unswept(f"UNSWEPT_DOCUMENT {path}: {exc}") from exc
2170
+
2171
+
2172
+ def sweep(run_dir):
2173
+ """`(residual, masked, by_key, bad_index, index_files)` over one run directory.
2174
+
2175
+ Raises `Unswept` when a subject cannot be judged or when there is no subject at all: an empty set
2176
+ satisfies every "no secret survives" claim, and this is the artifact that claim rests on."""
2177
+ run_dir = pathlib.Path(run_dir)
2178
+ residual, masked, by_key, subjects = 0, 0, collections.Counter(), 0
2179
+ for directory in SWEPT:
2180
+ base = run_dir / directory
2181
+ if not base.is_dir():
2182
+ continue
2183
+ for path in sorted(base.rglob("*")):
2184
+ if not path.is_file():
2185
+ continue
2186
+ subjects += 1
2187
+ for document in documents_in(path):
2188
+ for text in strings_of(document):
2189
+ for name in residual_in(text):
2190
+ residual += 1
2191
+ by_key[name] += 1
2192
+ masked += text.count(FLOOR.PLACEHOLDER)
2193
+ if not subjects:
2194
+ raise Unswept(f"UNSWEPT_EMPTY {run_dir}: no file under {', '.join(SWEPT)} to judge")
2195
+ bad_index, index_files = 0, 0
2196
+ for path in sorted((run_dir / "index").rglob("*.json")) if (run_dir / "index").is_dir() else []:
2197
+ index_files += 1
2198
+ try:
2199
+ document = json.loads(path.read_text(encoding="utf-8"))
2200
+ except ValueError:
2201
+ bad_index += 1
2202
+ continue
2203
+ postings = document.get("postings") if isinstance(document, dict) else None
2204
+ if not isinstance(postings, dict) or any(
2205
+ not isinstance(v, list) or any(not isinstance(n, int) for n in v) for v in postings.values()):
2206
+ bad_index += 1
2207
+ return residual, masked, by_key, bad_index, index_files
2208
+
2209
+
2210
+ def report_sweep(run_dir):
2211
+ """Print the sweep's counts and key names - never a value - and return 1 if anything is residual, or if
2212
+ there was nothing to judge or something that could not be judged."""
2213
+ try:
2214
+ residual, masked, by_key, bad_index, index_files = sweep(run_dir)
2215
+ except Unswept as exc:
2216
+ print(f"projection --sweep {run_dir}: refused - {exc}")
2217
+ return 1
2218
+ print(f"projection --sweep {run_dir}: {residual} residual member(s) over the decoded strings")
2219
+ print(f" placeholders already standing in those strings (must not be zero): {masked}")
2220
+ print(f" index files whose postings hold anything but lists of document numbers: {bad_index} of {index_files}")
2221
+ if by_key:
2222
+ print(" residual by key name (names only, never a value):")
2223
+ for name, count in by_key.most_common():
2224
+ print(f" {count:5} {name}")
2225
+ return 1 if residual or bad_index else 0
2226
+
2227
+
2228
+ # The fixture owner of this suite. A real owner's home must not be written into a shipped file: the
2229
+ # masking rule is shape-based, so a fixture home exercises it exactly as the author's own would, and
2230
+ # the content-hygiene gate reads what ships rather than who wrote it.
2231
+ FX_OWNER_HOME = "/Users/fixture-owner"
2232
+
2233
+
2234
+ def self_test():
2235
+ # This suite prints its own report outside the shared boundary, so in stop-at-first-failure mode
2236
+ # its list prints the failure itself, in the report's own form, before the suite leaves.
2237
+ from runlib import entry
2238
+ failures = entry.self_test_failures("projection --self-test",
2239
+ publish=lambda failure: print(f"projection --self-test [FAIL] {failure}"))
2240
+ # a .jsonl record ends at "\n" only; JSON allows U+2028 and U+2029 raw inside a string
2241
+ with tempfile.TemporaryDirectory() as td:
2242
+ held = {"text": "before\u2028between\u2029after"}
2243
+ swept = pathlib.Path(td) / "r.jsonl"
2244
+ swept.write_text(json.dumps(held, ensure_ascii=False) + "\n", encoding="utf-8")
2245
+ try:
2246
+ got = list(documents_in(swept))
2247
+ except Unswept as exc:
2248
+ got = str(exc)
2249
+ if got != [held]:
2250
+ failures.append(f"jsonl-line-separators-inside-a-string-read-whole (documents_in): {got!r}")
2251
+ # a bare CR is JSON whitespace, which text-mode reading would turn into a line break; CRLF still ends a record
2252
+ later = {"text": "after a bare CR"}
2253
+ swept.write_bytes(("{\r" + json.dumps(held)[1:] + "\r\n" + json.dumps(later) + "\n").encode("utf-8"))
2254
+ try:
2255
+ got = list(documents_in(swept))
2256
+ except Unswept as exc:
2257
+ got = str(exc)
2258
+ if got != [held, later]:
2259
+ failures.append(f"jsonl-bare-cr-whitespace-and-crlf-read-whole (documents_in): {got!r}")
2260
+ # the home every control states, rather than the account this process happens to run under: the owner's own
2261
+ # home is masked wherever it stands, so a fixture that named a real one would answer differently per machine
2262
+ owner = "/Users/fixture-owner"
2263
+ token = "sk-ant-oat01-" + "Ab1_" * 12
2264
+ secrets = [("a subscription token", f"use {token} now", "sk-ant-oat"),
2265
+ ("an api key assignment", "api_key=live_0123456789abcdef", "live_0123456789abcdef"),
2266
+ ("a bearer header", "Authorization: Bearer abcdef0123456789xyz", "abcdef0123456789xyz"),
2267
+ ("an email", "ask alice.dev@example.com", "alice.dev@example.com"),
2268
+ ("a github token", "ghp_" + "a" * 24, "ghp_a")]
2269
+ paths = [("a macOS home path", "see /Users/alice/Documents/repo/file.py:12", "/Users/alice"),
2270
+ # M#2: a Windows home is the same directory in any capitalisation, and M#1: an encoded one is
2271
+ # masked while decoded, so the decoded form must be the one that is kept
2272
+ ("a mixed-case Windows home path", r"open c:\users\FixtureOwner\notes", "FixtureOwner"),
2273
+ ("a mixed-case Windows home path of another person", r"open D:\USERS\Carol\x", "Carol"),
2274
+ ("an encoded home path under an ordinary key",
2275
+ '{"path":"\\u002fUsers\\u002ffixtureowner\\u002fnotes"}', "fixtureowner"),
2276
+ ("a Linux home path", "cd /home/bob/work && ls", "/home/bob"),
2277
+ ("a Windows home path", r"open C:\Users\carol\proj\a.txt", r"C:\Users\carol"),
2278
+ ("a path in quotes", "path='/Users/alice/x y'", "/Users/alice"),
2279
+ ("the end of a sentence", "it lives in /Users/alice.", "/Users/alice")]
2280
+ kept = [("a shared directory", "/Users/Shared/agent-bios-cells/run1"), ("a system path", "/usr/local/bin/python3"),
2281
+ ("prose", "the secret sauce is verifying the real dispatch path"), ("a relative path", "src/Users/alice.py"),
2282
+ ("a home-relative path", "~/Documents/notes.md"), ("a word that starts like a home", "/Usersfoo/bar")]
2283
+ for label, text, needle in secrets + paths: # positive controls: each is masked, and the surrounding prose is not
2284
+ out = project(text, home=owner)
2285
+ if needle in out or not (FLOOR.PLACEHOLDER in out or HOME_MASK in out):
2286
+ failures.append(f"{label} was not masked: {out!r}")
2287
+ if project(out, home=owner) != out:
2288
+ failures.append(f"{label}: the projection is not idempotent: {out!r} -> {project(out, home=owner)!r}")
2289
+ for label, text in kept:
2290
+ if project(text, home=owner) != text:
2291
+ failures.append(f"{label} was changed: {text!r} -> {project(text, home=owner)!r}")
2292
+ if project("see /Users/alice/Documents/repo/file.py:12", home=owner) != f"see {HOME_MASK}/Documents/repo/file.py:12":
2293
+ failures.append("a home path did not keep the rest of the path after the mask")
2294
+ # The defect a review of 5ea5c3a found, in both halves. A structured value handed to the floor as text
2295
+ # kept its secrets, because a serialised object puts a closing quote between the key and the colon; and a
2296
+ # Windows home path lost its masking to the backslashes `json.dumps` doubles. Every shape below is a
2297
+ # fabricated value, and the structure is what the floor is given now - never its serialisation.
2298
+ structured = [
2299
+ ("a password key", {"password": "hunter2xyz0123"}, "hunter2xyz0123"),
2300
+ ("an api_key key", {"api_key": "abc123def4567890"}, "abc123def4567890"),
2301
+ ("a token key", {"token": "t0kenvalue1234567"}, "t0kenvalue1234567"),
2302
+ ("an Authorization header value", {"Authorization": "Bearer wire9876543210value"}, "wire9876543210value"),
2303
+ ("a secret nested two deep", {"outer": {"inner": {"secret": "nested12345678"}}}, "nested12345678"),
2304
+ ("a secret inside a list", {"calls": [{"n": 1}, {"token": "listed123456789"}]}, "listed123456789"),
2305
+ ("a non-string secret value", {"token": 12345678901234}, "12345678901234"),
2306
+ # only the walk can mask these: once serialised, a `"key":` followed by `{` or `[` is a shape no text
2307
+ # pattern reads as a value, so the structure is where the key has to be recognised
2308
+ ("a secret whose value is an object", {"token": {"value": "objected123456", "kind": "oauth"}}, "objected123456"),
2309
+ ("a secret whose value is a list", {"api_key": ["k1abcdef123456", "k2abcdef123456"]}, "k1abcdef123456"),
2310
+ ("a secret key under a projected key", {f"{owner}/cfg": {"password": "keyed12345678"}}, "keyed12345678"),
2311
+ ("a Windows home path a tool argument carries", {"cmd": r"type C:\Users\carol\notes.txt"}, r"C:\Users\carol"),
2312
+ ("a string that quotes serialised JSON", '{"password": "quoted12345678"}', "quoted12345678"),
2313
+ # the names the floor calls secrets end a key rather than begin it; reading them as prefixes left
2314
+ # 11,045 of these unmasked in the live run of 2026-10-21, every one a key the floor itself names
2315
+ ("a prefixed key in text", '{"openai_api_key": "sk-planted0123456789"}', "planted0123456789"),
2316
+ ("a prefixed header key in text", '{"user_authorization": "Bearer plantedwire12345"}', "plantedwire12345"),
2317
+ ("a hyphenated key in text", '{"x-api-key": "plantedkeyvalue123"}', "plantedkeyvalue123"),
2318
+ ("a prefixed token key in text", '{"page_token": "plantedpagetoken123"}', "plantedpagetoken123"),
2319
+ ("a prefixed key in a structure", {"google_client_secret": "plantedclientsecret"}, "plantedclientsecret"),
2320
+ # a string that is itself a serialised structure, at one and at two removes: the shape no key pattern
2321
+ # of ours reads, because its quotes arrive escaped. 3,117 members of the live run of 2026-10-21 were
2322
+ # of this shape after the pattern had been fixed twice, which is why it is closed by parsing instead
2323
+ ("a secret one serialisation deep", {"body": '{"password": "deep1planted12"}'}, "deep1planted12"),
2324
+ ("a secret two serialisations deep",
2325
+ {"body": json.dumps({"inner": json.dumps({"api_key": "deep2planted12"})})}, "deep2planted12"),
2326
+ ("a serialised structure as the whole block", '{"body": "{\\"token\\": \\"deep3planted12\\"}"}',
2327
+ "deep3planted12"),
2328
+ # a secret-named key whose value OPENS a structure, in a fragment of a document rather than a whole
2329
+ # one: both key patterns read a scalar, so these kept everything inside them (277 live members)
2330
+ ("an object-valued key in a document fragment",
2331
+ ' },\n "authorization": {\n "scheme": "bearer",\n "value": "frag1planted"\n },\n "next": 1',
2332
+ "frag1planted"),
2333
+ ("an array-valued key in a fragment", 'prefix "hadSecret": ["frag2planted"], "other": 2', "frag2planted"),
2334
+ ("a structured value mid-sentence", 'a fragment "page_token": {"a": "frag3planted"} and more', "frag3planted"),
2335
+ # the same member with its quotes escaped, in a fragment no parse can take whole
2336
+ ("an escaped scalar member in a fragment", 'tail\\", \\"client_secret\\": \\"frag4planted\\", \\"next\\": 1',
2337
+ "frag4planted"),
2338
+ # the last shape any sweep of the live run found: an escaped member whose value opens a structure,
2339
+ # which only the pass through one level of unescaping reaches
2340
+ ("an escaped structured value",
2341
+ 'tail\\", \\"root_password\\": {\\n \\"value\\": \\"frag5planted\\"\\n}, \\"next\\": 1', "frag5planted"),
2342
+ ("an escaped object under a prefixed key", '}, \\"nextPageToken\\": {\\"a\\": \\"frag6planted\\"}',
2343
+ "frag6planted"),
2344
+ # a structure a view clipped: its extent is absent rather than unknown, so the rest of the text goes
2345
+ ("a clipped structured value", 'a clipped fragment "password": {"value": "frag7planted', "frag7planted"),
2346
+ # the thirteen scalars of the live run of 2026-10-21, by the shape that hid each of them: the key's
2347
+ # own quote missing because the fragment began mid-string, a value the old length cap or character
2348
+ # class could not span, a key longer than the old prefix cap, and a notation that is not JSON
2349
+ ("a keyed scalar with no opening quote", 'password": "sc1planted", "next": 1', "sc1planted"),
2350
+ ("a value holding a quote", 'a line "password": "pre\\"sc2planted" and more', "sc2planted"),
2351
+ ("a value holding a backslash", 'a line "password": "C:\\\\xsc3planted" and more', "sc3planted"),
2352
+ ("a value longer than four thousand characters",
2353
+ 'a line "password": "' + "p" * 4200 + 'sc4planted" and more', "sc4planted"),
2354
+ ("a value holding an escape sequence", 'a line "password": "\\u0041sc5planted" and more', "sc5planted"),
2355
+ ("a repr's single-quoted value", 'a line "password": \'sc6planted\' and more', "sc6planted"),
2356
+ ("a value behind a comment", 'a line "password": /*x*/ "sc7planted"', "sc7planted"),
2357
+ ("a key longer than the old prefix cap", 'a "' + "z" * 70 + 'password": "sc8planted"', "sc8planted"),
2358
+ # M#0: the floor's own substitution is destructive, so a pass that needs the key must run before it
2359
+ ("a quoted bearer header the floor truncates", 'Authorization: "Bearer m0aplanted"', "m0aplanted"),
2360
+ # P#0: the floor's scheme pattern crosses whitespace of any kind, including a newline. A scan for a
2361
+ # bare value stops at the first space, so composing the two by substitution lost the credential
2362
+ # whichever order they ran in; the union of their spans loses neither.
2363
+ ("a multiline bearer header", "Authorization: Bearer\np0aplanted0123456789", "p0aplanted0123456789"),
2364
+ ("a header split by a tab run", "Authorization:\tBearer \t p0bplanted0123456789", "p0bplanted0123456789"),
2365
+ # P#1: a decoded structure whose only secret stands in a KEY
2366
+ ("an encoded home path as a dictionary key", '{"\\u002fUsers\\u002ffixture-owner\\u002fnotes":1}',
2367
+ "fixture-owner"),
2368
+ ("a repr's single-quoted key and value", "{'password': 'm0bplanted'}", "m0bplanted"),
2369
+ # M#1: the floor and the path masking change text no keyed pass touches, and a walk that recorded
2370
+ # only keyed maskings threw their work away with the decoded form
2371
+ ("an encoded token under an ordinary key",
2372
+ '{"note":"sk\\u002dant\\u002doat01\\u002dAb1_Ab1_Ab1_Ab1_Ab1_Ab1_"}', "Ab1_Ab1_"),
2373
+ ("a Windows home path already escaped in text", r"see C:\\Users\\carol\\x", r"Users\\carol"),
2374
+ ]
2375
+ for label, value, needle in structured:
2376
+ out = project(value, home=owner)
2377
+ if needle in out or FLOOR.PLACEHOLDER not in out and HOME_MASK not in out:
2378
+ failures.append(f"{label} survived the projection: {out!r}")
2379
+ if project(out, home=owner) != out:
2380
+ failures.append(f"{label}: the projection is not idempotent: {out!r} -> {project(out, home=owner)!r}")
2381
+ # the walk is not a blanket: a key the floor does not treat as a secret keeps its value, and so does prose
2382
+ structured_kept = [("an ordinary key", {"command": "ls -la"}, '{"command":"ls -la"}'),
2383
+ # the floor needs its separator straight after the name, so a key the name only STARTS
2384
+ # is not a secret: a usage counter must survive, or every transcript loses its numbers
2385
+ ("a usage counter in text", '{"input_tokens": 1234}', '{"input_tokens": 1234}'),
2386
+ ("a nested usage counter in text", '{"total_token_usage": {"input": 7}}',
2387
+ '{"total_token_usage": {"input": 7}}'),
2388
+ ("a plural of a secret name", {"tokens": 42}, '{"tokens":42}'),
2389
+ # a JSON document with no secret in it keeps its own formatting: the walked form
2390
+ # replaces the text only when something was actually masked
2391
+ ("a pretty-printed document with no secret", '{\n "pretty": 1,\n "input_tokens": 2\n}',
2392
+ '{\n "pretty": 1,\n "input_tokens": 2\n}'),
2393
+ ("a serialised structure with nothing to mask", '{"keep": "no secret here at all"}',
2394
+ '{"keep": "no secret here at all"}'),
2395
+ # a structure under a key the floor does not name, and a value that does not decode,
2396
+ # are both left alone: the extent is found by decoding, never guessed at
2397
+ # the key is not one the floor claims, and neither is any other word on the line:
2398
+ # the word `secret` in the old wording of this fixture IS such a word, and under the
2399
+ # keyed rule's line unit it named the structure that followed it
2400
+ ("a structured value under an ordinary key", 'not a canary "input_tokens": {"a": 1}',
2401
+ 'not a canary "input_tokens": {"a": 1}'),
2402
+ # a value that does not decode but DOES close is another notation, not a clipped
2403
+ # structure: a repr's own extent is its own, and the prose after it is not the secret's
2404
+ ("a repr that closes, with prose after it",
2405
+ 'a line "token": {\'a\': 1} and prose after it',
2406
+ 'a line "token": {\'a\': 1} and prose after it'),
2407
+ # escaped text is re-spelled only when a secret was masked in it: prose and a member
2408
+ # under an ordinary key keep their own escaping, byte for byte
2409
+ ("escaped text with nothing to mask", 'a\\", \\"input_tokens\\": {\\"a\\": 1}',
2410
+ 'a\\", \\"input_tokens\\": {\\"a\\": 1}'),
2411
+ ("escaped prose", 'he said \\"hello\\" and left', 'he said \\"hello\\" and left'),
2412
+ ("a quoted key with no value after it", 'the "token" column is an integer',
2413
+ 'the "token" column is an integer'),
2414
+ ("a lesson about tokens", "trust the X-Hook-Token header; the server derives identity from it",
2415
+ "trust the X-Hook-Token header; the server derives identity from it")]
2416
+ for label, value, want in structured_kept:
2417
+ if project(value, home=owner) != want:
2418
+ failures.append(f"{label} was changed: {project(value, home=owner)!r}, expected {want!r}")
2419
+ # the key names are the floor's own, and the probe that asks it is not matched by the floor on its own
2420
+ if FLOOR.redact(_PROBE) != _PROBE:
2421
+ failures.append("instrument control: the floor redacts the probe value itself, so secret_key answers yes to every key")
2422
+ if not all(secret_key(k) for k in ("password", "api_key", "API-KEY", "secret", "token", "authorization", "bearer")):
2423
+ failures.append("a key name the floor's own pattern lists was not read as the name of a secret")
2424
+ if not all(secret_key(k) for k in ("openai_api_key", "user_authorization", "x-api-key", "page_token")):
2425
+ failures.append("a key the name only ends was not read as the name of a secret, though the floor redacts it")
2426
+ if any(secret_key(k) for k in ("command", "path", "file", "prompt", "input_tokens", "total_token_usage", "", None)):
2427
+ failures.append("a key name the floor does not list was read as the name of a secret")
2428
+ # a key whose own name the floor already masked holds the placeholder before the floor is asked: the
2429
+ # question is whether the floor CHANGES `name=<value>`, not whether the answer carries the placeholder
2430
+ if any(secret_key(k) for k in (FLOOR.PLACEHOLDER, f"serviceAccount:{FLOOR.PLACEHOLDER}", f"user:{FLOOR.PLACEHOLDER}")):
2431
+ failures.append("a key whose name already carries the placeholder was read as the name of a secret")
2432
+ # the floor's shape is read, never assumed: a floor whose key-name group moved is a named failure
2433
+ kept_first = FLOOR.SECRET_RE[0]
2434
+ FLOOR.SECRET_RE[0] = re.compile(r"nothing-like-the-floor")
2435
+ try:
2436
+ floor_key_alternation()
2437
+ failures.append("a floor whose first pattern does not lead with its key-name group was read anyway")
2438
+ except FloorUnreadable as exc:
2439
+ if "REDACTION_FLOOR_UNREADABLE" not in str(exc):
2440
+ failures.append(f"an unreadable floor was refused unnamed: {exc}")
2441
+ finally:
2442
+ FLOOR.SECRET_RE[0] = kept_first
2443
+ # a transcript carries tool arguments as JSON, so a line break reaches the text as `\` and `n`: it is a
2444
+ # boundary, not a path segment (the live run of 2026-10-21, 8,536 owner paths left in the projection)
2445
+ for label, text in (("an escaped newline", r"cat out\n/Users/alice/x"), ("an escaped tab", r"a\t/Users/alice/x"),
2446
+ ("an escaped return", r"a\r/Users/alice/x")):
2447
+ if HOME_MASK not in project(text, home=owner):
2448
+ failures.append(f"{label} before a home path was read as a path segment: {project(text, home=owner)!r}")
2449
+ # the owner's own home is masked wherever it stands - prose, a relative prefix or an escape may abut it
2450
+ for label, text in (("prose with no separator", "표시된/Users/fixture-owner/notes.md"),
2451
+ ("a relative prefix", "../../../Users/fixture-owner/notes.md"),
2452
+ ("a diff prefix", "a/Users/fixture-owner/notes.md")):
2453
+ if owner in project(text, home=owner):
2454
+ failures.append(f"the owner's home survived {label}: {project(text, home=owner)!r}")
2455
+ if project("src/Users/alice.py", home=owner) != "src/Users/alice.py":
2456
+ failures.append("another person's relative path was masked because the owner's rule is unconditional")
2457
+ if project(token) == token or "oat" in project(token):
2458
+ failures.append("the subscription token prefix survived the projection")
2459
+ # this process's own home, when it is not under /Users or /home
2460
+ if mask_one("log at /srv/people/zed/work/a.log", home="/srv/people/zed") != f"log at {HOME_MASK}/work/a.log":
2461
+ failures.append("a home outside /Users and /home was not masked")
2462
+ if mask_one("/srv/people/zedder/a", home="/srv/people/zed") != "/srv/people/zedder/a":
2463
+ failures.append("a longer directory name that merely begins with the home was masked")
2464
+ # block text: a string is itself, any other value its compact JSON
2465
+ if project("x", home=owner) != "x" or project({"a": [1, "é"]}, home=owner) != '{"a":[1,"é"]}':
2466
+ failures.append("a block did not project to the string itself or to its compact JSON")
2467
+ if project(json.loads('"a\\ud83dz"'), home=owner) != "a?z":
2468
+ failures.append("a lone surrogate was not replaced, so the block could not be written as UTF-8")
2469
+ # a registered second version is a different projection, and an unknown one is named
2470
+ VERSIONS["rt"] = lambda value, home=None: project_r22(value, home).upper()
2471
+ try:
2472
+ if project("path /Users/alice/x", "rt", owner) == project("path /Users/alice/x", home=owner):
2473
+ failures.append("a second registered version did not project differently")
2474
+ finally:
2475
+ del VERSIONS["rt"]
2476
+ for gone in ("r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21"): # each superseded projection masks less: removed, not left callable
2477
+ try:
2478
+ project("x", gone)
2479
+ failures.append(f"version {gone} was projected although it is not registered")
2480
+ except KeyError as exc:
2481
+ if "REDACTION_VERSION_MISMATCH" not in str(exc):
2482
+ failures.append(f"version {gone} was refused unnamed: {exc}")
2483
+ try:
2484
+ project("x", "r99")
2485
+ failures.append("an unregistered version was projected")
2486
+ except KeyError as exc:
2487
+ if "REDACTION_VERSION_MISMATCH" not in str(exc):
2488
+ failures.append(f"an unregistered version was refused unnamed: {exc}")
2489
+ # ---- R#0: a floor match that crosses the structure's syntax, and the credential behind it -----
2490
+ #
2491
+ # The shape the finding names: the floor's greedy run eats the closing quote and the comma, so masking it
2492
+ # first leaves text that no longer parses and the member after it is never decoded. Decoding first reaches
2493
+ # both; the oracle then checks the raw claim, so neither can be traded for the other.
2494
+ mixed = [("a floor match across the syntax, with an encoded key after it",
2495
+ '{"note":"api_key=abc", "\\u0070assword":"r0planted-value"}', ["r0planted-value", "api_key=abc"]),
2496
+ ("... and with an encoded home path as the key after it",
2497
+ '{"note":"api_key=abc", "\\u002fUsers\\u002ffixture-owner\\u002fn":1}',
2498
+ ["fixture-owner", "api_key=abc"]),
2499
+ ("a multiline header inside a structure",
2500
+ '{"header":"Authorization: Bearer\\nr0opaque0123456789"}', ["r0opaque0123456789"]),
2501
+ ("an escaped structure holding both",
2502
+ '\\"api_key\\": \\"r0escaped-value\\", \\"path\\": \\"/Users/fixture-owner/x\\"',
2503
+ ["r0escaped-value", "fixture-owner"])]
2504
+ for label, text, planted in mixed:
2505
+ out = project_text(text, owner)
2506
+ standing = [needle for needle in planted if needle in out]
2507
+ if standing:
2508
+ failures.append(f"{label}: {standing} survived the projection: {out!r}")
2509
+ if floor_leftovers(text, owner):
2510
+ failures.append(f"{label}: the floor claims a credential the projection left: {out!r}")
2511
+ if project_text(out, owner) != out:
2512
+ failures.append(f"{label}: the projection is not idempotent: {out!r} -> {project_text(out, owner)!r}")
2513
+
2514
+ # ---- the shapes that used to need two paths, now in one ---------------------------------------
2515
+ #
2516
+ # There is no candidate and no fallback any more: one pass, one set of extents, in the original text's
2517
+ # own coordinates. These are the cases each of the four previous rounds was about, kept because each one
2518
+ # is a shape a reader can check, and because a rule nobody can see fail is not a rule.
2519
+ single_pass = [
2520
+ ("a floor claim spread across two members", '{"a":"sk-' + "A1b2" * 6
2521
+ + ' api_key=","b":"r0leftover-credential"}', ["r0leftover"]),
2522
+ ("an encoded scalar credential behind that claim", '{"a":"sk-' + "A1b2" * 6
2523
+ + ' api_key=","b":"v0left", "\\u0070assword":"v0encoded-secret-123"}',
2524
+ ["v0encoded-secret-123"]),
2525
+ ("an encoded home path behind that claim", '{"a":"sk-' + "A1b2" * 6
2526
+ + ' api_key=","b":"v0left", "\\u002fUsers\\u002ffixtureowner\\u002fx":1}', ["fixtureowner"]),
2527
+ # A#0: the keyed value is a quoted scalar that happens to contain a structure. Masking what was
2528
+ # found INSIDE it left the rest of the scalar standing, and a second projection then removed the
2529
+ # rest - two runs, two answers.
2530
+ ("a quoted keyed value holding a structure", 'prefix "password": "x{}a0abcd-credential"',
2531
+ ["a0abcd-credential"]),
2532
+ # A#1: a plain structure followed by an escaped member. The escaped region is read in its own
2533
+ # coordinates, so neither part excuses the other.
2534
+ ("a cross-member claim followed by an escaped member", '{"a":"sk-' + "A1b2" * 6
2535
+ + ' api_key=","b":"a1left"} \\"\\u0070assword\\": \\"a1gap-secret-123\\"',
2536
+ ["a1gap-secret-123"]),
2537
+ ("... and with an encoded home path in that escaped member", '{"a":"sk-' + "A1b2" * 6
2538
+ + ' api_key=","b":"a1left"} \\"path\\": \\"\\u002fUsers\\u002ffixtureowner\\u002fx\\"',
2539
+ ["fixtureowner"]),
2540
+ # E#0: the key's name stands in an unrelated value, which is not coverage of the encoded member
2541
+ ("an encoded key whose name appears in a sibling value",
2542
+ '{"note":"password","\\u0070assword":"e0opaqueCredential123"}', ["e0opaqueCredential123"]),
2543
+ ("... and with an ordinary value under an ordinary key beside it",
2544
+ '{"note":"password","keep":"ordinary","\\u0070assword":"e0sibling-credential"}',
2545
+ ["e0sibling-credential"]),
2546
+ ("... and with the key spelled plainly twice over",
2547
+ '{"password":"e0first-credential","\\u0070assword":"e0second-credential"}',
2548
+ ["e0first-credential", "e0second-credential"]),
2549
+ # E#1: two findings in one decoded region, at different depths
2550
+ ("a token needing one more decoding beside an already plain path",
2551
+ '\\"note\\":\\"sk\\\\u002de1abcdefghijklmnopq\\", '
2552
+ '\\"path\\":\\"\\u002fUsers\\u002ffixtureowner/x\\"',
2553
+ ["e1abcdefghijklmnopq", "fixtureowner"]),
2554
+ # E#2: a decodable body with no escaped quote in it at all
2555
+ ("an encoded credential in a body with no escaped quotes", 'sk\\u002de2abcdefghijklmnopq',
2556
+ ["e2abcdefghijklmnopq"]),
2557
+ ("an encoded home path in such a body", '\\u002fUsers\\u002ffixtureowner\\u002fnotes',
2558
+ ["fixtureowner"]),
2559
+ ("an encoded credential in the tail after a plain structure",
2560
+ '{"note":"plain"} sk\\u002de2tail-abcdefghij', ["e2tail-abcdefghij"]),
2561
+ ("an escaped structure inside a tool argument",
2562
+ '{\\"command\\": \\"curl -H \\\\\\"authorization: Bearer a2abcdef0123456789\\\\\\"\\"}',
2563
+ ["a2abcdef0123456789"]),
2564
+ ]
2565
+ # E#3: the delimiters survive, the document still parses, and a second projection is the first
2566
+ syntax_cases = [
2567
+ ("a floor match inside a secret-named value", '{"password":"abc token=e3def-credential"}'),
2568
+ ("a floor match across two members",
2569
+ '{"a":"sk-' + "A1b2" * 6 + ' api_key=","b":"e3cross-credential"}'),
2570
+ ("a floor match in a nested structure",
2571
+ '{"outer":{"a":"sk-' + "A1b2" * 6 + ' api_key=","b":"e3nested"},"keep":"plain"}'),
2572
+ ("a floor match at the very end of a value", '{"token":"e3end token=e3tail-credential"}'),
2573
+ # R#5: the serialised scalar shapes, and a block the backstop really takes
2574
+ ("a numeric value under a secret-named key", '{"password":1234567890}'),
2575
+ ("a boolean value under a secret-named key", '{"password":true}'),
2576
+ ("a null value under a secret-named key", '{"password":null,"keep":"plain words"}'),
2577
+ ("duplicate secret-named members", '{"password":"r5first-value","password":"r5second-value"}'),
2578
+ # a VALID JSON document the backstop takes: the credential is six escape layers down, which the
2579
+ # mapping does not locate and the verifier's lenient reading does
2580
+ ]
2581
+ # S#4: the one fixture that must ACTIVATE the backstop, kept apart from the syntax cases because what is
2582
+ # asserted of it is different: the named detector, a counter that moved by one, and an output equal to
2583
+ # the JSON string `"<REDACTED>"` written out here rather than asked of `blank_for`.
2584
+ must_blank = json.dumps({"note": "sk" + "\\\\u005c" * 6 + "u002ds4blankedabcdefghijklmn"},
2585
+ ensure_ascii=False)
2586
+ floor_before = BLANKED["floor"]
2587
+ blanked_out = project_text(must_blank, owner)
2588
+ if BLANKED["floor"] - floor_before != 1:
2589
+ failures.append("the fixture that must activate the backstop did not blank by the floor detector "
2590
+ f"exactly once: {blanked_out[:60]!r}")
2591
+ if blanked_out != '"<REDACTED>"':
2592
+ failures.append(f"a blanked JSON block is not the JSON string \"<REDACTED>\": {blanked_out!r}")
2593
+ if json.loads(blanked_out) != FLOOR.PLACEHOLDER:
2594
+ failures.append(f"the blanked block does not read back as the mask: {blanked_out!r}")
2595
+ if project_text(blanked_out, owner) != blanked_out:
2596
+ failures.append(f"a blanked block is not a fixed point: {blanked_out!r}")
2597
+ # R#5: every one of these is parsed by `json.loads` here, and the blanked form is written out as the
2598
+ # literal `"<REDACTED>"` rather than asked of `blank_for` - a control that calls the producer's own
2599
+ # helper agrees with it by construction, including when both are wrong.
2600
+ for label, text in syntax_cases:
2601
+ out = project_text(text, owner)
2602
+ try:
2603
+ json.loads(out)
2604
+ except ValueError as exc:
2605
+ failures.append(f"{label}: the projection no longer parses as JSON: {out!r} ({exc})")
2606
+ again = project_text(out, owner)
2607
+ if again != out:
2608
+ failures.append(f"{label}: the second projection differs from the first: {out!r} -> {again!r}")
2609
+ if discloses(out, owner):
2610
+ failures.append(f"{label}: the verifier still finds {discloses(out, owner)} in {out!r}")
2611
+ if out.strip().startswith('"') and out != f'"{FLOOR.PLACEHOLDER}"' and json.loads(out) != text:
2612
+ failures.append(f"{label}: a blanked JSON block is not the JSON mask: {out!r}")
2613
+
2614
+ # Each mapping fix gets a control of its own, because the verifier would otherwise hide all of them:
2615
+ # with the backstop in place a mapping mistake blanks the block, the credential is gone either way, and
2616
+ # every absence control stays green. What tells the two apart is PRECISION - these shapes must be masked
2617
+ # in place, with the block surviving - so reverting a mapping fix fails here by name instead of silently
2618
+ # falling through to the blanket.
2619
+ precise = [
2620
+ ("E#0: an encoded key whose name stands in a sibling value",
2621
+ '{"note":"password","\\u0070assword":"e0precise-credential"}'),
2622
+ ("E#1: a twice-encoded token beside an already plain path in one region",
2623
+ '\\"note\\":\\"sk\\\\u002de1precise-abcdefghij\\", '
2624
+ '\\"path\\":\\"\\u002fUsers\\u002ffixtureowner/x\\"'),
2625
+ # surrounded by ordinary words, so masking in place is distinguishable from blanking the block
2626
+ ("E#2: a decodable body carrying no escaped quote",
2627
+ 'see sk\\u002de2precise-abcdefghij here'),
2628
+ ("E#2: an encoded home path in such a body",
2629
+ 'see \\u002fUsers\\u002ffixtureowner\\u002fnotes here'),
2630
+ ("E#3: a floor match inside a secret-named value",
2631
+ '{"password":"abc token=e3precise-credential"}'),
2632
+ ]
2633
+ for label, text in precise:
2634
+ blanked_before = sum(count for key, count in STATS.items() if key.startswith("blanked:"))
2635
+ out = project_text(text, owner)
2636
+ blanked = sum(count for key, count in STATS.items() if key.startswith("blanked:")) - blanked_before
2637
+ if blanked:
2638
+ failures.append(f"{label}: the mapping missed it and the verifier blanked the whole block, so "
2639
+ f"the masking this case is about is not happening: {out!r}")
2640
+ if out == FLOOR.PLACEHOLDER:
2641
+ failures.append(f"{label}: the whole block was replaced, so nothing proves the extent was found")
2642
+ # ---- M#6 and M#0: the backstop fires, by exactly the detector and exactly once ---------------
2643
+ #
2644
+ # The previous control required three things at once and so passed whenever none of them held - it was
2645
+ # green with the verifier removed. These require the counter to MOVE, by the named detector, by one.
2646
+ # The clean counterpart comes first: an input the mapping covers must NOT blank, or the figures below
2647
+ # would be satisfied by a projection that blanks everything.
2648
+ def blanked_by(text, home=owner):
2649
+ """`(reason, out)` - which detector blanked this block, and what it became."""
2650
+ before = collections.Counter({key: value for key, value in BLANKED.items()})
2651
+ out = project_text(text, home)
2652
+ moved = [key for key in BLANKED if BLANKED[key] - before[key] == 1]
2653
+ extra = [key for key in BLANKED if BLANKED[key] - before[key] > 1]
2654
+ if extra:
2655
+ failures.append(f"one block raised {extra} by more than one, so the counts are not per block")
2656
+ return (moved[0] if moved else None), out
2657
+
2658
+ def nested_layers(count, secret="sk-m0deepAbCdEfGhIjKlMn"):
2659
+ """A credential wrapped in `count` JSON documents, each inside the previous one's string."""
2660
+ value = secret
2661
+ for _level in range(count):
2662
+ value = json.dumps({"carrier": value}, ensure_ascii=False)
2663
+ return value
2664
+
2665
+ reason, out = blanked_by('{"note":"ordinary text","password":"m6clean-value"}')
2666
+ if reason is not None:
2667
+ failures.append(f"a block the mapping covers was blanked by {reason!r}: {out!r}")
2668
+
2669
+ # The depth limit is asked of the verifier directly, not through a projected block. Nothing the
2670
+ # projection emits can reach it: `holds_secret` fails closed past MAX_EMBEDDED, so a deeply wrapped
2671
+ # credential is already masked by the mapping and the output the verifier sees is clean. The limit is
2672
+ # still the rule that decides what an unfinished traversal means, so it is held where it lives - and the
2673
+ # shallower counterpart must NOT read as a limit, or the detector would be answering by depth alone.
2674
+ # At the limit with something still to decode, the traversal reports a limit rather than a clean list.
2675
+ # Asked of the traversal at its own boundary, because no constructed block reaches it from outside: the
2676
+ # lenient reading collapses any number of escape layers in one step, and JSON nesting escapes its own
2677
+ # quotes, so that reading shortcuts the nesting too. Both halves are asserted - at the boundary it
2678
+ # reports the limit, and one step below it reports the detector - or a rule that always says "limit"
2679
+ # would pass.
2680
+ at_limit = every_spelling(nested_layers(3), VERIFY_DEPTH)[1]
2681
+ if not at_limit.exhausted:
2682
+ failures.append("the traversal stopped at its depth limit with layers left to decode and did not "
2683
+ "report it, so an output it never finished reading would read as clean")
2684
+ inside_limit = every_spelling(nested_layers(3), VERIFY_DEPTH - 3)[1]
2685
+ if inside_limit.exhausted:
2686
+ failures.append("the traversal reported a limit although it had the depth to finish")
2687
+ thrifty = Reach()
2688
+ thrifty.budget = 2
2689
+ if not every_spelling(nested_layers(4), 0, thrifty)[1].exhausted:
2690
+ failures.append("the traversal spent its budget and did not report it")
2691
+ if discloses(nested_layers(2), owner) != "floor":
2692
+ failures.append("a credential two layers down was reported as "
2693
+ f"{discloses(nested_layers(2), owner)!r} rather than by the detector that finds it")
2694
+ if discloses(FLOOR.PLACEHOLDER, owner) is not None:
2695
+ failures.append("the verifier reports a finding in the mask itself, so every block would blank")
2696
+
2697
+ # ---- R#0 and R#1: the verifier's own rules, on the shapes the mapping cannot see ------------
2698
+ #
2699
+ # Clean counterpart first in each pair: a block the mapping covers must NOT blank, or a verifier that
2700
+ # blanks everything would satisfy the rest.
2701
+ member_cases = [
2702
+ ("a duplicate secret-named member behind a masked one",
2703
+ '{"password":"' + FLOOR.PLACEHOLDER + '","password":"r0dup-credential-456"}', True),
2704
+ ("a secret-named key with a newline before its colon",
2705
+ '{"safe":{"password":"' + FLOOR.PLACEHOLDER + '"},"password"\n:"r0newline-credential"}', True),
2706
+ ("a secret-named key with spaces around its colon",
2707
+ '{ "password" : "r0spaced-credential" }', True),
2708
+ ("a secret-named member nested under an ordinary one",
2709
+ '{"outer":{"inner":{"password":"r0nested-credential"}}}', True),
2710
+ ("a secret-named member whose value is a structure of leaves",
2711
+ '{"password":{"a":"r0leaf-one","b":["r0leaf-two"]}}', True),
2712
+ # ... and the absent value, which discloses nothing: the mapping may still mask it, but the block
2713
+ # must stay readable rather than being blanked whole
2714
+ ("a secret-named key with no value at all", '{"password":null,"other":"plain words"}', None),
2715
+ ("a secret-named key with an empty value", '{"password":"","other":"plain words"}', None),
2716
+ ]
2717
+ for label, text, must_mask in member_cases:
2718
+ out = project_text(text, owner)
2719
+ if must_mask and out == text:
2720
+ failures.append(f"{label}: the projection left the block untouched: {out!r}")
2721
+ if must_mask is None:
2722
+ if "plain words" not in out:
2723
+ failures.append(f"{label}: a block with nothing to disclose was blanked whole: {out!r}")
2724
+ if not parses_as_json(out):
2725
+ failures.append(f"{label}: a JSON block stopped parsing: {out!r}")
2726
+ if discloses(out, owner):
2727
+ failures.append(f"{label}: the verifier still finds {discloses(out, owner)!r} in {out!r}")
2728
+ if project_text(out, owner) != out:
2729
+ failures.append(f"{label}: not idempotent: {out!r} -> {project_text(out, owner)!r}")
2730
+ # the verifier reads the SHAPES directly too, so the rule is held where it lives
2731
+ for label, text, expected in (
2732
+ ("a duplicate secret-named member whose MASKED copy comes last - the one a reader that keeps "
2733
+ "only the last value cannot see",
2734
+ '{"password":"r0direct-credential","password":"' + FLOOR.PLACEHOLDER + '"}', "secret-named key"),
2735
+ ("a duplicate secret-named member whose masked copy comes first",
2736
+ '{"password":"' + FLOOR.PLACEHOLDER + '","password":"r0direct-second"}', "secret-named key"),
2737
+ ("a secret-named member nested two objects down",
2738
+ '{"outer":{"inner":{"password":"r0direct-nested"}}}', "secret-named key"),
2739
+ ("a secret-named member whose value is a structure with an unmasked leaf",
2740
+ '{"password":{"a":"' + FLOOR.PLACEHOLDER + '","b":["r0direct-leaf"]}}', "secret-named key"),
2741
+ ("a secret-named member whose value is a structure of masks only",
2742
+ '{"password":{"a":"' + FLOOR.PLACEHOLDER + '","b":["' + FLOOR.PLACEHOLDER + '"]}}', None),
2743
+ ("a newline before the colon",
2744
+ '{"password"\n:"r0direct-newline"}', "secret-named key"),
2745
+ ("a masked member and nothing else",
2746
+ '{"password":"' + FLOOR.PLACEHOLDER + '"}', None),
2747
+ ("an escape layer that starts and cannot be read", "ordinary text ending in a backslash\\",
2748
+ "verifier-limit"),
2749
+ ("a Windows path, whose characters the lenient reading does reach", "see C:\\temp\\notes.txt",
2750
+ None),
2751
+ # S#0: a readable keyed fragment in mixed text - no JSON object to read it as a member, no floor
2752
+ # match, no home path. The old verifier saw the decoded key as a bare word and nothing else.
2753
+ ("a keyed fragment in mixed text",
2754
+ '{"note":"plain"} "\\u0070assword":"s0canarycredential"', "keyed fragment"),
2755
+ ("the same fragment already masked",
2756
+ '{"note":"plain"} "password":"' + FLOOR.PLACEHOLDER + '"', None),
2757
+ ("a keyed fragment with the separator a few characters away",
2758
+ 'the setting token \\" = \\" s0spacedcredential', "keyed fragment"),
2759
+ ("a keyed fragment whose name the floor does not claim", 'colour = s0ordinaryvalue', None),
2760
+ # V#0: a readable structured value in a fragment keeps its key association, and every leaf of
2761
+ # it is held against the mask. Exempting it on the opening bracket alone let a complete array
2762
+ # carry an ordinary string.
2763
+ ("a readable array under an encoded key",
2764
+ '{"note":"plain"} "\\u0070assword":["v0structure_canary"]', "keyed fragment"),
2765
+ ("a readable object under an encoded key",
2766
+ '{"note":"plain"} "\\u0070assword":{"inner":"v0object_canary"}', "keyed fragment"),
2767
+ ("... while an array of masks only is exempt",
2768
+ '{"note":"plain"} "\\u0070assword":["<REDACTED>","<REDACTED>"]', None),
2769
+ ("... and a structure whose extent cannot be read is the owner-pending class, untouched",
2770
+ '{"note":"plain"} "\\u0070assword":{truncated', None),
2771
+ # V#1: what follows a scalar is not the scalar's, and nothing is stripped from inside one
2772
+ ("a suffix after a masked scalar",
2773
+ '{"note":"plain"} "\\u0070assword":"<REDACTED>"v1suffix_canary', "keyed fragment"),
2774
+ ("a quoted scalar holding only punctuation",
2775
+ '{"note":"plain"} "\\u0070assword":";"', "keyed fragment"),
2776
+ ("... while a masked scalar followed by packaging is exempt",
2777
+ '{"note":"plain"} "\\u0070assword":"<REDACTED>" ,', None),
2778
+ # V#2: a quoted key whose separator stands on the next line
2779
+ ("a quoted key with a newline before its separator",
2780
+ '{"note":"plain"} "password"\n: "v2line_canary"', "keyed fragment"),
2781
+ ("an encoded key with a newline before its separator",
2782
+ '{"note":"plain"} "\\u0070assword"\n= "v2encoded_canary"', "keyed fragment"),
2783
+ ("... while the same association already masked is exempt",
2784
+ '{"note":"plain"} "password"\n: "<REDACTED>"', None),
2785
+ # T#0: a long name token, which a cap split into two words the floor claims neither of
2786
+ ("a secret-named key behind 38 characters of name",
2787
+ '{"note":"plain"} "' + "x" * 38 + '\\u0070assword":"t0canarycredential"', "keyed fragment"),
2788
+ # T#1: a value that merely STARTS with the mask still holds what follows it
2789
+ ("a keyed value that starts with the mask and goes on",
2790
+ '{"note":"plain"} "\\u0070assword":"' + FLOOR.PLACEHOLDER + ' t1survivingcanary"',
2791
+ "keyed fragment"),
2792
+ ("... while the value that IS the mask is exempt",
2793
+ '{"note":"plain"} "password":"' + FLOOR.PLACEHOLDER + '"', None),
2794
+ ("a keyed value that ends with the mask",
2795
+ '{"note":"plain"} "\\u0070assword":"t1leading ' + FLOOR.PLACEHOLDER + '"', "keyed fragment"),
2796
+ # T#2: a backslash before a real newline - a run the lenient reading cannot cross
2797
+ ("a backslash before an actual newline, beside a structure that decodes",
2798
+ '{"note":"plain"} \\\nordinary', "verifier-limit"),
2799
+ ("a backslash before a carriage return", '{"note":"plain"} \\\rordinary', "verifier-limit"),
2800
+ ("an escaped newline, which IS a valid escape", '{"note":"plain"} \\n ordinary', None),
2801
+ # S#1: the unfinished run is reported although the block also holds a structure that decodes
2802
+ ("an unfinished escape run beside a structure that decodes", '{"note":"plain"} \\',
2803
+ "verifier-limit"),
2804
+ ("a truncated \\u sequence beside a structure that decodes", '{"note":"plain"} \\u00',
2805
+ "verifier-limit")):
2806
+ if discloses(text, owner) != expected:
2807
+ failures.append(f"the verifier reads {label} as {discloses(text, owner)!r}, not {expected!r}")
2808
+
2809
+ backstop_cases = [
2810
+ # ... and seven layers, which is inside the limit but outside the projection's own mapping
2811
+ ("seven decode layers in a mixed-prose tail",
2812
+ '{"note":"plain"} sk' + "\\\\u005c" * 6 + "u002dm0sevenabcdefghij", ("floor", "verifier-limit")),
2813
+ # more distinct strings than the traversal's budget allows: the same reasoning as the depth limit
2814
+ ("beyond the verifier's budget",
2815
+ json.dumps({f"k{index}": f"v{index}" for index in range(VERIFY_BUDGET + 50)}, ensure_ascii=False),
2816
+ ("verifier-limit",)),
2817
+ ]
2818
+ for label, text, allowed in backstop_cases:
2819
+ reason, out = blanked_by(text)
2820
+ if reason is None:
2821
+ failures.append(f"{label}: no block was blanked, so the backstop did not fire on the one input "
2822
+ f"this case is about: {out[:60]!r}")
2823
+ elif reason not in allowed:
2824
+ failures.append(f"{label}: the backstop blanked for {reason!r}, not one of {allowed}")
2825
+ if reason is not None and out != blank_for(text):
2826
+ failures.append(f"{label}: a blanked block is not the mask: {out[:60]!r}")
2827
+ if project_text(out, owner) != out:
2828
+ failures.append(f"{label}: a blanked block is not idempotent: {out[:60]!r}")
2829
+
2830
+ for label, text, planted in single_pass:
2831
+ out = project_text(text, "/Users/fixtureowner")
2832
+ standing = [needle for needle in planted if needle in out]
2833
+ if standing:
2834
+ failures.append(f"{label}: {standing} survived the projection: {out!r}")
2835
+ if readable_survivors(text, out):
2836
+ failures.append(f"{label}: an obligation of the original still reads in the projection: {out!r}")
2837
+ if project_text(out, "/Users/fixtureowner") != out:
2838
+ failures.append(f"{label}: the projection is not idempotent: {out!r} -> "
2839
+ f"{project_text(out, '/Users/fixtureowner')!r}")
2840
+ # ... and a block whose secrets are all reachable keeps its own text everywhere else: masking extents
2841
+ # means a document a person reads is not re-serialised for the sake of one member
2842
+ in_place = project_text('{"note": "ordinary text", "password": "r0kept-value"}', owner)
2843
+ if in_place != '{"note": "ordinary text", "password": "<REDACTED>"}':
2844
+ failures.append(f"a block was re-serialised rather than masked in place: {in_place!r}")
2845
+
2846
+ # ---- R#4: the oracle itself, before it is used to judge anything -----------------------------
2847
+ #
2848
+ # A differential is only as good as its question. The previous one asked whether an entire floor MATCH
2849
+ # still stood in the output, which the original defect passes: drop `Authorization: Bearer` and keep the
2850
+ # credential, and the whole match is gone. So the oracle is proven first - on a deliberately partial
2851
+ # mask - and then used.
2852
+ partial_cases = [
2853
+ ("a credential with its middle removed", "Authorization: Bearer abcdefgh01234567ijklmnop",
2854
+ "Authorization: Bearer abcdefgh<REDACTED>ijklmnop"),
2855
+ ("the P#0 shape: the header masked and the credential left",
2856
+ "Authorization: Bearer\nopaque0123456789abcdef", "<REDACTED>\nopaque0123456789abcdef"),
2857
+ ("a token with one character changed", "sk-" + "b" * 20, "sk-" + "b" * 19 + "c"),
2858
+ ("an email with its domain masked", "write to alice.developer@example.com",
2859
+ "write to alice.developer@<REDACTED>"),
2860
+ ]
2861
+ for label, raw, planted in partial_cases:
2862
+ if not floor_survivors(raw, planted):
2863
+ failures.append(f"the oracle accepted a deliberately partial mask ({label}): {planted!r}")
2864
+ for label, raw, _planted in partial_cases:
2865
+ if floor_survivors(raw, FLOOR.PLACEHOLDER):
2866
+ failures.append(f"the oracle reports a survivor in a wholly masked output ({label})")
2867
+ unit = [("a credential shorter than the unit is asked about whole", survives("short", "a short word"), True),
2868
+ ("... and is not found when it is absent", survives("short", "a long word"), False),
2869
+ ("eight characters of a credential standing together is a survival",
2870
+ survives("abcdefghij", "x abcdefgh y"), True),
2871
+ ("seven are not", survives("abcdefghij", "x abcdefg y"), False)]
2872
+ for label, got, want in unit:
2873
+ if got is not want:
2874
+ failures.append(f"the oracle's unit of survival is wrong: {label} gave {got}")
2875
+
2876
+ # the oracle asks about the CREDENTIAL, not about the key that named it: the keyed rule keeps that key on
2877
+ # purpose, so asking about the whole match would report a survivor wherever the key is kept, and a
2878
+ # control reading that report would call a correct projection a leak. No corpus string tells the two
2879
+ # apart today - wherever the floor matches, its own span masks the key too - so the contract is asserted
2880
+ # directly.
2881
+ keyed_cases = [("a header with a scheme", "Authorization: Bearer abcdefgh01234567", "abcdefgh01234567"),
2882
+ ("a header split by a newline", "Authorization: Bearer\nopaque0123456789", "opaque0123456789"),
2883
+ ("an assignment with no scheme", "api_key=live_0123456789abcdef", "live_0123456789abcdef")]
2884
+ for label, text, credential in keyed_cases:
2885
+ found = [secret_part(m) for pattern in floor_patterns() for m in pattern.finditer(text)
2886
+ if pattern.groups and m.group(1) is not None]
2887
+ if found[:1] != [credential]:
2888
+ failures.append(f"the oracle reads the wrong part of {label} as the credential: {found}")
2889
+ plain = [secret_part(m) for m in floor_patterns()[1].finditer("use sk-" + "A1b2" * 6 + " now")]
2890
+ if plain != ["sk-" + "A1b2" * 6]:
2891
+ failures.append(f"the oracle reads a pattern with no key as something other than its whole match: {plain}")
2892
+
2893
+ # ... and every pattern the floor carries has a positive case in this corpus. A pattern with no case is
2894
+ # a pattern this self-test says nothing about, so it fails by name rather than passing quietly.
2895
+ pattern_cases = {
2896
+ "the keyed header or assignment": "Authorization: Bearer abcdefgh01234567ijklmnop",
2897
+ "an sk- token": "use sk-" + "A1b2" * 6 + " now",
2898
+ "a GitHub token": "ghp_" + "C3d4" * 6,
2899
+ "a JWT": "eyJ" + "E5f6" * 6 + ".rest",
2900
+ "an AWS key id": "AKIA" + "G7H8I9J0K1L2",
2901
+ "an email": "write to alice.developer@example.com",
2902
+ }
2903
+ uncovered = [pattern.pattern[:40] for pattern in floor_patterns()
2904
+ if not any(pattern.search(text) for text in pattern_cases.values())]
2905
+ if uncovered:
2906
+ failures.append(f"{len(uncovered)} floor pattern(s) have no positive case in this self-test: {uncovered}")
2907
+ for label, text in pattern_cases.items():
2908
+ if floor_leftovers(text, owner):
2909
+ failures.append(f"{label} survives the projection: {text!r} -> {project_text(text, owner)!r}")
2910
+ if project_text(text, owner) == text:
2911
+ failures.append(f"{label} was not masked at all: {text!r}")
2912
+
2913
+ # The two ways the floor can stop being readable. Neither can be reached by any input, so each is reached
2914
+ # by replacing what the module reads - and both must fail BY NAME, because a floor whose patterns cannot
2915
+ # be read is a projection that would otherwise mask less than the floor and say nothing.
2916
+ kept_patterns = FLOOR.SECRET_RE
2917
+ try:
2918
+ for label, planted in (("SECRET_RE is not a list", "sk-"), ("SECRET_RE is empty", []),
2919
+ ("a member is not a compiled pattern", [kept_patterns[0], r"sk-\d+"])):
2920
+ FLOOR.SECRET_RE = planted
2921
+ try:
2922
+ project_text("Authorization: Bearer abc0123456789xyz", owner)
2923
+ failures.append(f"a floor whose {label} was read as if it were usable")
2924
+ except FloorUnreadable as exc:
2925
+ if "REDACTION_FLOOR_UNREADABLE" not in str(exc):
2926
+ failures.append(f"a floor whose {label} failed unnamed: {exc}")
2927
+ finally:
2928
+ FLOOR.SECRET_RE = kept_patterns
2929
+ if floor_patterns() is not kept_patterns:
2930
+ failures.append("the floor's patterns were not restored after the planted failures")
2931
+
2932
+ # ---- M#1: the choke point, held structurally rather than remembered --------------------------
2933
+ #
2934
+ # Every block this module returns must leave through `emit`, because `emit` is where the backstop runs.
2935
+ # A call added at each site is a rule someone forgets at the next site - which is exactly what happened:
2936
+ # the structured path serialised its walk and returned it unverified. So the question is asked of the
2937
+ # SOURCE: in each block-producing function, every `return` is a call to `emit`.
2938
+ import ast as _ast
2939
+ module = _ast.parse(pathlib.Path(__file__).read_text(encoding="utf-8"))
2940
+
2941
+ # ---- R#0 / U#4: the verifier is independent of the mapping, as one callable ------------------
2942
+ #
2943
+ # The backstop exists to catch the mapping's mistakes. Any reading of the mapping's own state makes it
2944
+ # blind exactly where the mapping is blind, which is what let a duplicate member through. The check is
2945
+ # ONE function returning named violations, so the same code can be run on this module and on an AST with
2946
+ # a dependency planted below an entry point - the second run is what proves the first one looks.
2947
+ verifier_entry = {"vf_unescape", "vf_load", "vf_structures", "vf_members", "vf_keyed", "vf_exempt",
2948
+ "vf_scalar", "vf_region", "vf_unfinished", "all_mask", "every_spelling", "discloses",
2949
+ "spellings_of"}
2950
+ detectors = {"floor_patterns", "home_patterns", "secret_key", "is_mask", "floor_key_alternation",
2951
+ "secret_part", "note_change", "blank_for", "parses_as_json"}
2952
+ mapping = {"mask_extents", "decoded_extents", "floor_spans", "floor_spans_normalised", "keyed_spans",
2953
+ "path_spans", "literal_ranges", "within_literals", "visible_secret_keys",
2954
+ "encoded_secret_keys", "escaped_regions", "escape_map", "structures_in", "relaxed_decode",
2955
+ "spans_of", "mask_spans", "mask_one", "holds_secret", "undecodable_claim", "project_text",
2956
+ "obligations", "floor_leftovers", "spellings", "unterminated", "mask_free", "survives"}
2957
+
2958
+ def independence_violations(tree, entry_points):
2959
+ """Every place the verifier's reachable closure in `tree` touches the mapping, by name.
2960
+
2961
+ The closure is computed from the call graph rather than read from a list, because a helper three
2962
+ calls down is as much the verifier as its entry point is."""
2963
+ bodies = {node.name: node for node in _ast.walk(tree) if isinstance(node, _ast.FunctionDef)}
2964
+
2965
+ def calls_of(name):
2966
+ node = bodies.get(name)
2967
+ return set() if node is None else {call.func.id for call in _ast.walk(node)
2968
+ if isinstance(call, _ast.Call)
2969
+ and isinstance(call.func, _ast.Name)}
2970
+
2971
+ reached, pending = set(), list(entry_points)
2972
+ while pending:
2973
+ name = pending.pop()
2974
+ if name in reached or name not in bodies:
2975
+ continue
2976
+ reached.add(name)
2977
+ pending += [called for called in calls_of(name)
2978
+ if called in bodies and called not in detectors]
2979
+ return sorted(f"{name} -> {called}" for name in reached for called in calls_of(name) & mapping), reached
2980
+
2981
+ violations, reached = independence_violations(module, verifier_entry)
2982
+ failures += [f"the verifier is not independent of the mapping: {violation}" for violation in violations]
2983
+ if reached & verifier_entry != verifier_entry:
2984
+ failures.append(f"the independence check reached {sorted(reached & verifier_entry)} rather than "
2985
+ f"{sorted(verifier_entry)}, so it is asking about functions that no longer exist")
2986
+ defined = {node.name for node in _ast.walk(module) if isinstance(node, _ast.FunctionDef)}
2987
+ if mapping - defined:
2988
+ failures.append(f"the independence check forbids {sorted(mapping - defined)}, which this module "
2989
+ "does not define, so those entries forbid nothing")
2990
+ # ... and the SAME callable on an AST whose dependency sits one call below an entry point
2991
+ planted_tree = _ast.parse("def vf_unescape(text):\n return vf_planted_helper()\n"
2992
+ "def vf_planted_helper():\n return keyed_spans('')\n")
2993
+ planted_violations, _planted_reached = independence_violations(planted_tree, {"vf_unescape"})
2994
+ if planted_violations != ["vf_planted_helper -> keyed_spans"]:
2995
+ failures.append("the independence check does not report a dependency planted one call below an "
2996
+ f"entry point: {planted_violations}")
2997
+
2998
+ # ---- M#1: the choke point, held structurally rather than remembered --------------------------
2999
+ #
3000
+ # Every block this module returns must leave through `emit`, because `emit` is where the backstop runs.
3001
+ # A call added at each site is a rule someone forgets at the next site - which is exactly what happened:
3002
+ # the structured path serialised its walk and returned it unverified. So the question is asked of the
3003
+ # SOURCE: in each block-producing function, every `return` is a call to `emit`.
3004
+ import ast as _ast
3005
+ module = _ast.parse(pathlib.Path(__file__).read_text(encoding="utf-8"))
3006
+
3007
+ # ---- R#0: the verifier is independent of the mapping, and that is a source-level fact ---------
3008
+ #
3009
+ # The backstop exists to catch the mapping's mistakes. Any reading of the mapping's own state - which
3010
+ # keys it located, which extents it covered, its scanner for a keyed value - makes it blind in exactly
3011
+ # the places the mapping is blind, which is what let a duplicate member through: the mapping declared
3012
+ # the key covered by name, and the verifier asked the mapping. So the verifier's functions may use the
3013
+ # FLOOR and the detectors, and nothing of the mapping.
3014
+ # The guard follows the verifier's whole REACHABLE closure, not a list of its entry points: a helper
3015
+ # three calls down is as much the verifier as `discloses` is, and a dependency added there would have
3016
+ # been invisible to a check that only read the names it was given. The closure is computed from the call
3017
+ # graph, and a planted dependency below must be rejected by it.
3018
+ bodies = {node.name: node for node in _ast.walk(module) if isinstance(node, _ast.FunctionDef)}
3019
+ detectors = {"floor_patterns", "home_patterns", "secret_key", "is_mask", "floor_key_alternation",
3020
+ "secret_part", "note_change", "blank_for", "parses_as_json"}
3021
+ mapping = {"mask_extents", "decoded_extents", "floor_spans", "floor_spans_normalised", "keyed_spans",
3022
+ "path_spans", "literal_ranges", "within_literals", "visible_secret_keys",
3023
+ "encoded_secret_keys", "escaped_regions", "escape_map", "structures_in", "relaxed_decode",
3024
+ "spans_of", "mask_spans", "mask_one", "holds_secret", "undecodable_claim", "project_text",
3025
+ "obligations", "floor_leftovers", "spellings", "unterminated", "mask_free", "survives"}
3026
+
3027
+ def calls_of(name):
3028
+ node = bodies.get(name)
3029
+ if node is None:
3030
+ return set()
3031
+ return {call.func.id for call in _ast.walk(node)
3032
+ if isinstance(call, _ast.Call) and isinstance(call.func, _ast.Name)}
3033
+
3034
+ entry_points = {"vf_unescape", "vf_load", "vf_structures", "vf_members", "vf_keyed", "vf_exempt",
3035
+ "vf_unfinished", "all_mask", "every_spelling", "discloses", "spellings_of"}
3036
+ verifier, pending = set(), list(entry_points)
3037
+ while pending:
3038
+ name = pending.pop()
3039
+ if name in verifier or name not in bodies:
3040
+ continue
3041
+ verifier.add(name)
3042
+ pending += [called for called in calls_of(name)
3043
+ if called in bodies and called not in detectors]
3044
+ for name in sorted(verifier):
3045
+ for called in sorted(calls_of(name) & mapping):
3046
+ failures.append(f"the verifier's {name} calls the mapping's {called}, so the backstop shares "
3047
+ "the blindness it exists to catch")
3048
+ seen_verifier = verifier & entry_points
3049
+ verifier = entry_points
3050
+ # ... and the guard really follows the closure: a dependency planted one call BELOW an entry point must
3051
+ # be rejected, or the traversal is only reading the names it was handed
3052
+ planted = _ast.parse("def vf_planted_helper():\n return keyed_spans('')\n"
3053
+ "def vf_planted_entry():\n return vf_planted_helper()\n")
3054
+ planted_bodies = {node.name: node for node in planted.body}
3055
+ bodies.update(planted_bodies)
3056
+ reached, pending = set(), ["vf_planted_entry"]
3057
+ while pending:
3058
+ name = pending.pop()
3059
+ if name in reached or name not in bodies:
3060
+ continue
3061
+ reached.add(name)
3062
+ pending += [called for called in calls_of(name) if called in bodies and called not in detectors]
3063
+ if not any(calls_of(name) & mapping for name in reached):
3064
+ failures.append("the independence guard does not follow a dependency planted one call below an "
3065
+ "entry point, so it only checks the functions it was handed")
3066
+ if seen_verifier != verifier:
3067
+ failures.append(f"the independence check found {sorted(seen_verifier)} rather than "
3068
+ f"{sorted(verifier)}, so it is asking about functions that no longer exist")
3069
+ # ... and the mapping names it checks for are real functions of this module, or the check forbids nothing
3070
+ defined = {node.name for node in _ast.walk(module) if isinstance(node, _ast.FunctionDef)}
3071
+ if mapping - defined:
3072
+ failures.append(f"the independence check forbids {sorted(mapping - defined)}, which this module "
3073
+ "does not define, so those entries forbid nothing")
3074
+
3075
+ producers = {"project_text", "project_r22"}
3076
+ checked = set()
3077
+ for node in _ast.walk(module):
3078
+ if not isinstance(node, _ast.FunctionDef) or node.name not in producers:
3079
+ continue
3080
+ checked.add(node.name)
3081
+ for statement in _ast.walk(node):
3082
+ if not isinstance(statement, _ast.Return) or statement.value is None:
3083
+ continue
3084
+ call = statement.value
3085
+ if not (isinstance(call, _ast.Call) and isinstance(call.func, _ast.Name)
3086
+ and call.func.id == "emit"):
3087
+ failures.append(f"{node.name} returns a block at line {statement.lineno} without passing "
3088
+ "through emit(), so that block is never verified")
3089
+ if checked != producers:
3090
+ failures.append(f"the choke-point check found {sorted(checked)} rather than {sorted(producers)}, so "
3091
+ "it is asking about functions that no longer exist")
3092
+ # ... and the exit really runs for both shapes of input, or the check above is about dead code
3093
+ before_emitted = STATS["emitted"]
3094
+ project_text("plain text", owner)
3095
+ project({"note": "plain"}, home=owner)
3096
+ if STATS["emitted"] - before_emitted < 2:
3097
+ failures.append("a string block and a structured block did not both leave through emit()")
3098
+
3099
+ # ---- A#2: a seeded property control whose transformations are REAL ---------------------------
3100
+ #
3101
+ # The previous generator advertised four spellings and delivered two: no generated credential held a
3102
+ # slash, so slash-escaping was a no-op, and double-encoding a credential with no special characters
3103
+ # changed nothing. Worse, the leak check looked for the PLAIN credential, so a case whose credential was
3104
+ # emitted escaped could pass while the escaped spelling stood in the output.
3105
+ #
3106
+ # Each case now records the spelling it actually emitted, each class asserts that its transformation
3107
+ # changed the text, and the output is decoded independently - every form the output takes through this
3108
+ # module's decodings - before the credential is looked for in any of them.
3109
+ rnd = random.Random(20261021)
3110
+
3111
+ def still_reads(secret, out, emitted=None):
3112
+ """The ONE predicate every generated case and every planted control is judged by: does any spelling
3113
+ the VERIFIER can reach from `out` still carry this credential, whole or in a run long enough to
3114
+ matter? Built on `every_spelling`, so the oracle does not share the projection's coordinates - and
3115
+ used for the deliberately unredacted and deliberately partial outputs below, so what it rejects is
3116
+ proven rather than assumed."""
3117
+ forms = spellings_of(out)
3118
+ wanted = [secret] + ([emitted] if emitted and emitted != secret else [])
3119
+ for form in forms:
3120
+ for value in wanted:
3121
+ if value in form:
3122
+ return True
3123
+ if len(value) >= PARTIAL_SURVIVAL and any(
3124
+ value[at:at + PARTIAL_SURVIVAL] in form
3125
+ for at in range(len(value) - PARTIAL_SURVIVAL + 1)):
3126
+ return True
3127
+ return False
3128
+
3129
+ # ---- AD#0 / AD#1: the spelling set is CLOSED under the transforms ----------------------------
3130
+ #
3131
+ # Two orders were missing when the set was "each decode layer, expanded by the skeleton": the
3132
+ # invisible characters were stripped only inside the casefolded skeleton, so a case-sensitive owner
3133
+ # path or credential pattern never saw a stripped, case-preserved spelling; and an escape that
3134
+ # normalisation REVEALS was never decoded, because decoding ran before normalising and never again.
3135
+ # The closure makes every composition reachable, and this control asserts the closure IS closed.
3136
+ closure_subjects = [
3137
+ '{"note":"plain"} caf' + chr(0xE9),
3138
+ "/Us" + chr(0x200B) + "ers/fixture-owner/notes.md",
3139
+ "a " + chr(0xFF3C) + "u0070assword field",
3140
+ chr(0xC554) + chr(0xD638) + " " + chr(0xD544) + chr(0xB4DC),
3141
+ ]
3142
+ for subject in closure_subjects:
3143
+ members_set, _members, closure_reach = vf_all_spellings(subject)
3144
+ if closure_reach.exhausted:
3145
+ failures.append(f"the closure of {subject[:28]!r} did not finish: {closure_reach.reason!r}")
3146
+ continue
3147
+ if not members_set:
3148
+ failures.append(f"the closure of {subject[:28]!r} is empty, so closure proves nothing")
3149
+ continue
3150
+ held = set(members_set)
3151
+ for spelling in members_set:
3152
+ for step in vf_transforms(spelling):
3153
+ if step not in held:
3154
+ failures.append(f"the spelling set is not closed: a transform of {spelling[:24]!r} "
3155
+ f"gives {step[:24]!r}, which is not in the set")
3156
+ break
3157
+ # ... one shape per ORDER, each refused. The last is refused as undecodable rather than by name,
3158
+ # because `\U` is outside the escape table and AA#0's refusal fires before any casefolding - still a
3159
+ # refusal, which is what the boundary owes.
3160
+ orders = [
3161
+ ("an invisible character inside a case-sensitive owner path",
3162
+ "/Us" + chr(0x200B) + "ers/fixture-owner/notes.md", "the owner's home path"),
3163
+ ("an invisible character inside a case-sensitive credential",
3164
+ "sk-abcdefghij" + chr(0x200B) + "klmnopqrst", "the floor claims"),
3165
+ ("an escape revealed by NFKC", "a " + chr(0xFF3C) + "u0070assword field", "password"),
3166
+ ("an escape revealed by casefolding", "A " + chr(92) + "U0070ASSWORD FIELD", "undecodable"),
3167
+ ]
3168
+ for label, text, expected in orders:
3169
+ allowed, why = evidence_quote_admissible(text, FX_OWNER_HOME)
3170
+ if allowed:
3171
+ failures.append(f"the strict rule admits {label}")
3172
+ elif expected not in (why or ""):
3173
+ failures.append(f"{label}: refused for the wrong reason: {why!r}")
3174
+ # ... and the admitted side, so the closure is not refusing everything it reaches
3175
+ for label, text in (("ordinary Korean text", chr(0xC554) + chr(0xD638) + " " + chr(0xD544) + chr(0xB4DC)),
3176
+ ("an ordinary escaped e-acute", "caf" + chr(92) + "u00e9 on the menu"),
3177
+ ("an emoji with a ZWJ sequence",
3178
+ "a family " + chr(0x1F468) + chr(0x200D) + chr(0x1F469) + chr(0x200D)
3179
+ + chr(0x1F467) + " here")):
3180
+ allowed, why = evidence_quote_admissible(text, FX_OWNER_HOME)
3181
+ if not allowed:
3182
+ failures.append(f"the strict rule refuses {label}, which names nothing: {why!r}")
3183
+ # ... and the bound itself REFUSES by name rather than truncating. Asserted by lowering the bound
3184
+ # around a quote the closure handles comfortably, so the control reads the bound and not one
3185
+ # hand-built pathological string.
3186
+ held_limit, held_rounds = VF_CLOSURE_LIMIT, VF_CLOSURE_ROUNDS
3187
+ try:
3188
+ globals()["VF_CLOSURE_LIMIT"] = 2
3189
+ allowed, why = evidence_quote_admissible('{"note":"plain"} caf' + chr(0xE9), FX_OWNER_HOME)
3190
+ if allowed or "spells more than 2 strings" not in (why or ""):
3191
+ failures.append(f"the closure's size bound does not refuse by name: {why!r}")
3192
+ globals()["VF_CLOSURE_LIMIT"] = held_limit
3193
+ globals()["VF_CLOSURE_ROUNDS"] = 1
3194
+ allowed, why = evidence_quote_admissible('{"note":"plain"} caf' + chr(0xE9), FX_OWNER_HOME)
3195
+ if allowed or "still growing after 1 round" not in (why or ""):
3196
+ failures.append(f"the closure's round bound does not refuse by name: {why!r}")
3197
+ finally:
3198
+ globals()["VF_CLOSURE_LIMIT"], globals()["VF_CLOSURE_ROUNDS"] = held_limit, held_rounds
3199
+ # ... and the bounds are back, so nothing after this runs under a lowered one
3200
+ if (VF_CLOSURE_LIMIT, VF_CLOSURE_ROUNDS) != (held_limit, held_rounds):
3201
+ failures.append("the closure bounds were left lowered by the control that tested them")
3202
+
3203
+ # ---- AC#0: the three triggers see ONE spelling set ------------------------------------------
3204
+ #
3205
+ # The name detector expanded the normalised spellings inside itself; the floor's value patterns and
3206
+ # the owner-path detector saw the decoded string alone. So a fullwidth or zero-width-spaced owner
3207
+ # path, and a fullwidth floor match, were judged by a narrower set than a name was.
3208
+ fullwidth = {character: chr(ord(character) - 0x61 + 0xFF41) for character in "abcdefghijklmnopqrstuvwxyz"}
3209
+ def wide(text):
3210
+ return "".join(fullwidth.get(character, character) for character in text)
3211
+ zwsp, acute = chr(0x200B), chr(0x0301)
3212
+ variants = [
3213
+ ("an owner path with a fullwidth letter", "/U" + wide("sers") + "/fixture-owner/notes.md",
3214
+ "the owner's home path"),
3215
+ ("an owner path with a zero-width space", "/Users/kang" + zwsp + "min/notes.md",
3216
+ "the owner's home path"),
3217
+ ("an owner path with a combining mark", "/Users/kangmi" + acute + "n/notes.md",
3218
+ "the owner's home path"),
3219
+ ("a floor value in fullwidth", "sk-" + wide("abcdefghijklmnopqrst"), "the floor claims"),
3220
+ ("a floor value with a zero-width space", "sk-abcdefghij" + zwsp + "klmnopqrst", "the floor claims"),
3221
+ ]
3222
+ for label, text, expected in variants:
3223
+ allowed, why = evidence_quote_admissible(text, FX_OWNER_HOME)
3224
+ if allowed:
3225
+ failures.append(f"the strict rule admits {label}")
3226
+ elif expected not in (why or ""):
3227
+ failures.append(f"{label}: refused by the wrong detector: {why!r}")
3228
+ # ... and the admitted side, so the uniform loop is not simply refusing everything
3229
+ for label, text in (("an ordinary non-owner path with Unicode letters", "/opt/caf" + chr(0xE9) + "/bin/tool"),
3230
+ ("ordinary Korean text", chr(0xC554) + chr(0xD638) + " " + chr(0xD544) + chr(0xB4DC)),
3231
+ ("a plain sentence", "three files changed")):
3232
+ allowed, why = evidence_quote_admissible(text, FX_OWNER_HOME)
3233
+ if not allowed:
3234
+ failures.append(f"the strict rule refuses {label}: {why!r}")
3235
+ # ... and the structural claim itself: each detector was asked about the SAME strings. Asked of an
3236
+ # ADMITTED quote, because a refusal returns early and would leave the three lists different lengths
3237
+ # for a reason that is not divergence.
3238
+ global SPELLING_PROBE
3239
+ SPELLING_PROBE = {}
3240
+ try:
3241
+ # an admitted quote with a structure to decode, and NO backslash: a `\\u0070` body would be
3242
+ # refused as undecodable before the loop runs, and the probe would record nothing
3243
+ evidence_quote_admissible('{"note":"plain","n":2} caf' + chr(0xE9), FX_OWNER_HOME)
3244
+ seen = {detector: tuple(items) for detector, items in SPELLING_PROBE.items()}
3245
+ finally:
3246
+ SPELLING_PROBE = None
3247
+ if sorted(seen) != ["floor", "home", "name"]:
3248
+ failures.append(f"strict admission did not run all three detectors: {sorted(seen)}")
3249
+ elif len(set(seen.values())) != 1:
3250
+ widths = {detector: len(items) for detector, items in seen.items()}
3251
+ narrowest = min(widths, key=widths.get)
3252
+ failures.append(f"the three strict detectors were handed different spelling sets - {narrowest!r} "
3253
+ f"saw the narrowest, {widths}")
3254
+ elif not seen["name"]:
3255
+ failures.append("the spelling probe recorded nothing, so the identity of the three sets is vacuous")
3256
+ # ... and the set really is every decode depth times every normalisation
3257
+ shared_set, _members, _reach = vf_all_spellings('{"note":"' + chr(92) + 'u0070lain"}')
3258
+ if not any("plain" in form for form in shared_set):
3259
+ failures.append("the shared spelling set does not reach a name behind a layer of escaping")
3260
+ if wide("secret") not in vf_all_spellings(wide("secret"))[0]:
3261
+ failures.append("the shared spelling set drops the text as it stands")
3262
+ if "secret" not in vf_all_spellings(wide("secret"))[0]:
3263
+ failures.append("the shared spelling set does not normalise a fullwidth spelling")
3264
+
3265
+ # ---- AB#0: the skeleton drops every character that renders nothing of its own ----------------
3266
+ #
3267
+ # Dropping only `Mn` closed accents and left the rest standing: `pass<ZWSP>word` reads as the name to
3268
+ # a person, tokenised as two ordinary names, and the floor was asked about neither.
3269
+ invisibles = [("an Mn mark", 0x0301), ("an Mc mark", 0x093E), ("an Me mark", 0x0488),
3270
+ ("a zero-width space", 0x200B), ("a zero-width joiner", 0x200D),
3271
+ ("a zero-width non-joiner", 0x200C), ("a soft hyphen", 0x00AD),
3272
+ ("a word joiner", 0x2060), ("a bidi override", 0x202E),
3273
+ ("a variation selector", 0xFE0F), ("a supplementary variation selector", 0xE0100),
3274
+ ("a tag character", 0xE0041), ("an unassigned tag code point", 0xE0002),
3275
+ ("a Mongolian free variation selector", 0x180B), ("a Mongolian separator", 0x180E),
3276
+ ("a Hangul choseong filler", 0x115F), ("a halfwidth Hangul filler", 0xFFA0)]
3277
+ for label, code in invisibles:
3278
+ if not vf_invisible(chr(code)):
3279
+ failures.append(f"{label} (U+{code:04X}) is not read as invisible")
3280
+ spelled = "the pass" + chr(code) + "word field"
3281
+ if vf_secret_name(spelled) != "password":
3282
+ failures.append(f"{label} inside the name hides it from the floor: "
3283
+ f"{vf_secret_name(spelled)!r}")
3284
+ allowed, why = evidence_quote_admissible(spelled, owner)
3285
+ if allowed:
3286
+ failures.append(f"the strict rule admits a quote with {label} inside a secret name")
3287
+ elif "password" not in (why or ""):
3288
+ failures.append(f"{label}: the refusal does not name the token: {why!r}")
3289
+ # ... every entry in the list is load-bearing: one a category already covers is a line no revert can
3290
+ # make fail, and this is the assertion that keeps the list honest as Unicode assigns new characters
3291
+ covered = sorted(code for code in VF_IGNORABLE
3292
+ if unicodedata.category(chr(code)) in VF_INVISIBLE_CATEGORIES)
3293
+ if covered:
3294
+ failures.append(f"VF_IGNORABLE lists {len(covered)} code point(s) a category already covers, "
3295
+ f"starting at U+{covered[0]:04X}")
3296
+ if not vf_invisible(chr(0xE0002)):
3297
+ failures.append("an unassigned tag code point (U+E0002) is not read as invisible")
3298
+ # ... and a character that renders something of its own is NOT dropped, so this is not a confusable
3299
+ # mapping: a Cyrillic lookalike stays a different name, which is the scope the owner set on
3300
+ # 2026-10-22 and a tracked residual rather than a gap
3301
+ for label, code in (("a Cyrillic a", 0x0430), ("an ordinary letter", ord("a")),
3302
+ ("a Hangul syllable", 0xC554), ("an emoji", 0x1F600)):
3303
+ if vf_invisible(chr(code)):
3304
+ failures.append(f"{label} (U+{code:04X}) is read as invisible, which it is not")
3305
+ # ... and the invisible characters where they name nothing are admitted
3306
+ admitted = [("ordinary Korean text", chr(0xC554) + chr(0xD638) + " " + chr(0xD544) + chr(0xB4DC)),
3307
+ ("an emoji with a ZWJ sequence",
3308
+ chr(0x1F468) + chr(0x200D) + chr(0x1F469) + chr(0x200D) + chr(0x1F467)),
3309
+ ("a variation selector in a non-secret word", "caf" + chr(0xE9) + chr(0xFE0F) + " menu")]
3310
+ for label, text in admitted:
3311
+ if vf_secret_name(text) is not None:
3312
+ failures.append(f"{label} is read as naming a secret: {vf_secret_name(text)!r}")
3313
+ allowed, why = evidence_quote_admissible("a " + text + " stands here", owner)
3314
+ if not allowed:
3315
+ failures.append(f"the strict rule refuses {label}, which names nothing: {why!r}")
3316
+
3317
+ # ---- AA#0: the strict traversal decodes the JSON escape table and nothing else ---------------
3318
+ #
3319
+ # The lenient reading drops a backslash before anything at all, so it read `\x41` as `x41`, reported no
3320
+ # layer left undone, and an unsupported escape passed strict admission. The strict side tracks this
3321
+ # itself: every sequence the table does not define is undecodable, at any decode depth.
3322
+ slash = chr(0x5C)
3323
+ for label, run in (("an \\x escape", slash + "x41"), ("a \\q escape", slash + "q"),
3324
+ ("a short \\u escape", slash + "u12"), ("a \\U escape", slash + "U0001D5C9"),
3325
+ ("an \\8 escape", slash + "8")):
3326
+ if vf_outside_table("a " + run + " field") is None:
3327
+ failures.append(f"{label} was read as a sequence the table defines")
3328
+ if vf_undecodable("a " + run + " field") is None:
3329
+ failures.append(f"{label} was not reached by the strict traversal")
3330
+ allowed, why = evidence_quote_admissible("a " + run + " field", owner)
3331
+ if allowed or "undecodable" not in (why or ""):
3332
+ failures.append(f"the strict rule does not refuse {label} as undecodable: {why!r}")
3333
+ if vf_outside_table("a field ends here " + slash) != slash:
3334
+ failures.append("a trailing lone backslash was read as a sequence the table defines")
3335
+ if evidence_quote_admissible("a field ends here " + slash, owner)[0]:
3336
+ failures.append("the strict rule admits a quote ending in a lone backslash")
3337
+ # ... at any depth: behind one layer of escaping, and inside a JSON structure the text spells
3338
+ behind = slash + slash + "x41 stands behind one layer"
3339
+ if vf_outside_table(behind) is not None:
3340
+ failures.append(f"the top layer of {behind!r} is not itself outside the table, so the depth case "
3341
+ f"proves nothing")
3342
+ if vf_undecodable(behind) is None:
3343
+ failures.append("an unsupported escape behind one layer of escaping was not reached")
3344
+ if evidence_quote_admissible(behind, owner)[0]:
3345
+ failures.append("the strict rule admits an unsupported escape behind one layer of escaping")
3346
+ inside = '{"note":"' + slash + slash + 'x41"}'
3347
+ if vf_undecodable(inside) is None:
3348
+ failures.append("an unsupported escape inside a spelled JSON structure was not reached")
3349
+ if evidence_quote_admissible(inside, owner)[0]:
3350
+ failures.append("the strict rule admits an unsupported escape inside a spelled structure")
3351
+ # ... and the table's own escapes, with characters that need none, are read and admitted
3352
+ table_only = "a " + slash + "n b " + slash + '" c ' + slash + "/ d " + chr(0xE9) + " " + chr(0x1F600)
3353
+ if vf_outside_table(table_only) is not None:
3354
+ failures.append(f"a table escape was read as outside it: {vf_outside_table(table_only)!r}")
3355
+ if vf_undecodable(table_only) is not None:
3356
+ failures.append(f"the strict traversal refuses the table's own escapes: "
3357
+ f"{vf_undecodable(table_only)!r}")
3358
+ if not evidence_quote_admissible(table_only, owner)[0]:
3359
+ failures.append("the strict rule refuses a quote holding only table escapes")
3360
+
3361
+ # ---- Y#0: a surrogate pair is one character, and a lone surrogate is none -------------------
3362
+ #
3363
+ # Reading the halves separately produced two lone surrogates, which no normalisation maps: a
3364
+ # compatibility name written in mathematical letters arrived as unmappable halves and the floor was
3365
+ # never asked about the name they spell. On the strict side an encoding this traversal cannot finish
3366
+ # refuses the quote, which is why a lone surrogate must say so rather than pass as a character.
3367
+ maths = "".join(chr(0x1D5BA + (ord(character) - ord("a"))) for character in "password")
3368
+ paired = "".join(f"\\u{((ord(c) - 0x10000) >> 10) + 0xD800:04x}"
3369
+ f"\\u{((ord(c) - 0x10000) & 0x3FF) + 0xDC00:04x}" for c in maths)
3370
+ if vf_unescape(paired) != maths:
3371
+ failures.append(f"a surrogate pair did not decode to its character: {vf_unescape(paired)!r}")
3372
+ if vf_relax("prefix " + paired + " suffix") != "prefix " + maths + " suffix":
3373
+ failures.append("the relaxed reading did not join a surrogate pair inside ordinary text")
3374
+ if vf_secret_name(maths) != "password":
3375
+ failures.append(f"the floor was not asked about the name those letters spell: "
3376
+ f"{vf_secret_name(maths)!r}")
3377
+ for label, text in (("a lone high surrogate", "a field \\ud83d here"),
3378
+ ("a lone low surrogate", "a field \\ude00 here"),
3379
+ ("a high surrogate followed by an ordinary escape", "x \\ud83d\\u0041 y"),
3380
+ ("a pair with too few digits in its second half", "x \\ud83d\\ude0 y")):
3381
+ if vf_unescape(text) is not None:
3382
+ failures.append(f"{label} decoded to something: {vf_unescape(text)!r}")
3383
+ if not vf_unfinished(text):
3384
+ failures.append(f"{label} was not reported as an unfinished run")
3385
+ allowed, why = evidence_quote_admissible(text, owner)
3386
+ if allowed or "undecodable" not in (why or ""):
3387
+ failures.append(f"the strict rule does not refuse {label} as undecodable: {why!r}")
3388
+ # ... and an ordinary non-ASCII word, escaped, is read and admitted
3389
+ for label, text in (("an escaped Korean word", "\\uc554\\ud638 \\ud544\\ub4dc"),
3390
+ ("an escaped emoji, written as a pair", "see \\ud83d\\ude00 here")):
3391
+ if vf_unescape(text) is None:
3392
+ failures.append(f"{label} was not readable: {text!r}")
3393
+ if vf_unfinished(text):
3394
+ failures.append(f"{label} was reported as an unfinished run")
3395
+ allowed, _why = evidence_quote_admissible(text, owner)
3396
+ if not allowed:
3397
+ failures.append(f"the strict rule refuses {label}, which names nothing")
3398
+
3399
+ # T#1: the exemption is EXACT equality, asked of the rule itself. A value that starts with the mask, or
3400
+ # ends with it, or carries a comma after it, is a value with something else still in it - and the
3401
+ # generous traversal catches most such shapes by another route, so the rule is held where it lives
3402
+ # rather than only through a block.
3403
+ for value, exempt in ((FLOOR.PLACEHOLDER, True), (HOME_MASK, True), ("", True),
3404
+ ('"' + FLOOR.PLACEHOLDER + '"', True),
3405
+ (FLOOR.PLACEHOLDER + ",", True), # packaging, not content
3406
+ (FLOOR.PLACEHOLDER + " ", True), (" " + FLOOR.PLACEHOLDER, True),
3407
+ (FLOOR.PLACEHOLDER + "};", True),
3408
+ (FLOOR.PLACEHOLDER + " u0after", False),
3409
+ ("u0before " + FLOOR.PLACEHOLDER, False),
3410
+ (FLOOR.PLACEHOLDER * 2, False),
3411
+ # the scanner reads a quoted scalar WHOLE, so a comma inside it is content
3412
+ ('"' + FLOOR.PLACEHOLDER + ',u0comma_canary"', False),
3413
+ ('"' + FLOOR.PLACEHOLDER + ' u0space_canary"', False),
3414
+ # ... and a scalar it cannot read to its close is a finding, not a pass
3415
+ ('"' + FLOOR.PLACEHOLDER + " u0unterminated", False),
3416
+ ('"' + FLOOR.PLACEHOLDER + " u0trailing\\", False)):
3417
+ if vf_exempt(value) != exempt:
3418
+ failures.append(f"the keyed-fragment exemption reads {value!r} as "
3419
+ f"{'exempt' if vf_exempt(value) else 'a finding'}, which is wrong")
3420
+
3421
+ # ---- the stricter quote rule, measured rather than enforced --------------------------------
3422
+ #
3423
+ # `evidence_quote_admissible` is not wired into anything yet. It is here so the cost of making it the
3424
+ # rule can be read off a measurement instead of guessed at, and these controls say what it would mean.
3425
+ quote_cases = [
3426
+ ("an ordinary sentence", "the tool reported three files changed", True),
3427
+ ("a masked keyed fragment, which the projection allows and this does not",
3428
+ '"password": "' + FLOOR.PLACEHOLDER + '"', False),
3429
+ ("a secret-named token on its own", "rotate the refresh_token next week", False),
3430
+ ("a credential the floor claims", "sk-" + "Ab1_" * 6, False),
3431
+ ("the owner's home path", owner + "/Documents/notes.md", False),
3432
+ ("a secret-named key inside a decoded document",
3433
+ json.dumps({"password": FLOOR.PLACEHOLDER}, ensure_ascii=False), False),
3434
+ ("a secret-named key one encoding down",
3435
+ '{"' + "".join(f"\\u{ord(ch):04x}" for ch in "password") + '":"' + FLOOR.PLACEHOLDER + '"}', False),
3436
+ ("an encoding this verifier cannot finish", "a quote ending in a backslash\\", False),
3437
+ ("the mask by itself", FLOOR.PLACEHOLDER, True),
3438
+ ]
3439
+ for label, quote, admissible in quote_cases:
3440
+ allowed, why = evidence_quote_admissible(quote, owner)
3441
+ if allowed != admissible:
3442
+ failures.append(f"the stricter quote rule reads {label} as "
3443
+ f"{'admissible' if allowed else 'refused'}: {why!r}")
3444
+ if not allowed and not why:
3445
+ failures.append(f"the stricter quote rule refused {label} without naming a reason")
3446
+
3447
+ # S#2: the extent rule itself, on a pair that differs only in whether a raw detector covers the plant
3448
+ covered = '{"password":"s2plainCredentialValue"}'
3449
+ uncovered = '{"' + "".join(f"\\u{ord(ch):04x}" for ch in "password") + '":"s2plainCredentialValue"}'
3450
+ spots = [(start, end) for start, end, _replacement, _rank in keyed_spans(covered)]
3451
+ if not any(start <= covered.find("s2plainCredentialValue") < end for start, end in spots):
3452
+ failures.append("the keyed locator does not cover a plainly keyed credential, so the extent rule "
3453
+ "below is not measuring coverage")
3454
+ if any(start <= uncovered.find("s2plainCredentialValue") < end
3455
+ for start, end, _replacement, _rank in keyed_spans(uncovered)):
3456
+ failures.append("the keyed locator covers a credential under an ENCODED key, so a case of a "
3457
+ "decoding class cannot be distinguished from a raw one")
3458
+
3459
+ # the oracle rejects an output that was not redacted at all, and one that was redacted by half
3460
+ oracle_secret = "sk-" + "Zz9Q" * 5
3461
+ oracle_controls = [
3462
+ ("an encoded credential left entirely unredacted",
3463
+ '{"note":"' + "".join(f"\\u{ord(ch):04x}" for ch in oracle_secret) + '"}'),
3464
+ ("a credential whose first half alone was masked",
3465
+ '{"note":"' + FLOOR.PLACEHOLDER + oracle_secret[10:] + '"}'),
3466
+ ("a credential inside a doubly encoded document",
3467
+ json.dumps({"payload": json.dumps({"v": oracle_secret}, ensure_ascii=False)}, ensure_ascii=False)),
3468
+ # S#2: fully and partially surviving ENCODED outputs, through this same predicate
3469
+ ("an encoded credential surviving whole",
3470
+ '{"v":"' + "".join(f"\\u{ord(ch):04x}" for ch in oracle_secret) + '"}'),
3471
+ ("an encoded credential surviving by half",
3472
+ '{"v":"' + FLOOR.PLACEHOLDER
3473
+ + "".join(f"\\u{ord(ch):04x}" for ch in oracle_secret[10:]) + '"}'),
3474
+ ("a credential surviving inside an escaped document",
3475
+ '\\"v\\": \\"' + oracle_secret + '\\"'),
3476
+ ]
3477
+ for label, planted_output in oracle_controls:
3478
+ if not still_reads(oracle_secret, planted_output):
3479
+ failures.append(f"the oracle accepts {label}, so every judgement it makes below is vacuous")
3480
+ if still_reads(oracle_secret, FLOOR.PLACEHOLDER):
3481
+ failures.append("the oracle reads a credential in the mask itself, so it can never report clean")
3482
+
3483
+ def body(length, alphabet="abcdefghijkmnpqrstuvwxyz23456789"):
3484
+ """A distinctive credential body: repeated filler would let two generated secrets share a run of
3485
+ eight characters, and the oracle would then read one as the other."""
3486
+ return "".join(rnd.choice(alphabet) for _ in range(length))
3487
+
3488
+ def floor_shape(which):
3489
+ """A credential the FLOOR itself claims, in the shape `which` names."""
3490
+ return {"sk": "sk-" + body(20), "ghp": "ghp_" + body(22),
3491
+ "jwt": "eyJ" + body(22) + ".rest", "akia": "AKIA" + body(14, "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"),
3492
+ "email": body(10) + ".dev@example.com"}[which]
3493
+
3494
+ def u_escape(text, portion=0.4):
3495
+ return "".join(f"\\u{ord(ch):04x}" if ch.isalnum() and rnd.random() < portion else ch for ch in text)
3496
+
3497
+ def emitted_in(text, spelling):
3498
+ """The spelling as `text` really carries it - the planted extent, not a guess.
3499
+
3500
+ Each nesting doubles the backslashes of the layer inside it, so the spelling a generator wrote and
3501
+ the one the finished text holds are different strings. The extent checks below are about the
3502
+ characters that are actually there, so the doubling is followed until it matches."""
3503
+ form = spelling
3504
+ for _doubling in range(5):
3505
+ if form and form in text:
3506
+ return form
3507
+ form = form.replace("\\", "\\\\")
3508
+ return None
3509
+
3510
+ cases = [] # (class, text, the credential, the spelling that was emitted)
3511
+ for which in ("sk", "ghp", "jwt", "akia", "email"):
3512
+ for _round in range(4):
3513
+ # 1. a credential inside an ESCAPED literal: only the escaped reading finds it
3514
+ secret = floor_shape(which)
3515
+ cases.append(("escaped literal", '{\\"note\\": \\"' + secret + '\\"}', secret, secret))
3516
+ # 2. a \u escape: the credential's own characters are written as escapes
3517
+ secret = floor_shape(which)
3518
+ spelled = u_escape(secret, 0.6)
3519
+ cases.append(("u-escaped value", '{"note":"' + spelled + '"}', secret, spelled))
3520
+ # 3. a \/ escape, over a value that HAS slashes - an owner path, which is what carries them
3521
+ path = f"{owner}/Documents/{body(6)}/notes.md"
3522
+ cases.append(("slash-escaped path", '{"at":"' + path.replace("/", "\\/") + '"}',
3523
+ owner, path.replace("/", "\\/")))
3524
+ # 4. double encoded: a literal whose content is itself a JSON document
3525
+ secret = floor_shape(which)
3526
+ # the KEY is encoded as well, or the raw keyed locator covers the planted extent without any
3527
+ # decoding and the case stops being about a decoding at all
3528
+ spelled = u_escape(secret, 1.0)
3529
+ inner = json.dumps({u_escape("password", 1.0): spelled}, ensure_ascii=False)
3530
+ text = json.dumps({"payload": inner}, ensure_ascii=False)
3531
+ cases.append(("double encoded", text, secret, emitted_in(text, spelled)))
3532
+ # 5. JSON in a string at depth two or more
3533
+ secret = floor_shape(which)
3534
+ spelled = u_escape(secret, 1.0)
3535
+ deep = json.dumps({"outer": json.dumps({"mid": json.dumps(
3536
+ {u_escape("api_key", 1.0): spelled}, ensure_ascii=False)}, ensure_ascii=False)},
3537
+ ensure_ascii=False)
3538
+ cases.append(("json in string at depth 2+", deep, secret, emitted_in(deep, spelled)))
3539
+ # 6. a quoted scalar that holds a structure - A#0's trace
3540
+ secret = floor_shape(which)
3541
+ cases.append(("quoted scalar holding a structure",
3542
+ 'prefix "password": "x{}' + secret + '"', secret, secret))
3543
+ # 7. a literal mask as a neighbour, in each position
3544
+ secret = floor_shape(which)
3545
+ cases.append(("literal mask before", f'{{"seen":"{FLOOR.PLACEHOLDER}"}} "token":"{secret}"',
3546
+ secret, secret))
3547
+ secret = floor_shape(which)
3548
+ cases.append(("literal mask inside the value",
3549
+ '"password": ' + json.dumps({"seen": FLOOR.PLACEHOLDER, "v": secret},
3550
+ ensure_ascii=False), secret, secret))
3551
+ # 8. a floor claim spread across two members - no leaf holds it
3552
+ secret = floor_shape(which)
3553
+ cases.append(("cross-member claim",
3554
+ '{"a":"' + floor_shape("sk") + ' api_key=","b":"' + secret + '"}', secret, secret))
3555
+ # 9. a secret in the prose before and after a structure
3556
+ secret = floor_shape(which)
3557
+ cases.append(("secret in the gap", f'token={secret} ' + '{"note":"plain"}', secret, secret))
3558
+ secret = floor_shape(which)
3559
+ cases.append(("secret in the tail", '{"note":"plain"} ' + f'token={secret}', secret, secret))
3560
+ # 10. an OPAQUE keyed value: nothing in the value's own characters says it is a credential, so
3561
+ # only the key that names it can mask it - and that key is written in escapes
3562
+ opaque = body(18, "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz")
3563
+ cases.append(("opaque value under an encoded key",
3564
+ '{"note":"ordinary", "' + u_escape("password", 1.0) + '":"' + opaque + '"}',
3565
+ opaque, opaque))
3566
+ # 11. a floor credential that only exists after a decoding - the floor cannot see the raw form
3567
+ secret = floor_shape(which)
3568
+ cases.append(("encoded floor credential", '{"note":"' + u_escape(secret, 1.0) + '"}',
3569
+ secret, u_escape(secret, 1.0)))
3570
+ # 12. an encoded secret-named KEY, whose member has no locatable extent. The value is a floor
3571
+ # shape written in escapes, so neither the key nor the value is readable without decoding.
3572
+ secret = floor_shape(which)
3573
+ cases.append(("encoded secret-named key",
3574
+ '{"note":"plain", "' + u_escape("password", 1.0) + '":"'
3575
+ + u_escape(secret, 1.0) + '"}', secret, u_escape(secret, 1.0)))
3576
+
3577
+ # Every class must have delivered the transformation it advertises - and what has to have changed is
3578
+ # not the same thing in each: the credential's own spelling in some, the container's in others, and in
3579
+ # one the KEY's. A blanket test called two classes inert that were doing exactly their job.
3580
+ def transformed(kind, text, secret, emitted):
3581
+ if kind == "escaped literal":
3582
+ return '\\"' in text # the container is written in escapes
3583
+ if kind in ("u-escaped value", "slash-escaped path"):
3584
+ return emitted != secret and emitted in text
3585
+ if kind == "double encoded":
3586
+ return '\\"' in text and text.count('"') > 4 # a literal whose content is itself a document
3587
+ if kind in ("encoded secret-named key", "opaque value under an encoded key"):
3588
+ return '"password"' not in text and "password" not in text
3589
+ if kind == "encoded floor credential":
3590
+ return emitted != secret and not any(p.search(text) for p in floor_patterns())
3591
+ if kind == "json in string at depth 2+":
3592
+ return text.count("\\\\") > 0 or text.count('\\"') > 1
3593
+ return True
3594
+ needs_decoding = {"escaped literal", "u-escaped value", "slash-escaped path", "double encoded",
3595
+ "json in string at depth 2+", "encoded secret-named key",
3596
+ "opaque value under an encoded key", "encoded floor credential"}
3597
+ # The escaped-literal class plants a PLAIN credential inside an escaped container: its subject is the
3598
+ # container, and the floor can see the credential by design. Every other decoding class must hide its
3599
+ # credential from the raw detectors, or the case proves nothing about a decoding.
3600
+ hidden_from_raw = needs_decoding - {"escaped literal"}
3601
+ # the depth each class is about, declared rather than implied
3602
+ declared_depth = {"u-escaped value": 1, "slash-escaped path": 1, "encoded floor credential": 1,
3603
+ "encoded secret-named key": 1, "opaque value under an encoded key": 1,
3604
+ "double encoded": 2, "json in string at depth 2+": 2}
3605
+ per_class, reached = collections.Counter(), collections.Counter()
3606
+ inert, leaked, not_idempotent, raw_visible, unreachable = [], [], [], [], []
3607
+
3608
+ def secret_key_visible(text, secret):
3609
+ """Whether a raw keyed rule already locates this credential - which means no decoding is needed."""
3610
+ return any(text[start:end] == secret for start, end, _replacement, _rank in keyed_spans(text))
3611
+
3612
+ def depth_validation(text, subject, declared):
3613
+ """`(depth, complaint)` - the decoding depth at which the verifier first sights `subject`, and what
3614
+ is wrong with it against the depth this case DECLARES.
3615
+
3616
+ One function for the generated cases and for the planted ones, so a case cannot be judged by a
3617
+ looser rule than the one the suite advertises. "At least one decoding" let a class claiming two
3618
+ layers pass on one."""
3619
+ depth = depth_of_first_sighting(text, subject)
3620
+ if depth is None:
3621
+ return None, f"no decoding reaches {subject[:12]!r}"
3622
+ if depth < declared:
3623
+ return depth, f"INSUFFICIENT_DEPTH actual={depth} declared={declared} subject={subject[:12]!r}"
3624
+ return depth, None
3625
+
3626
+ def depth_of_first_sighting(text, secret):
3627
+ """The least decode depth at which the VERIFIER's own traversal sees the credential, or None.
3628
+
3629
+ Depth 0 is the text as it stands. A class that advertises a decoding and is sighted at 0 is a case
3630
+ that proves nothing: the credential was readable without decoding anything."""
3631
+ for layers in range(VERIFY_DEPTH + 1):
3632
+ # the traversal starts at `VERIFY_DEPTH - layers`, so it has exactly `layers` left to spend
3633
+ forms = [form for form in every_spelling(text, VERIFY_DEPTH - layers)[0]
3634
+ if isinstance(form, str)]
3635
+ if any(secret in form for form in forms):
3636
+ return layers
3637
+ return None
3638
+ for kind, text, secret, emitted in cases:
3639
+ per_class[kind] += 1
3640
+ if not transformed(kind, text, secret, emitted):
3641
+ inert.append((kind, text[:40]))
3642
+ # M#5: for a class that advertises a decoding, the RAW detectors must be blind to the planted
3643
+ # credential and the intended depth must expose it. Without both halves a case can pass by being
3644
+ # trivially visible, which is the opposite of what it claims to test.
3645
+ if kind in hidden_from_raw:
3646
+ # S#2: no raw detector may COVER THE PLANTED EXTENT - the characters the credential was actually
3647
+ # emitted as. Asking "does any detector match anywhere in the text" is a different question: a
3648
+ # case can carry an unrelated raw match and still be claiming a decoding it does not need, and a
3649
+ # case whose own extent IS covered raw proves nothing whatever else the text holds.
3650
+ at = text.find(emitted) if emitted else -1
3651
+ if at < 0:
3652
+ inert.append((kind, "the emitted spelling is not in the text: " + emitted[:20]))
3653
+ else:
3654
+ extent = (at, at + len(emitted))
3655
+ covering = [pattern.pattern[:18] for pattern in list(floor_patterns())
3656
+ + list(home_patterns(owner))
3657
+ for match in pattern.finditer(text)
3658
+ if match.start() < extent[1] and match.end() > extent[0]]
3659
+ if covering:
3660
+ raw_visible.append((kind, f"a raw detector covers the planted extent: {covering[:2]}"))
3661
+ if any(start < extent[1] and end > extent[0]
3662
+ for start, end, _replacement, _rank in keyed_spans(text)):
3663
+ raw_visible.append((kind, "the keyed locator covers the planted extent"))
3664
+ # What has to require a decoding is not the same thing in every class. Where the credential
3665
+ # itself is encoded, the credential must be sighted only below the surface. Where the value is
3666
+ # opaque and the KEY carries the secrecy, it is the key that must be.
3667
+ subject = "password" if kind == "opaque value under an encoded key" else secret
3668
+ depth, complaint = depth_validation(text, subject, declared_depth[kind])
3669
+ if complaint:
3670
+ unreachable.append((kind, complaint))
3671
+
3672
+ out = project_text(text, owner)
3673
+ # judged by the shared predicate above, which the planted controls proved rejects both an
3674
+ # unredacted and a half-masked output
3675
+ if still_reads(secret, out, emitted):
3676
+ leaked.append((kind, secret[:14], out[:60]))
3677
+ if discloses(out, owner):
3678
+ leaked.append((kind, discloses(out, owner), out[:60]))
3679
+ reached[kind] += 1 if any(form != text for form in spellings_of(text)[1:]) else 0
3680
+ if project_text(out, owner) != out:
3681
+ not_idempotent.append((kind, out[:60]))
3682
+ for kind in ("escaped literal", "u-escaped value", "slash-escaped path", "double encoded",
3683
+ "json in string at depth 2+", "quoted scalar holding a structure", "literal mask before",
3684
+ "literal mask inside the value", "cross-member claim", "secret in the gap",
3685
+ "secret in the tail", "encoded secret-named key", "opaque value under an encoded key",
3686
+ "encoded floor credential"):
3687
+ if per_class[kind] < 4:
3688
+ failures.append(f"the class {kind!r} has {per_class[kind]} generated case(s), so it stands for "
3689
+ "nothing")
3690
+ # ... and for the classes whose whole point is a decoding, the verifier's own decoder must really
3691
+ # have had something to decode: a class that advertises an encoding and hands the verifier a plain
3692
+ # string proves nothing about either of them.
3693
+ if kind in needs_decoding and reached[kind] < 1:
3694
+ failures.append(f"no case of the class {kind!r} reached the verifier's decoder with anything to "
3695
+ "decode, so the class exercises nothing it advertises")
3696
+ if inert:
3697
+ failures.append(f"{len(inert)} case(s) advertise a transformation that changed nothing: {inert[:3]}")
3698
+ if raw_visible:
3699
+ failures.append(f"{len(raw_visible)} case(s) of a decoding class are already visible to the raw "
3700
+ f"detectors, so they do not test a decoding: {raw_visible[:3]}")
3701
+ # ... and the assertion is proven on a deliberately SHALLOWER fixture: a case that declares two layers
3702
+ # and delivers one must be rejected, or the declaration is decoration
3703
+ # U#3: a case that needs ONE decoding while claiming two must be rejected by that same function
3704
+ shallow_secret = floor_shape("sk")
3705
+ shallow = json.dumps({"payload": json.dumps({"v": shallow_secret}, ensure_ascii=False)},
3706
+ ensure_ascii=False)
3707
+ # this shape escapes only its container's quotes, so its credential stands in the raw text: depth 0.
3708
+ # Declaring one layer, or two, must be rejected; declaring none must not.
3709
+ # V#4: the violation is NAMED, and the name carries the actual depth and the declared one - a control
3710
+ # that only asks "was there a complaint" passes on a complaint about something else
3711
+ for declared in (1, 2):
3712
+ _depth, named = depth_validation(shallow, shallow_secret, declared)
3713
+ if named != f"INSUFFICIENT_DEPTH actual=0 declared={declared} subject={shallow_secret[:12]!r}":
3714
+ failures.append(f"the depth validation did not name its refusal of a case readable without any "
3715
+ f"decoding while declaring {declared}: {named!r}")
3716
+ if depth_validation(shallow, shallow_secret, 0)[1]:
3717
+ failures.append("the depth validation rejects the same case against the depth it really has")
3718
+ # ... and a case that really is one layer down is accepted at one and rejected at two
3719
+ one_layer = '{"v":"' + "".join(f"\\u{ord(ch):04x}" for ch in shallow_secret) + '"}'
3720
+ # X#5: the WHOLE returned tuple in both directions - the depth as well as the verdict, so a function
3721
+ # that reported the right complaint about the wrong depth would fail here
3722
+ accepted = depth_validation(one_layer, shallow_secret, 1)
3723
+ if accepted != (1, None):
3724
+ failures.append(f"the depth validation did not accept a one-decoding case declaring one as "
3725
+ f"(1, None): {accepted!r}")
3726
+ refused = depth_validation(one_layer, shallow_secret, 2)
3727
+ if refused != (1, f"INSUFFICIENT_DEPTH actual=1 declared=2 subject={shallow_secret[:12]!r}"):
3728
+ failures.append(f"a one-decoding case declaring two was not refused by name: {refused!r}")
3729
+ if unreachable:
3730
+ failures.append(f"{len(unreachable)} case(s) of a decoding class hide their credential from the "
3731
+ f"verifier's own traversal, so nothing proves the depth is reached: {unreachable[:3]}")
3732
+ if leaked:
3733
+ failures.append(f"{len(leaked)} generated case(s) leave a credential readable in some decoding of the "
3734
+ f"output, first: {leaked[:2]}")
3735
+ if not_idempotent:
3736
+ failures.append(f"{len(not_idempotent)} generated case(s) are not idempotent, first: {not_idempotent[:2]}")
3737
+ # ... and the oracle itself rejects a deliberately partial mask, or every count above means nothing
3738
+ partial_secret = floor_shape("sk")
3739
+ half_masked = f'{{"note":"{FLOOR.PLACEHOLDER}{partial_secret[10:]}"}}'
3740
+ if not any(partial_secret[10:] in form for form in spellings(half_masked)):
3741
+ failures.append("the leak oracle does not see a credential whose first half alone was masked")
3742
+ generated = len(cases)
3743
+ class_counts = dict(sorted(per_class.items()))
3744
+
3745
+ # The differential the lead's direction names: over every fixture string of this self-test, whatever the
3746
+ # unchanged floor would mask, the projection masks at least as much. Positive control first - the corpus
3747
+ # is non-empty and its own secret cases are asserted above - and the subject set is counted, because an
3748
+ # empty corpus satisfies this and every other "never less" claim.
3749
+ corpus = ([text if isinstance(text, str) else serialise(text) for _label, text, _planted in secrets + structured]
3750
+ + [text for _label, text, _planted in paths]
3751
+ + [text for _label, text in kept]
3752
+ + [value if isinstance(value, str) else serialise(value)
3753
+ for _label, value, _want in structured_kept]
3754
+ + ["Authorization: Bearer\nopaque0123456789abcdef", "ask alice.dev@example.com",
3755
+ "api_key=live_0123456789abcdef and sk-" + "a" * 20, "nothing to see here"])
3756
+ if len(corpus) < 40:
3757
+ failures.append(f"the differential corpus is {len(corpus)} strings, too few to be the subject of this claim")
3758
+ leftover = {text: floor_leftovers(text, owner) for text in corpus if floor_leftovers(text, owner)}
3759
+ if leftover:
3760
+ failures.append(f"the floor masks something the projection does not, which is the one direction this "
3761
+ f"module may not take: {sorted(leftover)[:3]}")
3762
+ # ... and the projection masks MORE than the floor somewhere in the corpus, or it is not a projection
3763
+ if not any(project_text(text, owner) != FLOOR.redact(text) for text in corpus):
3764
+ failures.append("the projection masks exactly what the floor masks everywhere, so the corpus cannot "
3765
+ "show the difference this module exists to make")
3766
+
3767
+ # The sweep, over a fixture run directory: it must find a member the projection would have masked, must
3768
+ # not count one already masked, and must read the index only for its shape. Positive control first, so a
3769
+ # green sweep cannot be a sweep that scanned nothing.
3770
+ with tempfile.TemporaryDirectory() as tmp:
3771
+ run = pathlib.Path(tmp)
3772
+ (run / "redacted").mkdir()
3773
+ (run / "index" / "bm25").mkdir(parents=True)
3774
+ planted = 'tail\\", \\"client_secret\\": \\"sweepplanted\\", \\"next\\": 1'
3775
+ line = {"line": 1, "ts": "2026-10-15T00:00:00Z",
3776
+ "items": [{"pointer": "/a", "kind": "tool_result", "tool": "Bash", "error": False, "text": planted}]}
3777
+ (run / "redacted" / "x.r2.jsonl").write_text(json.dumps(line, ensure_ascii=False) + "\n", encoding="utf-8")
3778
+ (run / "index" / "bm25" / "t.json").write_text(json.dumps(
3779
+ {"version_sha": "x", "redaction_version": CURRENT, "docs": [], "postings": {"token": [1, 2]}}), encoding="utf-8")
3780
+ residual, masked, by_key, bad_index, index_files = sweep(run)
3781
+ if residual != 1 or by_key != collections.Counter({"client_secret": 1}): # the whole key, not just `secret`
3782
+ failures.append(f"the sweep did not find the planted residual member: {residual}, {dict(by_key)}")
3783
+ if bad_index or index_files != 1:
3784
+ failures.append(f"the sweep misread a well-formed index: {bad_index} bad of {index_files}")
3785
+ # the same line as the projection writes it: nothing residual, and the placeholder is counted
3786
+ line["items"][0]["text"] = project(planted, home=owner)
3787
+ (run / "redacted" / "x.r2.jsonl").write_text(json.dumps(line, ensure_ascii=False) + "\n", encoding="utf-8")
3788
+ residual, masked, _by_key, _bad, _files = sweep(run)
3789
+ if residual:
3790
+ failures.append(f"the sweep called the projection's own output residual: {residual}")
3791
+ if not masked:
3792
+ failures.append("the sweep counted no placeholder in projected text, so it scanned nothing")
3793
+ # M#4: a window file is a pretty-printed document, not one record per line, and reading it line by
3794
+ # line skipped every window in the run while printing a clean result
3795
+ (run / "views" / "s1").mkdir(parents=True)
3796
+ window = {"records": [{"text": 'tail\\", \\"client_secret\\": \\"windowplanted\\"'}]}
3797
+ (run / "views" / "s1" / "1.json").write_text(json.dumps(window, indent=2, ensure_ascii=False), encoding="utf-8")
3798
+ try:
3799
+ residual, _masked, by_key, _bad, _files = sweep(run)
3800
+ if residual != 1 or by_key != collections.Counter({"client_secret": 1}):
3801
+ failures.append(f"the sweep did not read a pretty-printed window: {residual}, {dict(by_key)}")
3802
+ except Unswept as exc:
3803
+ failures.append(f"the sweep could not read a pretty-printed window at all: {exc}")
3804
+ # ... and every quoting the masker can write is recognised as masked, including a repr's
3805
+ for spelling in ('"password": "{}"', "'password': '{}'", 'password": \\"{}\\"', "password = {}"):
3806
+ projected = project(spelling.format("quoteplanted"), home=owner)
3807
+ if residual_in(projected):
3808
+ failures.append(f"the sweep called its own masker's output residual: {spelling}")
3809
+ # an index whose postings are not document numbers is the one index shape the sweep does judge
3810
+ (run / "views" / "s1" / "1.json").unlink()
3811
+ (run / "index" / "bm25" / "t.json").write_text(json.dumps(
3812
+ {"version_sha": "x", "redaction_version": CURRENT, "docs": [], "postings": {"token": "a secret"}}),
3813
+ encoding="utf-8")
3814
+ if sweep(run)[3] != 1:
3815
+ failures.append("the sweep accepted an index posting that is not a list of document numbers")
3816
+ # M#4: a subject it cannot read, and no subject at all, are refusals - not a clean sweep
3817
+ (run / "redacted" / "broken.jsonl").write_text("{not json\n", encoding="utf-8")
3818
+ try:
3819
+ sweep(run)
3820
+ failures.append("the sweep skipped a record it could not read instead of refusing")
3821
+ except Unswept as exc:
3822
+ if "UNSWEPT_RECORD" not in str(exc):
3823
+ failures.append(f"an unreadable record was refused unnamed: {exc}")
3824
+ (run / "redacted" / "broken.jsonl").unlink()
3825
+ (run / "views" / "s1" / "sequence.json").write_text("{not json", encoding="utf-8")
3826
+ try:
3827
+ sweep(run)
3828
+ failures.append("the sweep skipped a document it could not read instead of refusing")
3829
+ except Unswept as exc:
3830
+ if "UNSWEPT_DOCUMENT" not in str(exc):
3831
+ failures.append(f"an unreadable document was refused unnamed: {exc}")
3832
+ with tempfile.TemporaryDirectory() as empty:
3833
+ try:
3834
+ sweep(empty)
3835
+ failures.append("the sweep judged a run directory with no subject and called it clean")
3836
+ except Unswept as exc:
3837
+ if "UNSWEPT_EMPTY" not in str(exc):
3838
+ failures.append(f"an empty subject set was refused unnamed: {exc}")
3839
+ with contextlib.redirect_stdout(io.StringIO()): # its refusal is the subject here, not its printing
3840
+ refused = report_sweep(empty)
3841
+ if refused == 0:
3842
+ failures.append("the sweep reported success over no subject at all")
3843
+ # ---- document_disclosures: one entry point, over every representation a caller can hand it.
3844
+ # The helpers underneath read different shapes (`all_mask` an object as Members, `holds_secret` a
3845
+ # plain object, `discloses` a string), and a caller choosing per value got one wrong in each
3846
+ # direction. The table is the contract: the same document discloses the same thing whichever
3847
+ # representation it arrives in.
3848
+ doc_token = "sk-ant-oat01-" + "Ab1_" * 12
3849
+ document_shapes = [
3850
+ ("a plain mapping with a credential-named member", {"api_key": "shortpass"}, True),
3851
+ ("the same mapping in this module's own representation", Members([("api_key", "shortpass")]), True),
3852
+ ("a duplicate credential-named member behind a masked one",
3853
+ Members([("api_key", FLOOR.PLACEHOLDER), ("api_key", "shortpass")]), True),
3854
+ ("a list of mappings", [{"api_key": "shortpass"}], True),
3855
+ ("a mapping nested three deep", {"a": {"b": {"api_key": "shortpass"}}}, True),
3856
+ ("a secret string inside a list inside a mapping", {"a": [{"note": f"use {doc_token} now"}]}, True),
3857
+ ("a credential-named member carrying a number", {"api_key": 12345678901234567890}, True),
3858
+ ("a credential-named member carrying a structure", {"token": {"value": "shortpass"}}, True),
3859
+ ("a structure masked through and through", {"token": {"value": FLOOR.PLACEHOLDER}}, False),
3860
+ ("a credential-named member with nothing in it", {"api_key": None}, False),
3861
+ ("the owner's home path in a value", {"path": f"{owner}/Documents/x"}, True),
3862
+ ("a credential as a key", {f"api_key {doc_token}": "x"}, True),
3863
+ ("ordinary prose", {"note": "the dispatch path is verified"}, False),
3864
+ ("a mapping of masked members", Members([("api_key", FLOOR.PLACEHOLDER), ("note", "plain")]), False),
3865
+ ]
3866
+ for label, document, expected in document_shapes:
3867
+ found = document_disclosures(document, owner)
3868
+ if bool(found) != expected:
3869
+ failures.append(f"document_disclosures on {label}: expected "
3870
+ f"{'a disclosure' if expected else 'none'}, got {found}")
3871
+ for row in found:
3872
+ if doc_token in row or owner in row or "shortpass" in row:
3873
+ failures.append(f"document_disclosures on {label} repeated what it objected to: {row}")
3874
+ both_ways = (document_disclosures({"a": {"api_key": "shortpass"}}, owner),
3875
+ document_disclosures(as_members({"a": {"api_key": "shortpass"}}), owner))
3876
+ if not both_ways[0] or both_ways[0] != both_ways[1]:
3877
+ failures.append(f"the two representations of one document disclosed differently: {both_ways}")
3878
+ if document_members({"a": 1}) is None or document_members(Members([("a", 1)])) is None \
3879
+ or document_members([1]) is not None:
3880
+ failures.append("document_members does not read both object representations, and only those")
3881
+ if all_mask(as_members({"value": FLOOR.PLACEHOLDER})) is not True \
3882
+ or all_mask({"value": FLOOR.PLACEHOLDER}) is not False:
3883
+ failures.append("as_members no longer hands all_mask the representation it reads")
3884
+ deep = {"a": "x"}
3885
+ for _ in range(MAX_DEPTH + 2):
3886
+ deep = {"a": deep}
3887
+ if not any("nested deeper" in row for row in document_disclosures(deep, owner)):
3888
+ failures.append("a document nested past this floor's reach was judged rather than named")
3889
+ # ---- a location names a key only from the owning code's schema; every other key is an ordinal.
3890
+ # `shortpass` is an ordinary short secret and a perfectly ordinary word to find as a key, and
3891
+ # naming it because it matched a name-shaped regex repeated it in the refusal.
3892
+ nested_key = document_disclosures({"api_key": {"shortpass": {"token": "x"}}}, owner)
3893
+ if not nested_key or any("shortpass" in row for row in nested_key):
3894
+ failures.append(f"an ordinary short secret as a nested key was repeated in its location: {nested_key}")
3895
+ if not all("[key #" in row for row in nested_key):
3896
+ failures.append(f"a key no schema declares was named rather than numbered: {nested_key}")
3897
+ declared = document_disclosures({"api_key": "shortpass"}, owner, schema=frozenset({"api_key"}))
3898
+ if not declared or not all(row.startswith("$.api_key") for row in declared):
3899
+ failures.append(f"a member name the owning code declares was not used as the location: {declared}")
3900
+ # The "a key discloses" rule needs a control of its own: the credential-named-member rule fires on
3901
+ # the same fixture for a secret-shaped key, so removing this rule went unnoticed. A home path as a
3902
+ # key discloses without being credential-named, and this is the only rule that reports it.
3903
+ key_only = document_disclosures({f"{owner}/Documents/x": "plain"}, owner)
3904
+ if [row.partition(": ")[2] for row in key_only] != ["a key discloses a home path"]:
3905
+ failures.append(f"a key that discloses without being credential-named was not reported: {key_only}")
3906
+ if any(owner in row for row in key_only):
3907
+ failures.append(f"the refusal repeated the home path it objected to: {key_only}")
3908
+ # ---- a span is projected with the intact carrier's structural context (GC#4)
3909
+ span_carrier = 'api_key: [\n "alpha",\n\n "bravo",\n\n "shortpass"\n]\n'
3910
+ last = span_carrier.index(' "shortpass"')
3911
+ far = project_span(span_carrier, last, len(span_carrier), owner)
3912
+ if "shortpass" in far:
3913
+ failures.append(f"a credential whose key sits more than two nonblank lines above the value "
3914
+ f"was emitted unmasked: {far!r}")
3915
+ multiline = 'password: "alpha\nbravo\nshortpass"\n'
3916
+ fragment = project_span(multiline, multiline.index("bravo"), len(multiline), owner)
3917
+ if "shortpass" in fragment or "bravo" in fragment:
3918
+ failures.append(f"a span inside a multi-line credential was emitted unmasked: {fragment!r}")
3919
+ plain = "the dispatch path is verified\n"
3920
+ if project_span(plain, 0, len(plain), owner) != project(plain, CURRENT, owner):
3921
+ failures.append("a span of a carrier that discloses nothing is not the carrier's own projection")
3922
+ if project_span(span_carrier, 0, len(span_carrier), owner) != project(span_carrier, CURRENT, owner):
3923
+ failures.append("a span that IS the whole carrier differs from projecting the carrier")
3924
+ # ---- a printed line passes the same floor, and a line that still discloses is withheld
3925
+ if owner in diagnostic(f"cannot read {owner}/Documents/x", owner):
3926
+ failures.append("a diagnostic printed the owner's home path")
3927
+ if diagnostic("STAGE_NOT_IMPLEMENTED read (S3)", owner) != "STAGE_NOT_IMPLEMENTED read (S3)":
3928
+ failures.append("a diagnostic with nothing to mask was not printed as it stands")
3929
+
3930
+ # ---- the remembered answers: a rule, a home or a bound that changed is never answered from memory ----
3931
+ #
3932
+ # Each control warms the cache first and shows the warm answer CAME from it (a hit counted), so a pass is
3933
+ # not the verifier answering where the cache should have been asked.
3934
+ def asked_twice(text, home=None):
3935
+ """The answer asked once and again, and whether the second ask was answered from the cache."""
3936
+ first = discloses(text, home)
3937
+ hits = DISCLOSES_CACHE_STATS["hits"]
3938
+ second = discloses(text, home)
3939
+ return first, second, DISCLOSES_CACHE_STATS["hits"] == hits + 1
3940
+
3941
+ planted_text = "zq7 a value only a planted floor pattern names 0123456789"
3942
+ cold, warm, hit = asked_twice(planted_text, owner)
3943
+ FLOOR.SECRET_RE.append(re.compile(r"zq7 a value only a planted floor pattern names"))
3944
+ try:
3945
+ planted_answer = discloses(planted_text, owner)
3946
+ finally:
3947
+ FLOOR.SECRET_RE.pop()
3948
+ restored_answer = discloses(planted_text, owner)
3949
+ if (cold, warm, hit, planted_answer, restored_answer) != (None, None, True, "floor", None):
3950
+ failures.append(f"a warm cache answers a floor pattern planted in place after it: cold={cold!r} warm={warm!r} "
3951
+ f"hit={hit} planted={planted_answer!r} restored={restored_answer!r}")
3952
+
3953
+ member_text = '{"zq7plainname": "a plain value"}'
3954
+ cold, warm, hit = asked_twice(member_text, owner)
3955
+ kept_secret_key = globals()["secret_key"]
3956
+ globals()["secret_key"] = lambda name: True
3957
+ try:
3958
+ replaced_answer = discloses(member_text, owner)
3959
+ finally:
3960
+ globals()["secret_key"] = kept_secret_key
3961
+ restored_answer = discloses(member_text, owner)
3962
+ if (cold, warm, hit, replaced_answer, restored_answer) != (None, None, True, "secret-named key", None):
3963
+ failures.append(f"a warm cache answers a secret_key replaced after it: cold={cold!r} warm={warm!r} hit={hit} "
3964
+ f"replaced={replaced_answer!r} restored={restored_answer!r}")
3965
+
3966
+ # a helper the verifier reaches only through another one: `vf_unescape`, through `every_spelling`
3967
+ deep_text = "zq7 nothing here to unescape"
3968
+ cold, warm, hit = asked_twice(deep_text, owner)
3969
+ kept_unescape = globals()["vf_unescape"]
3970
+ globals()["vf_unescape"] = lambda text: f"api_key={_PROBE}"
3971
+ try:
3972
+ deep_answer = discloses(deep_text, owner)
3973
+ finally:
3974
+ globals()["vf_unescape"] = kept_unescape
3975
+ restored_answer = discloses(deep_text, owner)
3976
+ if (cold, warm, hit, deep_answer, restored_answer) != (None, None, True, "floor", None):
3977
+ failures.append(f"a warm cache answers a helper replaced two calls below the verifier: cold={cold!r} "
3978
+ f"warm={warm!r} hit={hit} replaced={deep_answer!r} restored={restored_answer!r}")
3979
+
3980
+ home_a, home_b = "/opt/zq7-home-a", "/opt/zq7-home-b"
3981
+ home_text = f"read {home_a}/notes"
3982
+ a_cold, a_warm, a_hit = asked_twice(home_text, home_a)
3983
+ b_answer = discloses(home_text, home_b)
3984
+ kept_home = os.environ.get("HOME")
3985
+ try:
3986
+ os.environ["HOME"] = home_a
3987
+ env_a, env_a_again, env_a_hit = asked_twice(home_text)
3988
+ os.environ["HOME"] = home_b
3989
+ env_b = discloses(home_text)
3990
+ finally:
3991
+ if kept_home is None:
3992
+ os.environ.pop("HOME", None)
3993
+ else:
3994
+ os.environ["HOME"] = kept_home
3995
+ if (a_cold, a_warm, a_hit, b_answer, env_a, env_a_again, env_a_hit, env_b) != (
3996
+ "home path", "home path", True, None, "home path", "home path", True, None):
3997
+ failures.append(f"a warm cache answers each home with its own answer, and an unnamed home as HOME stands: "
3998
+ f"a={a_cold!r}/{a_warm!r} hit={a_hit} b={b_answer!r} HOME=a {env_a!r}/{env_a_again!r} "
3999
+ f"hit={env_a_hit} HOME=b {env_b!r}")
4000
+
4001
+ kept_max = DISCLOSES_CACHE_MAX
4002
+ bound_texts = [f"zq7 bound probe {n}" for n in range(7)]
4003
+ with _DISCLOSES_LOCK:
4004
+ size_before, evicted_before = len(_DISCLOSES_CACHE), DISCLOSES_CACHE_STATS["evicted"]
4005
+ try:
4006
+ globals()["DISCLOSES_CACHE_MAX"] = 4
4007
+ bound_answers = [discloses(text, owner) for text in bound_texts]
4008
+ with _DISCLOSES_LOCK:
4009
+ size_bounded, evicted = len(_DISCLOSES_CACHE), DISCLOSES_CACHE_STATS["evicted"] - evicted_before
4010
+ misses = DISCLOSES_CACHE_STATS["misses"]
4011
+ again = discloses(bound_texts[0], owner)
4012
+ again_missed = DISCLOSES_CACHE_STATS["misses"] == misses + 1
4013
+ finally:
4014
+ globals()["DISCLOSES_CACHE_MAX"] = kept_max
4015
+ with _DISCLOSES_LOCK:
4016
+ size_after = len(_DISCLOSES_CACHE)
4017
+ if (size_bounded != 4 or evicted != size_before + len(bound_texts) - 4 or again != bound_answers[0]
4018
+ or not again_missed or size_after > DISCLOSES_CACHE_MAX):
4019
+ failures.append(f"the cache holds at most its bound, forgetting the oldest: size={size_bounded} of 4, "
4020
+ f"evicted={evicted} of {size_before + len(bound_texts) - 4}, the forgotten asked again "
4021
+ f"missed={again_missed} same={again == bound_answers[0]}, then {size_after} of "
4022
+ f"{DISCLOSES_CACHE_MAX}")
4023
+
4024
+ # every rule the key compares is a value that cannot change in place - a dict or set changed in place
4025
+ # would compare equal to itself and keep an answer computed under its old contents - and no reached
4026
+ # function looks a name up by its string, which the derivation cannot follow
4027
+ def immutable_rule(value):
4028
+ if isinstance(value, tuple):
4029
+ return all(immutable_rule(item) for item in value)
4030
+ # A path is a value object with no public mutator: `FLOOR_PATH`, which the verifier's refusal names,
4031
+ # is one, and without it here this control would refuse today's verifier for a value that cannot change.
4032
+ return value is None or isinstance(value, (types.FunctionType, types.BuiltinFunctionType, type,
4033
+ types.ModuleType, re.Pattern, pathlib.PurePath, str, bytes,
4034
+ int, float, range, frozenset))
4035
+
4036
+ def code_names(code):
4037
+ names, codes = set(), [code]
4038
+ while codes:
4039
+ here = codes.pop()
4040
+ names |= set(here.co_names)
4041
+ codes += [constant for constant in here.co_consts if isinstance(constant, types.CodeType)]
4042
+ return names
4043
+
4044
+ helper_values, floor_values = disclosure_rules()
4045
+ mutable = [f"{name} ({type(value).__name__})" for name, value in zip(DISCLOSURE_RULE_NAMES, helper_values)
4046
+ if not immutable_rule(value)]
4047
+ mutable += [f"FLOOR.{name} ({type(value).__name__})" for name, value in floor_values if not immutable_rule(value)]
4048
+ by_string = sorted(name for name, value in zip(DISCLOSURE_RULE_NAMES, helper_values)
4049
+ if isinstance(value, types.FunctionType)
4050
+ and code_names(value.__code__) & {"globals", "vars", "eval", "exec"})
4051
+ if mutable or by_string or len(DISCLOSURE_RULE_NAMES) < 2 or not floor_values:
4052
+ failures.append(f"every rule the cache compares is immutable and reached by name: mutable={mutable} "
4053
+ f"looked up by string={by_string} names={len(DISCLOSURE_RULE_NAMES)} "
4054
+ f"floor members={len(floor_values)}")
4055
+
4056
+ for failure in failures:
4057
+ print(f"projection --self-test [FAIL] {failure}")
4058
+ if failures:
4059
+ return 1
4060
+ print(f"projection --self-test: OK ({len(document_shapes)} decoded-document shapes judged through the one "
4061
+ f"entry point in both representations, {len(secrets)} secret shapes and {len(paths)} home-path shapes masked and "
4062
+ f"idempotent, {len(structured)} structured and JSON-keyed shapes masked (keyed secrets, nested, in a list, "
4063
+ f"a non-string value, a Windows path through a tool argument and through escaped text), "
4064
+ f"{len(kept) + len(structured_kept)} look-alikes untouched, three escape sequences read as boundaries, the "
4065
+ f"owner's own home masked through prose, a relative prefix and a diff prefix, its longer-name look-alike "
4066
+ f"kept, the floor's key names read from the floor and an unreadable floor named, a block's characters, "
4067
+ f"versions, ONE monotone masking pass in the original text's own coordinates ({generated} seeded "
4068
+ f"cases over fourteen classes, each asserted to have made the transformation it advertises and judged "
4069
+ f"by decoding the output independently at every depth: {class_counts}), the oracle "
4070
+ f"proven on deliberately partial masks and carrying a positive case for every floor pattern, the "
4071
+ f"differential over the whole fixture corpus (whatever the unchanged floor masks, the "
4072
+ f"projection masks at least as much, and somewhere it masks more), and the sweep over a fixture run directory - a planted member found in a record and in a "
4073
+ f"pretty-printed window, every quoting its masker writes recognised, an index judged only for its "
4074
+ f"shape, and an unreadable record, an unreadable document and an empty subject set each refused, and "
4075
+ f"the remembered verifier answers asked again after a floor pattern, a helper, a home and the bound "
4076
+ f"each changed under a warm cache)")
4077
+ return 0
4078
+
4079
+
4080
+ # The names the verifier reaches, derived here rather than beside the cache: every name exists by now, so a
4081
+ # helper defined below the verifier cannot be missed for not existing yet.
4082
+ DISCLOSURE_RULE_NAMES = _reached_names("discloses_uncached")
4083
+
4084
+
4085
+ if __name__ == "__main__":
4086
+ if "--self-test" in sys.argv[1:]:
4087
+ sys.exit(self_test())
4088
+ if len(sys.argv) == 3 and sys.argv[1] == "--sweep":
4089
+ sys.exit(report_sweep(sys.argv[2]))
4090
+ sys.exit("usage: projection.py --self-test | --sweep <run-dir>")