secretscreen 0.3.0__tar.gz → 0.4.0__tar.gz

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 (40) hide show
  1. {secretscreen-0.3.0 → secretscreen-0.4.0}/.github/workflows/ci.yml +4 -1
  2. {secretscreen-0.3.0 → secretscreen-0.4.0}/.github/workflows/codeql.yml +4 -1
  3. {secretscreen-0.3.0 → secretscreen-0.4.0}/PKG-INFO +57 -3
  4. {secretscreen-0.3.0 → secretscreen-0.4.0}/README.md +56 -2
  5. {secretscreen-0.3.0 → secretscreen-0.4.0}/pyproject.toml +1 -1
  6. {secretscreen-0.3.0 → secretscreen-0.4.0}/src/secretscreen/__init__.py +1 -1
  7. {secretscreen-0.3.0 → secretscreen-0.4.0}/src/secretscreen/_cli.py +188 -15
  8. {secretscreen-0.3.0 → secretscreen-0.4.0}/src/secretscreen/_core.py +173 -2
  9. {secretscreen-0.3.0 → secretscreen-0.4.0}/src/secretscreen/_urls.py +14 -0
  10. secretscreen-0.4.0/tests/test_explain.py +255 -0
  11. {secretscreen-0.3.0 → secretscreen-0.4.0}/tests/test_urls.py +34 -0
  12. secretscreen-0.4.0/tests/test_yaml_and_prefixes.py +248 -0
  13. {secretscreen-0.3.0 → secretscreen-0.4.0}/.github/FUNDING.yml +0 -0
  14. {secretscreen-0.3.0 → secretscreen-0.4.0}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
  15. {secretscreen-0.3.0 → secretscreen-0.4.0}/.github/dependabot.yml +0 -0
  16. {secretscreen-0.3.0 → secretscreen-0.4.0}/.github/pull_request_template.md +0 -0
  17. {secretscreen-0.3.0 → secretscreen-0.4.0}/.github/workflows/dependabot-automerge.yml +0 -0
  18. {secretscreen-0.3.0 → secretscreen-0.4.0}/.github/workflows/publish.yml +0 -0
  19. {secretscreen-0.3.0 → secretscreen-0.4.0}/.github/workflows/scorecard.yml +0 -0
  20. {secretscreen-0.3.0 → secretscreen-0.4.0}/.gitignore +0 -0
  21. {secretscreen-0.3.0 → secretscreen-0.4.0}/CODE_OF_CONDUCT.md +0 -0
  22. {secretscreen-0.3.0 → secretscreen-0.4.0}/CONTRIBUTING.md +0 -0
  23. {secretscreen-0.3.0 → secretscreen-0.4.0}/LICENSE +0 -0
  24. {secretscreen-0.3.0 → secretscreen-0.4.0}/NOTICE +0 -0
  25. {secretscreen-0.3.0 → secretscreen-0.4.0}/SECURITY.md +0 -0
  26. {secretscreen-0.3.0 → secretscreen-0.4.0}/docs/audits/security-audit-2026-04-05.md +0 -0
  27. {secretscreen-0.3.0 → secretscreen-0.4.0}/src/secretscreen/_entropy.py +0 -0
  28. {secretscreen-0.3.0 → secretscreen-0.4.0}/src/secretscreen/_formats.py +0 -0
  29. {secretscreen-0.3.0 → secretscreen-0.4.0}/src/secretscreen/_keys.py +0 -0
  30. {secretscreen-0.3.0 → secretscreen-0.4.0}/src/secretscreen/_parsers.py +0 -0
  31. {secretscreen-0.3.0 → secretscreen-0.4.0}/src/secretscreen/gitleaks.toml +0 -0
  32. {secretscreen-0.3.0 → secretscreen-0.4.0}/src/secretscreen/py.typed +0 -0
  33. {secretscreen-0.3.0 → secretscreen-0.4.0}/tests/__init__.py +0 -0
  34. {secretscreen-0.3.0 → secretscreen-0.4.0}/tests/test_architecture.py +0 -0
  35. {secretscreen-0.3.0 → secretscreen-0.4.0}/tests/test_cli.py +0 -0
  36. {secretscreen-0.3.0 → secretscreen-0.4.0}/tests/test_core.py +0 -0
  37. {secretscreen-0.3.0 → secretscreen-0.4.0}/tests/test_entropy.py +0 -0
  38. {secretscreen-0.3.0 → secretscreen-0.4.0}/tests/test_formats.py +0 -0
  39. {secretscreen-0.3.0 → secretscreen-0.4.0}/tests/test_keys.py +0 -0
  40. {secretscreen-0.3.0 → secretscreen-0.4.0}/tests/test_parsers.py +0 -0
@@ -3,8 +3,11 @@ name: CI
3
3
  on:
4
4
  push:
5
5
  branches: [main]
6
+ # No `branches:` filter. Gating on the base branch means a stacked pull
7
+ # request — one opened against another feature branch — runs nothing, and
8
+ # reports only the skipped automerge job, which reads like a pass. Push is
9
+ # still limited to main so feature-branch pushes do not double-run.
6
10
  pull_request:
7
- branches: [main]
8
11
 
9
12
  concurrency:
10
13
  group: ${{ github.workflow }}-${{ github.ref }}
@@ -3,8 +3,11 @@ name: CodeQL
3
3
  on:
4
4
  push:
5
5
  branches: [main]
6
+ # No `branches:` filter. Gating on the base branch means a stacked pull
7
+ # request — one opened against another feature branch — runs nothing, and
8
+ # reports only the skipped automerge job, which reads like a pass. Push is
9
+ # still limited to main so feature-branch pushes do not double-run.
6
10
  pull_request:
7
- branches: [main]
8
11
  schedule:
9
12
  - cron: "0 6 * * 3"
10
13
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: secretscreen
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Detect and redact secrets in key-value pairs, dicts, and environment variables. Library and CLI.
5
5
  Project-URL: Homepage, https://github.com/featurecreep-cron/secretscreen
6
6
  Project-URL: Repository, https://github.com/featurecreep-cron/secretscreen
@@ -98,12 +98,66 @@ secretscreen --audit config.json # findings only, no values, exit 1 i
98
98
  ```
99
99
  secretscreen [FILE...] reads stdin when FILE is omitted or '-'
100
100
  --audit report findings without values; exit 1 if any
101
- --format env|json|ini|dsn|auto default: auto-detect from extension, then content
101
+ --format env|json|ini|yaml|dsn|auto default: auto-detect from extension, then content
102
102
  --aggressive add entropy detection; more false positives
103
+ --explain account on stderr for every value, including the untouched ones
103
104
  --replacement TEXT default: [REDACTED]
104
105
  ```
105
106
 
106
- Redaction is structural, not line-based: it parses the format, so it catches `DB_PASSWORD=hunter2` on the key name and rewrites `postgres://admin:s3cr3t@host/db` to `postgres://admin:[REDACTED]@host/db` without destroying the rest of the line. Comments, blank lines, quoting, `export` prefixes, INI sections and `:` separators all survive the round trip.
107
+ Redaction is structural, not line-based: it parses the format, so it catches `DB_PASSWORD=hunter2` on the key name and rewrites `postgres://admin:s3cr3t@host/db` to `postgres://admin:REDACTED@host/db` without destroying the rest of the line. Comments, blank lines, quoting, `export` prefixes, INI sections and `:` separators all survive the round trip.
108
+
109
+ Inside a URL the replacement drops its brackets, because `[` in that position makes the result unparseable — screening already-screened output would otherwise destroy it.
110
+
111
+ ### Compose files and grep output
112
+
113
+ ```
114
+ $ secretscreen compose.yaml
115
+ # Watchtower stack
116
+ services:
117
+ watchtower:
118
+ image: containrrr/watchtower
119
+ environment:
120
+ WATCHTOWER_NOTIFICATION_URL: discord://REDACTED@1234567890
121
+ WATCHTOWER_CLEANUP: "true"
122
+ # keep an eye on this one
123
+ restart: unless-stopped
124
+ ```
125
+
126
+ Indentation, comments, and block openers (`services:`) survive; only values are touched. List entries are screened whether they carry a key (`- DB_PASSWORD=hunter2`) or not (`- discord://token@id`).
127
+
128
+ This is **line-oriented, not a real YAML parse** — a parser would mean a third-party dependency, and this package is stdlib-only on purpose. Block scalars (`|`, `>`) are the visible consequence: their bodies are not `key: value`, so they are redacted and reported rather than quietly passed through.
129
+
130
+ grep's `file:NN:` and `file-NN-` markers are recognised and stripped before parsing, then put back on output, so `grep -rn SECRET ~/stacks | secretscreen` keeps its file-and-line context:
131
+
132
+ ```
133
+ $ grep -n 'NOTIFICATION' compose.yaml | secretscreen
134
+ secretscreen: detected grep-style line prefixes; stripped before parsing, restored on output
135
+ 6: WATCHTOWER_NOTIFICATION_URL: discord://REDACTED@1234567890
136
+ ```
137
+
138
+ That stripping is what makes colon-separated detection safe to attempt at all. Without it the first colon on the line belongs to grep's line number, the key becomes `6`, and the whole remainder — secret included — becomes one value that matches nothing. So when the input is only partly prefixed and the shape is ambiguous, the sniffer refuses the colon format and falls back to `env`, which redacts what it cannot parse. Useless output beats quiet output.
139
+
140
+ One case stays deliberately blunt: a single stream mixing formats, such as `grep -rn` across both `.env` and `.yaml` files, picks the majority format and redacts the rest wholesale. Loud and safe rather than half-parsed.
141
+
142
+ ### Knowing what was left alone
143
+
144
+ A missed secret is invisible: the output looks screened and nothing says otherwise. `--explain` writes an account of every value to **stderr**, so stdout stays a usable redacted stream and `secretscreen app.env --explain > clean.env` still works.
145
+
146
+ ```
147
+ $ secretscreen watchtower.env --explain > screened.env
148
+ secretscreen: explain — key names and reasons only, no values
149
+ redacted WATCHTOWER_NOTIFICATION_URL url_credentials credential in userinfo position
150
+ vetoed GF_OAUTH_TOKEN_URL key_pattern matched 'token', suppressed by safe suffix '_url'
151
+ clean IMAGE_DIGEST - entropy 4.14 (aggressive would not flag; threshold 4.50)
152
+ clean DEPLOY_PUBLIC_KEY - entropy 4.67 (aggressive WOULD flag; threshold 4.50)
153
+ unscanned BACKUP_BLOB - 2202009 bytes exceeds the 65536-byte scan cap
154
+ ```
155
+
156
+ Four states. `redacted` and `clean` are self-explanatory; the two in between are the ones worth reading. **`vetoed`** means a rule fired and something suppressed it — that is where the tool decided to stay quiet. **`unscanned`** means the size cap skipped the value-scanning layers.
157
+
158
+ Clean lines carry the nearest miss rather than silence. The entropy figure is computed even in normal mode, where that layer never runs, so you can see what `--aggressive` would change before turning it on.
159
+
160
+ Like `--audit`, this never prints a value — paste it into a bug report as-is.
107
161
 
108
162
  **What the exit code means:**
109
163
 
@@ -66,12 +66,66 @@ secretscreen --audit config.json # findings only, no values, exit 1 i
66
66
  ```
67
67
  secretscreen [FILE...] reads stdin when FILE is omitted or '-'
68
68
  --audit report findings without values; exit 1 if any
69
- --format env|json|ini|dsn|auto default: auto-detect from extension, then content
69
+ --format env|json|ini|yaml|dsn|auto default: auto-detect from extension, then content
70
70
  --aggressive add entropy detection; more false positives
71
+ --explain account on stderr for every value, including the untouched ones
71
72
  --replacement TEXT default: [REDACTED]
72
73
  ```
73
74
 
74
- Redaction is structural, not line-based: it parses the format, so it catches `DB_PASSWORD=hunter2` on the key name and rewrites `postgres://admin:s3cr3t@host/db` to `postgres://admin:[REDACTED]@host/db` without destroying the rest of the line. Comments, blank lines, quoting, `export` prefixes, INI sections and `:` separators all survive the round trip.
75
+ Redaction is structural, not line-based: it parses the format, so it catches `DB_PASSWORD=hunter2` on the key name and rewrites `postgres://admin:s3cr3t@host/db` to `postgres://admin:REDACTED@host/db` without destroying the rest of the line. Comments, blank lines, quoting, `export` prefixes, INI sections and `:` separators all survive the round trip.
76
+
77
+ Inside a URL the replacement drops its brackets, because `[` in that position makes the result unparseable — screening already-screened output would otherwise destroy it.
78
+
79
+ ### Compose files and grep output
80
+
81
+ ```
82
+ $ secretscreen compose.yaml
83
+ # Watchtower stack
84
+ services:
85
+ watchtower:
86
+ image: containrrr/watchtower
87
+ environment:
88
+ WATCHTOWER_NOTIFICATION_URL: discord://REDACTED@1234567890
89
+ WATCHTOWER_CLEANUP: "true"
90
+ # keep an eye on this one
91
+ restart: unless-stopped
92
+ ```
93
+
94
+ Indentation, comments, and block openers (`services:`) survive; only values are touched. List entries are screened whether they carry a key (`- DB_PASSWORD=hunter2`) or not (`- discord://token@id`).
95
+
96
+ This is **line-oriented, not a real YAML parse** — a parser would mean a third-party dependency, and this package is stdlib-only on purpose. Block scalars (`|`, `>`) are the visible consequence: their bodies are not `key: value`, so they are redacted and reported rather than quietly passed through.
97
+
98
+ grep's `file:NN:` and `file-NN-` markers are recognised and stripped before parsing, then put back on output, so `grep -rn SECRET ~/stacks | secretscreen` keeps its file-and-line context:
99
+
100
+ ```
101
+ $ grep -n 'NOTIFICATION' compose.yaml | secretscreen
102
+ secretscreen: detected grep-style line prefixes; stripped before parsing, restored on output
103
+ 6: WATCHTOWER_NOTIFICATION_URL: discord://REDACTED@1234567890
104
+ ```
105
+
106
+ That stripping is what makes colon-separated detection safe to attempt at all. Without it the first colon on the line belongs to grep's line number, the key becomes `6`, and the whole remainder — secret included — becomes one value that matches nothing. So when the input is only partly prefixed and the shape is ambiguous, the sniffer refuses the colon format and falls back to `env`, which redacts what it cannot parse. Useless output beats quiet output.
107
+
108
+ One case stays deliberately blunt: a single stream mixing formats, such as `grep -rn` across both `.env` and `.yaml` files, picks the majority format and redacts the rest wholesale. Loud and safe rather than half-parsed.
109
+
110
+ ### Knowing what was left alone
111
+
112
+ A missed secret is invisible: the output looks screened and nothing says otherwise. `--explain` writes an account of every value to **stderr**, so stdout stays a usable redacted stream and `secretscreen app.env --explain > clean.env` still works.
113
+
114
+ ```
115
+ $ secretscreen watchtower.env --explain > screened.env
116
+ secretscreen: explain — key names and reasons only, no values
117
+ redacted WATCHTOWER_NOTIFICATION_URL url_credentials credential in userinfo position
118
+ vetoed GF_OAUTH_TOKEN_URL key_pattern matched 'token', suppressed by safe suffix '_url'
119
+ clean IMAGE_DIGEST - entropy 4.14 (aggressive would not flag; threshold 4.50)
120
+ clean DEPLOY_PUBLIC_KEY - entropy 4.67 (aggressive WOULD flag; threshold 4.50)
121
+ unscanned BACKUP_BLOB - 2202009 bytes exceeds the 65536-byte scan cap
122
+ ```
123
+
124
+ Four states. `redacted` and `clean` are self-explanatory; the two in between are the ones worth reading. **`vetoed`** means a rule fired and something suppressed it — that is where the tool decided to stay quiet. **`unscanned`** means the size cap skipped the value-scanning layers.
125
+
126
+ Clean lines carry the nearest miss rather than silence. The entropy figure is computed even in normal mode, where that layer never runs, so you can see what `--aggressive` would change before turning it on.
127
+
128
+ Like `--audit`, this never prints a value — paste it into a bug report as-is.
75
129
 
76
130
  **What the exit code means:**
77
131
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "secretscreen"
7
- version = "0.3.0"
7
+ version = "0.4.0"
8
8
  description = "Detect and redact secrets in key-value pairs, dicts, and environment variables. Library and CLI."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -37,4 +37,4 @@ __all__ = [
37
37
  "redact_pair",
38
38
  ]
39
39
 
40
- __version__ = "0.3.0"
40
+ __version__ = "0.4.0"
@@ -17,6 +17,7 @@ from __future__ import annotations
17
17
 
18
18
  import argparse
19
19
  import json
20
+ import re
20
21
  import sys
21
22
  from typing import TYPE_CHECKING
22
23
 
@@ -26,6 +27,8 @@ from secretscreen._core import (
26
27
  Mode,
27
28
  audit_dict,
28
29
  audit_pair,
30
+ explain_dict,
31
+ explain_pair,
29
32
  redact_dict,
30
33
  redact_pair,
31
34
  )
@@ -33,21 +36,56 @@ from secretscreen._core import (
33
36
  if TYPE_CHECKING:
34
37
  from collections.abc import Sequence
35
38
 
36
- from secretscreen._core import Finding
39
+ from secretscreen._core import Explanation, Finding
37
40
 
38
41
  EXIT_OK = 0
39
42
  EXIT_FINDINGS = 1
40
43
  EXIT_ERROR = 2
41
44
 
42
- FORMATS = ("env", "json", "ini", "dsn", "auto")
45
+ FORMATS = ("env", "json", "ini", "yaml", "dsn", "auto")
43
46
 
44
47
  _JSON_EXTENSIONS = {".json"}
45
48
  _INI_EXTENSIONS = {".ini", ".cfg", ".conf", ".properties"}
46
49
  _ENV_EXTENSIONS = {".env", ".envrc"}
50
+ _YAML_EXTENSIONS = {".yaml", ".yml"}
51
+
52
+ # grep prefixes its output with `file:` and `line:` when given -n or several
53
+ # files. Those colons break any colon-separated format: the first ':' belongs
54
+ # to the prefix, so the key becomes a line number and the rest of the line —
55
+ # including any secret — becomes one opaque value that no layer matches.
56
+ #
57
+ # Detection is document-wide rather than per-line. A single line starting with
58
+ # digits and a colon is ambiguous (a timestamp, a port); a whole input shaped
59
+ # that way is grep output. Prefixes are stripped for detection and put back on
60
+ # output, so `file:line:` context survives into the redacted result.
61
+ # grep marks matching lines `file:NN:` and context lines `file-NN-`, mixing both
62
+ # delimiters in one stream whenever -A/-B/-C is used. Matching only the colon
63
+ # form drops the ratio below the threshold on such a stream, which skips
64
+ # stripping and lets the colon format be chosen anyway — the leak this guard
65
+ # exists to prevent. The filename may not contain whitespace, which keeps the
66
+ # pattern off ordinary content like `command: run --port 8080-9090-x`.
67
+ _GREP_PREFIX = re.compile(r"^(?:\S*?([:-])\d+\1|\d+[:-])")
68
+ _GREP_SEPARATOR = "--"
69
+ _GREP_MIN_LINES = 2
70
+ _GREP_PREFIX_RATIO = 0.8
71
+
72
+ # A YAML list entry carrying a bare value: `- prod`. There is no key, but there
73
+ # is a value, so it is scanned rather than passed through or redacted wholesale.
74
+ _YAML_LIST_ITEM = re.compile(r"^(\s*-\s+)(\S.*)$")
75
+
76
+ # Column widths for --explain output. The key column is capped so one very long
77
+ # key (a grep prefix, a deep JSON path) cannot push every reason off the screen.
78
+ _EXPLAIN_KEY_MAX_WIDTH = 44
79
+ _EXPLAIN_LAYER_WIDTH = 17
47
80
 
48
81
  # Separator characters by format, in precedence order.
49
- _SEPARATORS = {"env": ("=",), "ini": ("=", ":")}
50
- _COMMENT_PREFIXES = {"env": ("#",), "ini": ("#", ";")}
82
+ # YAML separates a mapping key from its value with a colon *and a space*.
83
+ # Splitting on a bare colon would cut `- discord://token@id` at the scheme,
84
+ # leaving `//token@id` as a value under the key `- discord` — which matches
85
+ # nothing, so the token prints. INI keeps the bare colon: `key:value` is valid
86
+ # there, and its values do not usually carry URLs.
87
+ _SEPARATORS = {"env": ("=",), "ini": ("=", ":"), "yaml": ("=", ": ")}
88
+ _COMMENT_PREFIXES = {"env": ("#",), "ini": ("#", ";"), "yaml": ("#",)}
51
89
 
52
90
 
53
91
  class _Report:
@@ -60,6 +98,8 @@ class _Report:
60
98
  def __init__(self) -> None:
61
99
  self.findings: list[tuple[str, int, Finding]] = []
62
100
  self.problems: list[str] = []
101
+ self.explanations: list[tuple[str, int, Explanation]] = []
102
+ self.notes: list[str] = []
63
103
 
64
104
  def problem(self, source: str, lineno: int, message: str) -> None:
65
105
  self.problems.append(f"{source}:{lineno}: {message}")
@@ -72,6 +112,30 @@ def _strip_quotes(value: str) -> tuple[str, str]:
72
112
  return "", value
73
113
 
74
114
 
115
+ def _split_grep_prefixes(text: str) -> list[tuple[str, str]] | None:
116
+ """Split grep-style `file:line:` prefixes off each line, or None if absent.
117
+
118
+ Returns (prefix, remainder) per line so the prefix can be reprinted while
119
+ only the remainder is parsed. The decision is made for the whole input:
120
+ one line that happens to start with digits and a colon is ambiguous, an
121
+ input where nearly every line does is grep output.
122
+ """
123
+ lines = text.splitlines()
124
+ candidates = [line for line in lines if line.strip() and line.strip() != _GREP_SEPARATOR]
125
+ if len(candidates) < _GREP_MIN_LINES:
126
+ return None
127
+
128
+ matched = sum(1 for line in candidates if _GREP_PREFIX.match(line))
129
+ if matched < len(candidates) * _GREP_PREFIX_RATIO:
130
+ return None
131
+
132
+ split: list[tuple[str, str]] = []
133
+ for line in lines:
134
+ match = _GREP_PREFIX.match(line)
135
+ split.append((match.group(0), line[match.end() :]) if match else ("", line))
136
+ return split
137
+
138
+
75
139
  def _detect_format(text: str, filename: str | None) -> str:
76
140
  """Pick a parser from the file extension, falling back to content sniffing."""
77
141
  if filename:
@@ -82,6 +146,8 @@ def _detect_format(text: str, filename: str | None) -> str:
82
146
  return "json"
83
147
  if extension in _INI_EXTENSIONS:
84
148
  return "ini"
149
+ if extension in _YAML_EXTENSIONS:
150
+ return "yaml"
85
151
  if extension in _ENV_EXTENSIONS or lowered.split("/")[-1].startswith(".env"):
86
152
  return "env"
87
153
 
@@ -92,6 +158,29 @@ def _detect_format(text: str, filename: str | None) -> str:
92
158
  bare = line.strip()
93
159
  if bare.startswith("[") and bare.endswith("]"):
94
160
  return "ini"
161
+
162
+ # Colon-separated content only after any grep prefixes have been removed.
163
+ # Sniffing before that would read grep's own `line:` as the separator and
164
+ # hand the whole remainder — secret included — to detection as one value.
165
+ body = _split_grep_prefixes(text)
166
+ if body is not None:
167
+ lines = [rest for _, rest in body]
168
+ elif any(_GREP_PREFIX.match(line) for line in text.splitlines()):
169
+ # Some lines look prefixed and not enough to strip with confidence.
170
+ # Refuse the colon format: env redacts what it cannot parse, which is
171
+ # useless but loud, and that is the right way to be wrong here.
172
+ return "env"
173
+ else:
174
+ lines = text.splitlines()
175
+ equals = colons = 0
176
+ for line in lines:
177
+ bare = line.strip()
178
+ if not bare or bare.startswith("#"):
179
+ continue
180
+ equals += "=" in bare
181
+ colons += ":" in bare and "=" not in bare.split(":", 1)[0]
182
+ if colons > equals:
183
+ return "yaml"
95
184
  return "env"
96
185
 
97
186
 
@@ -108,37 +197,76 @@ def _process_lines(text: str, fmt: str, source: str, args: argparse.Namespace, r
108
197
  comments = _COMMENT_PREFIXES[fmt]
109
198
  out: list[str] = []
110
199
 
111
- for lineno, raw in enumerate(text.splitlines(), 1):
200
+ rows = _split_grep_prefixes(text)
201
+ if rows is None:
202
+ rows = [("", line) for line in text.splitlines()]
203
+ elif any(prefix for prefix, _ in rows):
204
+ report.notes.append("detected grep-style line prefixes; stripped before parsing, restored on output")
205
+
206
+ for lineno, (prefix, raw) in enumerate(rows, 1):
112
207
  stripped = raw.strip()
113
208
 
114
- if not stripped or stripped.startswith(comments):
115
- out.append(raw)
209
+ # Comments and blanks are judged after the grep prefix is removed.
210
+ # `compose.yaml:24:# note` does not start with '#', which is why piped
211
+ # comments used to be redacted while the same file read directly was fine.
212
+ if not stripped or stripped.startswith(comments) or stripped == _GREP_SEPARATOR:
213
+ out.append(prefix + raw)
116
214
  continue
117
215
 
118
- if fmt == "ini" and stripped.startswith("[") and stripped.endswith("]"):
119
- out.append(raw)
216
+ if fmt in ("ini", "yaml") and stripped.startswith("[") and stripped.endswith("]"):
217
+ out.append(prefix + raw)
120
218
  continue
121
219
 
122
- positions = [raw.find(sep) for sep in separators if raw.find(sep) != -1]
123
- if not positions:
220
+ # `services:` opens a block. There is no value slot on the line, so
221
+ # there is nothing to screen and nothing to vouch for.
222
+ if fmt == "yaml" and stripped.endswith(":"):
223
+ out.append(prefix + raw)
224
+ continue
225
+
226
+ found = [(raw.find(sep), sep) for sep in separators if raw.find(sep) != -1]
227
+ if not found:
228
+ # A YAML list entry has a value but no key, so it is scanned as one
229
+ # rather than redacted for lacking a separator it was never going
230
+ # to have.
231
+ item = _YAML_LIST_ITEM.match(raw) if fmt == "yaml" else None
232
+ if item is not None:
233
+ marker, content = item.group(1), item.group(2)
234
+ redacted, unscanned = _redact_value("", content, args.mode, args.replacement)
235
+ if args.explain:
236
+ report.explanations.append((source, lineno, explain_pair("", content, mode=args.mode)))
237
+ if args.audit:
238
+ finding = audit_pair("", content, mode=args.mode)
239
+ if finding is not None:
240
+ report.findings.append((source, lineno, finding))
241
+ continue
242
+ if unscanned:
243
+ report.problem(source, lineno, f"value exceeds the {_MAX_DETECT_LENGTH}-byte scan cap; not scanned")
244
+ out.append(f"{prefix}{marker}{redacted}")
245
+ continue
246
+
124
247
  # Structurally unparseable. Redact rather than echo it — an unparsed
125
248
  # line is exactly the one we cannot vouch for.
126
249
  report.problem(source, lineno, "no key=value separator; line redacted unscanned")
127
250
  out.append(args.replacement)
128
251
  continue
129
252
 
130
- split_at = min(positions)
131
- separator = raw[split_at] # preserve ':' vs '=' rather than normalising
253
+ # preserve the separator as written rather than normalising it
254
+ split_at, separator = min(found)
132
255
  # `left` is echoed verbatim so that spacing and any `export ` prefix survive
133
256
  # the round trip; only the detection key is normalised.
134
- left, value = raw[:split_at], raw[split_at + 1 :]
257
+ left, value = raw[:split_at], raw[split_at + len(separator) :]
135
258
  key = left.strip()
136
259
  if fmt == "env" and key.startswith("export "):
137
260
  key = key[len("export ") :].strip()
261
+ if fmt == "yaml" and key.startswith("- "):
262
+ key = key[2:].strip()
138
263
 
139
264
  quote, inner = _strip_quotes(value.strip())
140
265
  leading = value[: len(value) - len(value.lstrip())]
141
266
 
267
+ if args.explain:
268
+ report.explanations.append((source, lineno, explain_pair(key, inner, mode=args.mode)))
269
+
142
270
  if args.audit:
143
271
  finding = audit_pair(key, inner, mode=args.mode)
144
272
  if finding is not None:
@@ -150,7 +278,7 @@ def _process_lines(text: str, fmt: str, source: str, args: argparse.Namespace, r
150
278
  redacted, unscanned = _redact_value(key, inner, args.mode, args.replacement)
151
279
  if unscanned:
152
280
  report.problem(source, lineno, f"value exceeds the {_MAX_DETECT_LENGTH}-byte scan cap; not scanned")
153
- out.append(f"{left}{separator}{leading}{quote}{redacted}{quote}")
281
+ out.append(f"{prefix}{left}{separator}{leading}{quote}{redacted}{quote}")
154
282
 
155
283
  return out
156
284
 
@@ -163,6 +291,10 @@ def _process_json(text: str, source: str, args: argparse.Namespace, report: _Rep
163
291
  report.problem(source, exc.lineno, f"invalid JSON ({exc.msg}); nothing printed")
164
292
  return []
165
293
 
294
+ if args.explain:
295
+ for explanation in explain_dict(data, mode=args.mode):
296
+ report.explanations.append((source, 0, explanation))
297
+
166
298
  if args.audit:
167
299
  for finding in audit_dict(data, mode=args.mode):
168
300
  report.findings.append((source, 0, finding))
@@ -179,6 +311,8 @@ def _process_dsn(text: str, source: str, args: argparse.Namespace, report: _Repo
179
311
  if not raw.strip():
180
312
  out.append(raw)
181
313
  continue
314
+ if args.explain:
315
+ report.explanations.append((source, lineno, explain_pair("dsn", raw.strip(), mode=args.mode)))
182
316
  if args.audit:
183
317
  finding = audit_pair("dsn", raw.strip(), mode=args.mode)
184
318
  if finding is not None:
@@ -203,6 +337,35 @@ def _read(path: str, report: _Report) -> str | None:
203
337
  return None
204
338
 
205
339
 
340
+ def _print_explanations(report: _Report) -> None:
341
+ """Write the accounting to stderr so stdout stays a usable redacted stream.
342
+
343
+ Location is shown only when more than one input contributed, so the common
344
+ single-file case stays readable.
345
+ """
346
+ if not report.explanations:
347
+ return
348
+
349
+ print("secretscreen: explain — key names and reasons only, no values", file=sys.stderr)
350
+
351
+ sources = {source for source, _, _ in report.explanations}
352
+ show_location = len(sources) > 1
353
+ labels = [
354
+ f"{source}:{lineno}" if show_location and lineno else source if show_location else ""
355
+ for source, lineno, _ in report.explanations
356
+ ]
357
+
358
+ state_width = max(len(e.state) for _, _, e in report.explanations)
359
+ key_width = min(max(len(e.key) for _, _, e in report.explanations), _EXPLAIN_KEY_MAX_WIDTH)
360
+ label_width = max((len(label) for label in labels), default=0)
361
+
362
+ for label, (_, _, explanation) in zip(labels, report.explanations, strict=True):
363
+ prefix = f"{label:<{label_width}} " if show_location else ""
364
+ layer = explanation.layer or "-"
365
+ columns = f"{explanation.state:<{state_width}} {explanation.key:<{key_width}} {layer:<{_EXPLAIN_LAYER_WIDTH}}"
366
+ print(f" {prefix}{columns} {explanation.reason}", file=sys.stderr)
367
+
368
+
206
369
  def _build_parser() -> argparse.ArgumentParser:
207
370
  parser = argparse.ArgumentParser(
208
371
  prog="secretscreen",
@@ -214,6 +377,11 @@ def _build_parser() -> argparse.ArgumentParser:
214
377
  parser.add_argument("--audit", action="store_true", help="report findings without values; exit 1 if any are found")
215
378
  parser.add_argument("--format", choices=FORMATS, default="auto", help="input format (default: auto-detect)")
216
379
  parser.add_argument("--aggressive", action="store_true", help="add entropy detection; more false positives")
380
+ parser.add_argument(
381
+ "--explain",
382
+ action="store_true",
383
+ help="report on stderr what happened to every value and why, including the ones left alone",
384
+ )
217
385
  parser.add_argument("--replacement", default=REDACTED, help=f"replacement text (default: {REDACTED})")
218
386
  return parser
219
387
 
@@ -251,6 +419,11 @@ def main(argv: Sequence[str] | None = None) -> int:
251
419
  for line in lines:
252
420
  print(line)
253
421
 
422
+ for note in dict.fromkeys(report.notes):
423
+ print(f"secretscreen: {note}", file=sys.stderr)
424
+
425
+ _print_explanations(report)
426
+
254
427
  for problem in report.problems:
255
428
  print(f"secretscreen: {problem}", file=sys.stderr)
256
429