stackdoctor-cli 1.0.1__py3-none-any.whl

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. stackdoctor/__init__.py +15 -0
  2. stackdoctor/__main__.py +6 -0
  3. stackdoctor/agent/__init__.py +5 -0
  4. stackdoctor/agent/compaction.py +66 -0
  5. stackdoctor/agent/diagnosis.py +398 -0
  6. stackdoctor/agent/loop.py +801 -0
  7. stackdoctor/agent/prompts.py +85 -0
  8. stackdoctor/agent/providers/__init__.py +295 -0
  9. stackdoctor/agent/providers/base.py +210 -0
  10. stackdoctor/agent/providers/claude.py +285 -0
  11. stackdoctor/agent/providers/gemini.py +312 -0
  12. stackdoctor/agent/providers/openai_compat.py +537 -0
  13. stackdoctor/agent/providers/prices.py +90 -0
  14. stackdoctor/benchmark/__init__.py +11 -0
  15. stackdoctor/benchmark/__main__.py +198 -0
  16. stackdoctor/benchmark/holmes.py +386 -0
  17. stackdoctor/benchmark/report.py +362 -0
  18. stackdoctor/benchmark/runner.py +710 -0
  19. stackdoctor/benchmark/scenarios.py +153 -0
  20. stackdoctor/benchmark/scoring.py +184 -0
  21. stackdoctor/cli.py +882 -0
  22. stackdoctor/dependencies.py +221 -0
  23. stackdoctor/discovery.py +361 -0
  24. stackdoctor/evidence.py +134 -0
  25. stackdoctor/github.py +168 -0
  26. stackdoctor/live.py +808 -0
  27. stackdoctor/mcp_server.py +233 -0
  28. stackdoctor/models.py +275 -0
  29. stackdoctor/pglog.py +55 -0
  30. stackdoctor/postgres.py +294 -0
  31. stackdoctor/probes.py +172 -0
  32. stackdoctor/py.typed +0 -0
  33. stackdoctor/redaction.py +215 -0
  34. stackdoctor/rules.py +303 -0
  35. stackdoctor/validation.py +61 -0
  36. stackdoctor_cli-1.0.1.dist-info/METADATA +177 -0
  37. stackdoctor_cli-1.0.1.dist-info/RECORD +40 -0
  38. stackdoctor_cli-1.0.1.dist-info/WHEEL +4 -0
  39. stackdoctor_cli-1.0.1.dist-info/entry_points.txt +3 -0
  40. stackdoctor_cli-1.0.1.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,294 @@
1
+ """PostgreSQL configuration rules (SD106-SD108).
2
+
3
+ They model the official `postgres` image: on first start, with an empty data
4
+ directory, its entrypoint creates the superuser ``POSTGRES_USER`` (default
5
+ ``postgres``) with ``POSTGRES_PASSWORD`` and the database ``POSTGRES_DB``
6
+ (default: the user name). These variables are ignored once the data directory
7
+ is initialized, so a configuration that matches can still fail at runtime
8
+ when an existing volume was created with other values. The live checks catch
9
+ that case from the server's own log messages.
10
+
11
+ Clients are found in two forms:
12
+
13
+ - a connection URL to a PostgreSQL service
14
+ (``postgres://user:password@db:5432/name``);
15
+ - a ``<P>_HOST`` variable naming a PostgreSQL service, with optional
16
+ ``<P>_USER`` / ``<P>_PASSWORD`` / ``<P>_NAME`` siblings
17
+ (``DB_HOST=db``, ``DB_PASSWORD=...``).
18
+
19
+ Passwords are compared only through `Service.secret_labels`, which discovery
20
+ assigns before redaction; no rule ever sees a password.
21
+ """
22
+
23
+ import re
24
+ from collections.abc import Iterable
25
+ from dataclasses import dataclass
26
+
27
+ from stackdoctor.dependencies import find_host_references
28
+ from stackdoctor.evidence import make_evidence
29
+ from stackdoctor.models import ComposeProject, EvidenceRef, Finding, Service, Severity
30
+ from stackdoctor.redaction import REDACTED
31
+
32
+ POSTGRES_IMAGE = re.compile(r"(^|/)postgres([:@]|$)")
33
+ DEFAULT_USER = "postgres"
34
+
35
+ _URL_PARTS = re.compile(
36
+ r"^(?P<scheme>postgres(?:ql)?)://(?:(?P<user>[^:@/\s]*)(?::[^@/\s]*)?@)?"
37
+ r"[^/?#\s]*(?:/(?P<database>[^/?#\s]*))?",
38
+ re.IGNORECASE,
39
+ )
40
+ _HOST_SUFFIX = re.compile(r"_(?:HOST|ADDR|ADDRESS)$", re.IGNORECASE)
41
+ _USER_SUFFIXES = ("USER", "USERNAME")
42
+ _PASSWORD_SUFFIXES = ("PASSWORD", "PASS", "PASSWD", "PWD")
43
+ _DATABASE_SUFFIXES = ("NAME", "DB", "DATABASE", "DBNAME")
44
+
45
+
46
+ def is_postgres(service: Service) -> bool:
47
+ """Whether the service runs the official PostgreSQL image (by name)."""
48
+ return bool(service.image and POSTGRES_IMAGE.search(service.image))
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class Client:
53
+ """How one service connects to one PostgreSQL service."""
54
+
55
+ source: str
56
+ target: str
57
+ via: str # the URL or *_HOST variable
58
+ user: str | None
59
+ user_variable: str | None # None when the user is part of the URL
60
+ password_variable: str | None
61
+ database: str | None
62
+ database_variable: str | None
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Server:
67
+ """What the PostgreSQL service is configured to create."""
68
+
69
+ service: Service
70
+
71
+ @property
72
+ def user(self) -> str:
73
+ return self.service.environment.get("POSTGRES_USER") or DEFAULT_USER
74
+
75
+ @property
76
+ def database(self) -> str:
77
+ return self.service.environment.get("POSTGRES_DB") or self.user
78
+
79
+ def has(self, variable: str) -> bool:
80
+ return self.service.environment.get(variable) is not None
81
+
82
+ @property
83
+ def password_label(self) -> str | None:
84
+ return self.service.secret_labels.get("POSTGRES_PASSWORD")
85
+
86
+ @property
87
+ def sets_auth_method(self) -> bool:
88
+ # The value (trust, md5, ...) is redacted, because the key contains
89
+ # "auth"; any value means the default password check may not apply.
90
+ return bool(self.service.environment.get("POSTGRES_HOST_AUTH_METHOD"))
91
+
92
+
93
+ def find_clients(project: ComposeProject) -> list[Client]:
94
+ """Every connection from a service to a PostgreSQL service."""
95
+ services = {service.name: service for service in project.services}
96
+ clients = []
97
+ for ref in find_host_references(project.services):
98
+ target = services.get(ref.target or "")
99
+ if target is None or ref.target == ref.source or not is_postgres(target):
100
+ continue
101
+ source = services[ref.source]
102
+ value = source.environment.get(ref.variable) or ""
103
+ url = _URL_PARTS.match(value)
104
+ if url:
105
+ clients.append(
106
+ Client(
107
+ source=ref.source,
108
+ target=target.name,
109
+ via=ref.variable,
110
+ # Redaction removes a user given without a password (it may
111
+ # be a token); the user is then unknown.
112
+ user=url["user"] if url["user"] and url["user"] != REDACTED else None,
113
+ user_variable=None,
114
+ password_variable=ref.variable
115
+ if ref.variable in source.secret_labels
116
+ else None,
117
+ database=url["database"] or None,
118
+ database_variable=None,
119
+ )
120
+ )
121
+ elif ref.scheme is None and _HOST_SUFFIX.search(ref.variable):
122
+ prefix = _HOST_SUFFIX.sub("", ref.variable)
123
+ user_variable = _sibling(source, prefix, _USER_SUFFIXES)
124
+ database_variable = _sibling(source, prefix, _DATABASE_SUFFIXES)
125
+ clients.append(
126
+ Client(
127
+ source=ref.source,
128
+ target=target.name,
129
+ via=ref.variable,
130
+ user=source.environment.get(user_variable) if user_variable else None,
131
+ user_variable=user_variable,
132
+ password_variable=_sibling(source, prefix, _PASSWORD_SUFFIXES),
133
+ database=source.environment.get(database_variable)
134
+ if database_variable
135
+ else None,
136
+ database_variable=database_variable,
137
+ )
138
+ )
139
+ return clients
140
+
141
+
142
+ # --- SD106 -------------------------------------------------------------------------
143
+
144
+
145
+ def credential_mismatch(project: ComposeProject) -> Iterable[Finding]:
146
+ """SD106: a client's user or password differs from what PostgreSQL creates."""
147
+ services = {service.name: service for service in project.services}
148
+ for client in find_clients(project):
149
+ server = Server(services[client.target])
150
+ if client.user and client.user != server.user:
151
+ yield Finding(
152
+ rule_id="SD106",
153
+ severity=Severity.WARNING,
154
+ title=f"{client.source} logs in to {client.target} as an unknown user",
155
+ message=(
156
+ f'{client.source} connects to {client.target} as "{client.user}", but '
157
+ f'{client.target} only creates the user "{server.user}". The login fails '
158
+ "unless an init script or an earlier setup created that user."
159
+ ),
160
+ service=client.source,
161
+ hint=f'Use the user "{server.user}", or set POSTGRES_USER on {client.target}.',
162
+ evidence=(
163
+ _client_evidence(project, client, client.user_variable),
164
+ _server_evidence(project, server, "POSTGRES_USER"),
165
+ ),
166
+ )
167
+ continue
168
+ if server.sets_auth_method or server.has("POSTGRES_PASSWORD_FILE"):
169
+ continue # another auth method, or the password is not visible
170
+ password_variable = client.password_variable
171
+ if password_variable is None:
172
+ continue
173
+ client_label = services[client.source].secret_labels.get(password_variable)
174
+ server_label = server.password_label
175
+ if client_label is None or server_label is None or client_label == server_label:
176
+ continue
177
+ yield Finding(
178
+ rule_id="SD106",
179
+ severity=Severity.ERROR,
180
+ title=f"{client.source} uses a different password than {client.target}",
181
+ message=(
182
+ f"{password_variable} in {client.source} and POSTGRES_PASSWORD in "
183
+ f"{client.target} hold different values (compared without revealing them), "
184
+ f'so logging in as "{server.user}" fails with "password authentication '
185
+ 'failed".'
186
+ ),
187
+ service=client.source,
188
+ hint=(
189
+ f"Use the same value in both places, for example one variable from an "
190
+ f"env_file. Note that {client.target} only applies POSTGRES_PASSWORD when its "
191
+ "data directory is first initialized."
192
+ ),
193
+ evidence=(
194
+ make_evidence(
195
+ project, "services", client.source, "secret_labels", password_variable
196
+ ),
197
+ make_evidence(
198
+ project, "services", client.target, "secret_labels", "POSTGRES_PASSWORD"
199
+ ),
200
+ ),
201
+ )
202
+
203
+
204
+ # --- SD107 -------------------------------------------------------------------------
205
+
206
+
207
+ def missing_superuser_password(project: ComposeProject) -> Iterable[Finding]:
208
+ """SD107: the postgres image has no password and no alternative, so it cannot initialize."""
209
+ for service in project.services:
210
+ if not is_postgres(service):
211
+ continue
212
+ password = service.environment.get("POSTGRES_PASSWORD")
213
+ alternatives = ("POSTGRES_PASSWORD_FILE", "POSTGRES_HOST_AUTH_METHOD")
214
+ if password or any(service.environment.get(v) for v in alternatives):
215
+ continue
216
+ empty = password == ""
217
+ declared = "POSTGRES_PASSWORD" in service.environment
218
+ yield Finding(
219
+ rule_id="SD107",
220
+ severity=Severity.WARNING,
221
+ title=f"{service.name} has {'an empty' if empty else 'no'} superuser password",
222
+ message=(
223
+ f"POSTGRES_PASSWORD is {'empty' if empty else 'not set'} on {service.name}. "
224
+ "With an empty data directory, the postgres image refuses to initialize "
225
+ '("superuser password is not specified") and the container exits. An '
226
+ "already-initialized data volume still starts."
227
+ ),
228
+ service=service.name,
229
+ hint=(
230
+ "Set POSTGRES_PASSWORD (check that the variable it is interpolated from is set), "
231
+ "or use POSTGRES_PASSWORD_FILE."
232
+ ),
233
+ evidence=(
234
+ make_evidence(project, "services", service.name, "environment", "POSTGRES_PASSWORD")
235
+ if declared
236
+ else make_evidence(project, "services", service.name, "environment"),
237
+ ),
238
+ )
239
+
240
+
241
+ # --- SD108 -------------------------------------------------------------------------
242
+
243
+
244
+ def database_mismatch(project: ComposeProject) -> Iterable[Finding]:
245
+ """SD108: a client asks for a database PostgreSQL does not create."""
246
+ services = {service.name: service for service in project.services}
247
+ for client in find_clients(project):
248
+ server = Server(services[client.target])
249
+ if not client.database or client.database == server.database:
250
+ continue
251
+ if client.user and client.user != server.user:
252
+ continue # SD106 already reports the unknown user
253
+ yield Finding(
254
+ rule_id="SD108",
255
+ severity=Severity.WARNING,
256
+ title=f'{client.target} does not create the database "{client.database}"',
257
+ message=(
258
+ f'{client.source} connects to the database "{client.database}", but '
259
+ f'{client.target} only creates "{server.database}". The connection fails '
260
+ '("database does not exist") unless an init script creates it.'
261
+ ),
262
+ service=client.source,
263
+ hint=(f'Use the database "{server.database}", or set POSTGRES_DB on {client.target}.'),
264
+ evidence=(
265
+ _client_evidence(project, client, client.database_variable),
266
+ _server_evidence(project, server, "POSTGRES_DB"),
267
+ ),
268
+ )
269
+
270
+
271
+ RULES = (credential_mismatch, missing_superuser_password, database_mismatch)
272
+
273
+
274
+ # --- Helpers -----------------------------------------------------------------------
275
+
276
+
277
+ def _sibling(service: Service, prefix: str, suffixes: tuple[str, ...]) -> str | None:
278
+ """The `<prefix>_<suffix>` variable of the service, in any case."""
279
+ wanted = {f"{prefix}_{suffix}".upper() for suffix in suffixes}
280
+ return next((name for name in sorted(service.environment) if name.upper() in wanted), None)
281
+
282
+
283
+ def _client_evidence(project: ComposeProject, client: Client, variable: str | None) -> EvidenceRef:
284
+ # The value is in the URL itself, or in the sibling variable.
285
+ return make_evidence(project, "services", client.source, "environment", variable or client.via)
286
+
287
+
288
+ def _server_evidence(project: ComposeProject, server: Server, variable: str) -> EvidenceRef:
289
+ # The default applies when the variable is not set; cite the whole
290
+ # environment, which shows that it is missing.
291
+ name = server.service.name
292
+ if server.has(variable):
293
+ return make_evidence(project, "services", name, "environment", variable)
294
+ return make_evidence(project, "services", name, "environment")
stackdoctor/probes.py ADDED
@@ -0,0 +1,172 @@
1
+ """Network probes run from inside a project's networks (`validate --live --probe`).
2
+
3
+ A probe is a short-lived container attached to the networks of the service
4
+ whose connections are being checked, so it resolves names the way that service
5
+ does. Probes are the only live check that creates anything: a container that is
6
+ removed when it exits, which is why they need their own flag. They are
7
+ hardened and bounded:
8
+
9
+ - `--rm`, `--read-only`, `--cap-drop ALL`, `--security-opt no-new-privileges`,
10
+ an unprivileged user (65534), and memory and process limits;
11
+ - no environment from the project, no volumes, no published ports;
12
+ - a label (`dev.stackdoctor.probe`) and a random name, and `docker rm -f` if the
13
+ probe does not finish in time;
14
+ - a digest-pinned busybox image for DNS and TCP checks (pulled if missing),
15
+ and the database service's own image for `pg_isready` (never pulled);
16
+ - host names come from the configuration, which is untrusted: only names that
17
+ look like DNS names are probed, and they are passed to a fixed script as
18
+ arguments, never interpolated into it.
19
+
20
+ `pg_isready` only asks whether the server accepts connections; it sends no
21
+ credentials. No probe logs in anywhere.
22
+ """
23
+
24
+ import contextlib
25
+ import re
26
+ import secrets
27
+ import subprocess
28
+ from collections.abc import Sequence
29
+ from dataclasses import dataclass
30
+ from pathlib import Path
31
+ from typing import Any, Literal
32
+
33
+ from stackdoctor.discovery import ComposeRunner
34
+
35
+ # busybox:1.37 (multi-arch index), looked up with
36
+ # `docker buildx imagetools inspect busybox:1.37`.
37
+ BUSYBOX_IMAGE = (
38
+ "busybox:1.37@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec"
39
+ )
40
+ PROBE_LABEL = "dev.stackdoctor.probe"
41
+ MAX_PROBE_CONTAINERS = 20
42
+ PROBE_TIMEOUT_SECONDS = 60.0
43
+
44
+ HARDENING = (
45
+ "--rm",
46
+ "--read-only",
47
+ "--cap-drop",
48
+ "ALL",
49
+ "--security-opt",
50
+ "no-new-privileges",
51
+ "--user",
52
+ "65534:65534",
53
+ "--memory",
54
+ "32m",
55
+ "--pids-limit",
56
+ "32",
57
+ "--label",
58
+ f"{PROBE_LABEL}=1",
59
+ )
60
+
61
+ # Arguments come in pairs: a host and a port ("-" for none). The script is fixed.
62
+ # busybox nslookup exits 1 when any search-domain variant of a name fails, even
63
+ # if the name itself resolved (hosts with a DNS search domain, such as cloud
64
+ # VMs, copy it into containers). So the absolute name ("db.") is tried first,
65
+ # and the plain name, which goes through the search list, only as a fallback.
66
+ DNS_TCP_SCRIPT = (
67
+ 'while [ "$#" -ge 2 ]; do h="$1"; p="$2"; shift 2; '
68
+ 'if timeout 5 nslookup "$h." >/dev/null 2>&1 || timeout 5 nslookup "$h" >/dev/null 2>&1; '
69
+ 'then echo "dns $h ok"; '
70
+ 'if [ "$p" != "-" ]; then '
71
+ 'if nc -z -w 3 "$h" "$p" >/dev/null 2>&1; then echo "tcp $h $p open"; '
72
+ 'else echo "tcp $h $p fail"; fi; fi; '
73
+ 'else echo "dns $h fail"; fi; done'
74
+ )
75
+
76
+ _PROBE_HOST = re.compile(r"^[a-z0-9_](?:[a-z0-9_.\-]{0,251}[a-z0-9_])?$")
77
+ _DNS_LINE = re.compile(r"^dns (?P<host>\S+) (?P<result>ok|fail)$")
78
+ _TCP_LINE = re.compile(r"^tcp (?P<host>\S+) (?P<port>\d{1,5}) (?P<result>open|fail)$")
79
+
80
+ PgResult = Literal["accepting", "rejecting", "no_response", "no_attempt", "unknown", "timeout"]
81
+ _PG_ISREADY_CODES: dict[int, PgResult] = {
82
+ 0: "accepting",
83
+ 1: "rejecting",
84
+ 2: "no_response",
85
+ 3: "no_attempt",
86
+ }
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class Target:
91
+ host: str
92
+ port: int | None
93
+
94
+
95
+ def can_probe(host: str) -> bool:
96
+ """Only plain DNS names are probed (never options, paths or shell syntax)."""
97
+ return bool(_PROBE_HOST.match(host))
98
+
99
+
100
+ def dns_tcp_command(name: str, networks: Sequence[str], targets: Sequence[Target]) -> list[str]:
101
+ args = ["docker", "run", "--name", name, "--pull", "missing", *HARDENING]
102
+ for network in networks:
103
+ args += ["--network", network]
104
+ args += [BUSYBOX_IMAGE, "sh", "-c", DNS_TCP_SCRIPT, "sh"]
105
+ for target in targets:
106
+ args += [target.host, str(target.port) if target.port is not None else "-"]
107
+ return args
108
+
109
+
110
+ def pg_isready_command(
111
+ name: str, networks: Sequence[str], image: str, host: str, port: int
112
+ ) -> list[str]:
113
+ args = ["docker", "run", "--name", name, "--pull", "never", *HARDENING]
114
+ for network in networks:
115
+ args += ["--network", network]
116
+ return [
117
+ *args,
118
+ "--entrypoint",
119
+ "pg_isready",
120
+ image,
121
+ "-h",
122
+ host,
123
+ "-p",
124
+ str(port),
125
+ "-t",
126
+ "3",
127
+ "-q",
128
+ ]
129
+
130
+
131
+ def parse_dns_tcp(stdout: str, targets: Sequence[Target]) -> list[dict[str, Any]]:
132
+ """One result per requested target. Lines that do not match are ignored."""
133
+ dns: dict[str, str] = {}
134
+ tcp: dict[tuple[str, int], str] = {}
135
+ for line in stdout.splitlines():
136
+ if match := _DNS_LINE.match(line.strip()):
137
+ dns[match["host"]] = match["result"]
138
+ elif match := _TCP_LINE.match(line.strip()):
139
+ tcp[(match["host"], int(match["port"]))] = match["result"]
140
+ return [
141
+ {
142
+ "host": target.host,
143
+ "port": target.port,
144
+ "dns": dns.get(target.host, "unknown"),
145
+ "tcp": tcp.get((target.host, target.port), "unknown")
146
+ if target.port is not None and dns.get(target.host) == "ok"
147
+ else None,
148
+ }
149
+ for target in targets
150
+ ]
151
+
152
+
153
+ def pg_result(returncode: int) -> PgResult:
154
+ return _PG_ISREADY_CODES.get(returncode, "unknown")
155
+
156
+
157
+ def run_probe(runner: ComposeRunner, args: list[str], name: str) -> tuple[int, str] | None:
158
+ """Run a probe container; return (exit code, stdout), or None on timeout.
159
+
160
+ On a timeout the container is force-removed, so nothing is left behind.
161
+ """
162
+ try:
163
+ result = runner(args, cwd=Path.cwd(), timeout=PROBE_TIMEOUT_SECONDS)
164
+ except subprocess.TimeoutExpired:
165
+ with contextlib.suppress(subprocess.TimeoutExpired, OSError):
166
+ runner(["docker", "rm", "-f", name], cwd=Path.cwd(), timeout=30)
167
+ return None
168
+ return result.returncode, result.stdout
169
+
170
+
171
+ def probe_name() -> str:
172
+ return f"sdprobe-{secrets.token_hex(6)}"
stackdoctor/py.typed ADDED
File without changes
@@ -0,0 +1,215 @@
1
+ """Secret redaction for everything StackDoctor collects.
2
+
3
+ `docker compose config --format json` resolves environment variables, so its
4
+ output can contain real credentials. Every value that leaves the core engine
5
+ (CLI output, MCP tool results, logs, reports, AI prompts) must pass through
6
+ this module first.
7
+
8
+ Design choices:
9
+
10
+ - Fail closed. Key detection is deliberately broad: redacting a harmless value
11
+ (for example ``AUTHOR``) costs a little diagnostic detail, leaking a secret
12
+ costs far more.
13
+ - Keep what is useful for diagnosis. Credentials embedded in URLs are removed,
14
+ but the scheme, username, host and port stay, because they are what most
15
+ integration failures are about.
16
+ - Idempotent. Redacting already-redacted data changes nothing, so layers can
17
+ redact defensively without corrupting each other's output.
18
+ """
19
+
20
+ import os
21
+ import re
22
+ from collections.abc import Iterable, Mapping
23
+ from typing import Any
24
+
25
+ REDACTED = "[REDACTED]"
26
+
27
+ # Matched anywhere in the key after lowercasing and removing separators, so
28
+ # `DB_PASSWORD`, `db-password`, `dbPassword` and `DBPASSWORD` all match.
29
+ _SENSITIVE_SUBSTRINGS = (
30
+ "password",
31
+ "passwd",
32
+ "passphrase",
33
+ "pwd",
34
+ "secret",
35
+ "token",
36
+ "apikey",
37
+ "auth",
38
+ "credential",
39
+ "privatekey",
40
+ "accesskey",
41
+ "dsn",
42
+ )
43
+
44
+ # Too short or too common to match as substrings (`pass` is in `PASSTHROUGH`,
45
+ # `key` is in `KEYBOARD`). They match only as a whole segment (`DB_PASS`,
46
+ # `STRIPE_KEY`) or as the end of the key (`DBPASS`, `SIGNINGKEY`).
47
+ _SENSITIVE_SEGMENTS = ("pass", "key")
48
+
49
+ _CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
50
+ _SEGMENT_SEPARATORS = re.compile(r"[^a-z0-9]+")
51
+
52
+ # `scheme://userinfo@`. Greedy userinfo stops at the last `@` before any `/`,
53
+ # `?`, `#` or whitespace, so a raw `@` inside a password is still covered.
54
+ _URL_USERINFO = re.compile(
55
+ r"(?P<scheme>\b[A-Za-z][A-Za-z0-9+.\-]*://)(?P<userinfo>[^\s/?#]+)@",
56
+ )
57
+
58
+ # `KEY=value`, `KEY: value`, `"KEY": "value"`, `--key=value`, `-Dkey=value`.
59
+ # Only the key and separator are matched here; the value is matched separately
60
+ # and only when the key is sensitive. Otherwise a non-sensitive key such as
61
+ # `error:` would swallow the next token (`X-Api-Key:`) as its value and hide
62
+ # the real secret that follows it.
63
+ _KEY_SEPARATOR = re.compile(
64
+ r"""(?<![A-Za-z0-9_.])
65
+ (?P<key>[A-Za-z_][A-Za-z0-9_.\-]*)
66
+ (?P<sep>["']?\s*[=:]\s*)""",
67
+ re.VERBOSE,
68
+ )
69
+ # A quoted string or a run of characters up to whitespace or a delimiter.
70
+ _VALUE = re.compile(r""""[^"]*"|'[^']*'|[^\s,;&"']+""")
71
+
72
+ # Known secret values shorter than this are not replaced literally: they would
73
+ # match innocent text too often.
74
+ _MIN_KNOWN_VALUE_LENGTH = 4
75
+
76
+
77
+ def is_sensitive_key(key: str) -> bool:
78
+ """Return whether a variable or field name probably holds a secret."""
79
+ # Segments are computed before separators are stripped, so `STRIPE_KEY`
80
+ # yields the segment `key` while `KEYBOARD_LAYOUT` does not.
81
+ segments = [s for s in _SEGMENT_SEPARATORS.split(_CAMEL_BOUNDARY.sub("_", key).lower()) if s]
82
+ compact = "".join(segments)
83
+ if not compact:
84
+ return False
85
+ if any(word in compact for word in _SENSITIVE_SUBSTRINGS):
86
+ return True
87
+ return any(word in segments or compact.endswith(word) for word in _SENSITIVE_SEGMENTS)
88
+
89
+
90
+ def redact_url_credentials(text: str) -> str:
91
+ """Remove credentials from every URL in ``text``, keeping user, host and port.
92
+
93
+ ``postgres://app:hunter2@db:5432/app`` becomes
94
+ ``postgres://app:[REDACTED]@db:5432/app``. Userinfo without a password
95
+ (``https://TOKEN@host``) is removed entirely, because it is often a token.
96
+ """
97
+
98
+ def replace(match: re.Match[str]) -> str:
99
+ user, has_password, _ = match["userinfo"].partition(":")
100
+ userinfo = f"{user}:{REDACTED}" if has_password and user else REDACTED
101
+ return f"{match['scheme']}{userinfo}@"
102
+
103
+ return _URL_USERINFO.sub(replace, text)
104
+
105
+
106
+ def url_passwords(text: str) -> list[str]:
107
+ """Return the password of every URL in ``text`` that has one."""
108
+ passwords = []
109
+ for match in _URL_USERINFO.finditer(text):
110
+ _, has_password, password = match["userinfo"].partition(":")
111
+ if has_password and password:
112
+ passwords.append(password)
113
+ return passwords
114
+
115
+
116
+ def _redact_key_values(text: str) -> str:
117
+ parts: list[str] = []
118
+ position = 0
119
+ while match := _KEY_SEPARATOR.search(text, position):
120
+ parts.append(text[position : match.end()])
121
+ position = match.end()
122
+ if not is_sensitive_key(match["key"]):
123
+ continue
124
+ value = _VALUE.match(text, position)
125
+ if value is None:
126
+ continue
127
+ quote = value[0][0] if value[0][0] in "\"'" else ""
128
+ parts.append(f"{quote}{REDACTED}{quote}")
129
+ position = value.end()
130
+ parts.append(text[position:])
131
+ return "".join(parts)
132
+
133
+
134
+ def _replace_known_values(text: str, known_values: Iterable[str]) -> str:
135
+ values = sorted(
136
+ {v for v in known_values if len(v) >= _MIN_KNOWN_VALUE_LENGTH and v != REDACTED},
137
+ key=len,
138
+ reverse=True,
139
+ )
140
+ if not values:
141
+ return text
142
+ # Replace only between existing placeholders, so a known value that happens
143
+ # to be a substring of "[REDACTED]" cannot corrupt earlier redaction.
144
+ pieces = text.split(REDACTED)
145
+ for value in values:
146
+ pieces = [piece.replace(value, REDACTED) for piece in pieces]
147
+ return REDACTED.join(pieces)
148
+
149
+
150
+ def redact_text(text: str, known_values: Iterable[str] = ()) -> str:
151
+ """Redact secrets from free text such as error messages or command output.
152
+
153
+ Applies, in order: literal replacement of ``known_values`` (for example the
154
+ values of sensitive variables in the current environment), ``KEY=value``
155
+ style pairs whose key looks sensitive, and URL credentials.
156
+
157
+ Pattern matching cannot catch every secret (for example a password passed
158
+ as ``-pSECRET``), so prefer not to collect such text at all.
159
+ """
160
+ text = _replace_known_values(text, known_values)
161
+ # Key/value pairs go before URLs: a URL whose username looks sensitive
162
+ # (`token:...@host`) is then redacted entirely rather than partially.
163
+ text = _redact_key_values(text)
164
+ return redact_url_credentials(text)
165
+
166
+
167
+ def redact_json(value: Any, known_values: Iterable[str] = ()) -> Any:
168
+ """Apply :func:`redact_text` to every string inside a JSON-like value.
169
+
170
+ Used as a last line of defense on collected evidence and on everything
171
+ sent to an AI provider. Keys are left alone: they are structural (service
172
+ names, field names), and replacing a subtree because its key looks
173
+ sensitive (a service called ``auth``) would break evidence paths.
174
+ Producers must still allowlist what they collect.
175
+ """
176
+ known = tuple(known_values)
177
+ if isinstance(value, str):
178
+ return redact_text(value, known)
179
+ if isinstance(value, dict):
180
+ return {key: redact_json(item, known) for key, item in value.items()}
181
+ if isinstance(value, list | tuple):
182
+ return [redact_json(item, known) for item in value]
183
+ return value
184
+
185
+
186
+ def sensitive_environment_values(environ: Mapping[str, str] | None = None) -> list[str]:
187
+ """Values of the variables in ``environ`` (default: this process) that look secret.
188
+
189
+ Passed as ``known_values`` to :func:`redact_text`, so a secret from the
190
+ caller's own environment (an API key, a token) is removed wherever it
191
+ appears, even in text that does not look like ``KEY=value``.
192
+ """
193
+ source = os.environ if environ is None else environ
194
+ return [value for key, value in source.items() if value and is_sensitive_key(key)]
195
+
196
+
197
+ def redact_environment(environment: Mapping[str, str | None]) -> dict[str, str | None]:
198
+ """Redact a service's environment variables.
199
+
200
+ Values under sensitive keys become ``[REDACTED]``. Other values still go
201
+ through :func:`redact_text`, which catches credentials in URLs and inline
202
+ ``key=value`` options. ``None`` (declared but unset) is kept, because an
203
+ unset variable is useful diagnostic information, and so is an empty value
204
+ (``""``, for example from an unset interpolated variable), which is not a
205
+ secret.
206
+ """
207
+ redacted: dict[str, str | None] = {}
208
+ for key, value in environment.items():
209
+ if value is None or value == "":
210
+ redacted[key] = value
211
+ elif is_sensitive_key(key):
212
+ redacted[key] = REDACTED
213
+ else:
214
+ redacted[key] = redact_text(value)
215
+ return redacted