secretscreen 0.2.0__tar.gz → 0.3.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.
- {secretscreen-0.2.0 → secretscreen-0.3.0}/.gitignore +5 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/PKG-INFO +21 -8
- {secretscreen-0.2.0 → secretscreen-0.3.0}/README.md +12 -1
- {secretscreen-0.2.0 → secretscreen-0.3.0}/docs/audits/security-audit-2026-04-05.md +23 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/pyproject.toml +6 -4
- {secretscreen-0.2.0 → secretscreen-0.3.0}/src/secretscreen/__init__.py +4 -1
- {secretscreen-0.2.0 → secretscreen-0.3.0}/src/secretscreen/_core.py +24 -10
- {secretscreen-0.2.0 → secretscreen-0.3.0}/src/secretscreen/_parsers.py +7 -3
- secretscreen-0.3.0/src/secretscreen/_urls.py +169 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/tests/test_cli.py +2 -2
- {secretscreen-0.2.0 → secretscreen-0.3.0}/tests/test_core.py +35 -5
- secretscreen-0.3.0/tests/test_urls.py +288 -0
- secretscreen-0.2.0/src/secretscreen/_urls.py +0 -72
- secretscreen-0.2.0/tests/test_urls.py +0 -63
- {secretscreen-0.2.0 → secretscreen-0.3.0}/.github/FUNDING.yml +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/.github/dependabot.yml +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/.github/pull_request_template.md +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/.github/workflows/ci.yml +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/.github/workflows/codeql.yml +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/.github/workflows/dependabot-automerge.yml +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/.github/workflows/publish.yml +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/.github/workflows/scorecard.yml +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/CODE_OF_CONDUCT.md +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/CONTRIBUTING.md +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/LICENSE +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/NOTICE +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/SECURITY.md +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/src/secretscreen/_cli.py +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/src/secretscreen/_entropy.py +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/src/secretscreen/_formats.py +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/src/secretscreen/_keys.py +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/src/secretscreen/gitleaks.toml +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/src/secretscreen/py.typed +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/tests/__init__.py +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/tests/test_architecture.py +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/tests/test_entropy.py +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/tests/test_formats.py +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/tests/test_keys.py +0 -0
- {secretscreen-0.2.0 → secretscreen-0.3.0}/tests/test_parsers.py +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: secretscreen
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: Detect and redact secrets in key-value pairs, dicts, and environment variables.
|
|
3
|
+
Version: 0.3.0
|
|
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
|
|
7
7
|
Project-URL: Issues, https://github.com/featurecreep-cron/secretscreen/issues
|
|
@@ -9,8 +9,9 @@ Author-email: Cron <cron@featurecreep.dev>
|
|
|
9
9
|
License-Expression: MIT
|
|
10
10
|
License-File: LICENSE
|
|
11
11
|
License-File: NOTICE
|
|
12
|
-
Keywords: docker,environment,redaction,secrets,security
|
|
12
|
+
Keywords: cli,command-line,docker,environment,redaction,secrets,security
|
|
13
13
|
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Environment :: Console
|
|
14
15
|
Classifier: Intended Audience :: Developers
|
|
15
16
|
Classifier: License :: OSI Approved :: MIT License
|
|
16
17
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -19,13 +20,14 @@ Classifier: Programming Language :: Python :: 3.12
|
|
|
19
20
|
Classifier: Programming Language :: Python :: 3.13
|
|
20
21
|
Classifier: Topic :: Security
|
|
21
22
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Classifier: Topic :: Utilities
|
|
22
24
|
Classifier: Typing :: Typed
|
|
23
25
|
Requires-Python: >=3.11
|
|
24
26
|
Provides-Extra: dev
|
|
25
|
-
Requires-Dist: mypy<3,>=
|
|
26
|
-
Requires-Dist: pytest-cov>=
|
|
27
|
-
Requires-Dist: pytest>=
|
|
28
|
-
Requires-Dist: ruff<0.17,>=0.
|
|
27
|
+
Requires-Dist: mypy<3,>=2.3.0; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest-cov>=7.1.0; extra == 'dev'
|
|
29
|
+
Requires-Dist: pytest>=9.1.1; extra == 'dev'
|
|
30
|
+
Requires-Dist: ruff<0.17,>=0.16.0; extra == 'dev'
|
|
29
31
|
Description-Content-Type: text/markdown
|
|
30
32
|
|
|
31
33
|
# secretscreen
|
|
@@ -44,10 +46,21 @@ Best-effort defense-in-depth. Not a security boundary.
|
|
|
44
46
|
|
|
45
47
|
## Install
|
|
46
48
|
|
|
49
|
+
As a library:
|
|
50
|
+
|
|
47
51
|
```
|
|
48
52
|
pip install secretscreen
|
|
49
53
|
```
|
|
50
54
|
|
|
55
|
+
As a command-line tool — `pipx` or `uv` keep it in its own environment and put `secretscreen` on your PATH everywhere, rather than only in whichever venv is active:
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
pipx install secretscreen
|
|
59
|
+
uv tool install secretscreen
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Zero dependencies, Python 3.11+.
|
|
63
|
+
|
|
51
64
|
## Quick start
|
|
52
65
|
|
|
53
66
|
```python
|
|
@@ -100,7 +113,7 @@ Redaction is structural, not line-based: it parses the format, so it catches `DB
|
|
|
100
113
|
| 1 | `--audit` found secrets |
|
|
101
114
|
| 2 | Something could not be parsed or read — see stderr |
|
|
102
115
|
|
|
103
|
-
That third case is the one that matters. This is best-effort defense-in-depth, and a cat-replacement is exactly the tool people stop thinking about, so the CLI never prints unparsed content verbatim: a line it cannot structure is replaced with the redaction token, named on stderr, and turns the exit code non-zero. The same applies to values above the
|
|
116
|
+
That third case is the one that matters. This is best-effort defense-in-depth, and a cat-replacement is exactly the tool people stop thinking about, so the CLI never prints unparsed content verbatim: a line it cannot structure is replaced with the redaction token, named on stderr, and turns the exit code non-zero. The same applies to values above the 64 KB detection cap — they are reported as unscanned rather than passed off as clean.
|
|
104
117
|
|
|
105
118
|
If you are scanning a git repository rather than config-shaped data, use [gitleaks](https://github.com/gitleaks/gitleaks) instead. That is a different job.
|
|
106
119
|
|
|
@@ -14,10 +14,21 @@ Best-effort defense-in-depth. Not a security boundary.
|
|
|
14
14
|
|
|
15
15
|
## Install
|
|
16
16
|
|
|
17
|
+
As a library:
|
|
18
|
+
|
|
17
19
|
```
|
|
18
20
|
pip install secretscreen
|
|
19
21
|
```
|
|
20
22
|
|
|
23
|
+
As a command-line tool — `pipx` or `uv` keep it in its own environment and put `secretscreen` on your PATH everywhere, rather than only in whichever venv is active:
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
pipx install secretscreen
|
|
27
|
+
uv tool install secretscreen
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Zero dependencies, Python 3.11+.
|
|
31
|
+
|
|
21
32
|
## Quick start
|
|
22
33
|
|
|
23
34
|
```python
|
|
@@ -70,7 +81,7 @@ Redaction is structural, not line-based: it parses the format, so it catches `DB
|
|
|
70
81
|
| 1 | `--audit` found secrets |
|
|
71
82
|
| 2 | Something could not be parsed or read — see stderr |
|
|
72
83
|
|
|
73
|
-
That third case is the one that matters. This is best-effort defense-in-depth, and a cat-replacement is exactly the tool people stop thinking about, so the CLI never prints unparsed content verbatim: a line it cannot structure is replaced with the redaction token, named on stderr, and turns the exit code non-zero. The same applies to values above the
|
|
84
|
+
That third case is the one that matters. This is best-effort defense-in-depth, and a cat-replacement is exactly the tool people stop thinking about, so the CLI never prints unparsed content verbatim: a line it cannot structure is replaced with the redaction token, named on stderr, and turns the exit code non-zero. The same applies to values above the 64 KB detection cap — they are reported as unscanned rather than passed off as clean.
|
|
74
85
|
|
|
75
86
|
If you are scanning a git repository rather than config-shaped data, use [gitleaks](https://github.com/gitleaks/gitleaks) instead. That is a different job.
|
|
76
87
|
|
|
@@ -131,6 +131,29 @@ never touches the value — so `AWS_SECRET_ACCESS_KEY=<2MB blob>` passed through
|
|
|
131
131
|
unredacted and `audit_pair` reported no finding. Trading a 7.7s CPU stall for a silent secret
|
|
132
132
|
leak is the wrong direction for a redaction library.
|
|
133
133
|
|
|
134
|
+
**Second correction (2026-07-27)**: the 1MB threshold was also wrong, and for the same
|
|
135
|
+
reason the finding understated the problem — both were measured on benign input. The
|
|
136
|
+
"~7.7s at 50MB" figure above reproduces (I measured 11.7s for 50MB of `"x"`), but a run of
|
|
137
|
+
one character is not the worst case. On random high-entropy text — what a secret-shaped
|
|
138
|
+
blob actually looks like — at least one vendored pattern backtracks and cost goes roughly
|
|
139
|
+
quadratic above ~128KB:
|
|
140
|
+
|
|
141
|
+
| size | `"x" * n` | random |
|
|
142
|
+
|------|-----------|--------|
|
|
143
|
+
| 64KB | — | 0.57s |
|
|
144
|
+
| 128KB | — | 1.00s |
|
|
145
|
+
| 256KB | — | 14s |
|
|
146
|
+
| 1MB | 0.195s | **107s** |
|
|
147
|
+
| 10MB | 1.8s | 20.7 min |
|
|
148
|
+
|
|
149
|
+
A 1MB cap therefore admitted exactly the input that hurts most: a value one byte under it
|
|
150
|
+
pinned a core for nearly two minutes. Lowered to 64KB (0.57s worst case), matching
|
|
151
|
+
`MAX_PARSE_LENGTH`, which already bounded Layer 2 — so only Layers 3–5 narrow, and only
|
|
152
|
+
for values large enough to be data dumps rather than config. Pinned by
|
|
153
|
+
`test_worst_case_input_at_the_cap_stays_sub_second`.
|
|
154
|
+
|
|
155
|
+
Not yet identified: *which* rule backtracks. Tracked with the gitleaks sync work in #1.
|
|
156
|
+
|
|
134
157
|
The cap now gates Layers 2–5 only; Layer 1 always runs. Residual gap, accepted and tested
|
|
135
158
|
(`test_oversized_value_under_non_denylisted_key_is_a_known_gap`): an oversized value under a key
|
|
136
159
|
that Layer 1 does not match — including safe-suffix keys like `DATABASE_URL`, which depend on
|
|
@@ -4,15 +4,16 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "secretscreen"
|
|
7
|
-
version = "0.
|
|
8
|
-
description = "Detect and redact secrets in key-value pairs, dicts, and environment variables."
|
|
7
|
+
version = "0.3.0"
|
|
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"
|
|
11
11
|
requires-python = ">=3.11"
|
|
12
12
|
authors = [{ name = "Cron", email = "cron@featurecreep.dev" }]
|
|
13
|
-
keywords = ["secrets", "redaction", "security", "environment", "docker"]
|
|
13
|
+
keywords = ["secrets", "redaction", "security", "environment", "docker", "cli", "command-line"]
|
|
14
14
|
classifiers = [
|
|
15
15
|
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Environment :: Console",
|
|
16
17
|
"Intended Audience :: Developers",
|
|
17
18
|
"License :: OSI Approved :: MIT License",
|
|
18
19
|
"Programming Language :: Python :: 3",
|
|
@@ -21,6 +22,7 @@ classifiers = [
|
|
|
21
22
|
"Programming Language :: Python :: 3.13",
|
|
22
23
|
"Topic :: Security",
|
|
23
24
|
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
25
|
+
"Topic :: Utilities",
|
|
24
26
|
"Typing :: Typed",
|
|
25
27
|
]
|
|
26
28
|
|
|
@@ -30,7 +32,7 @@ secretscreen = "secretscreen._cli:main"
|
|
|
30
32
|
[project.optional-dependencies]
|
|
31
33
|
# Linters gate CI, so they carry upper bounds: an unpinned ruff minor bump
|
|
32
34
|
# (0.15 -> 0.16) silently changed formatting rules and broke an unrelated PR.
|
|
33
|
-
dev = ["pytest>=
|
|
35
|
+
dev = ["pytest>=9.1.1", "pytest-cov>=7.1.0", "ruff>=0.16.0,<0.17", "mypy>=2.3.0,<3"]
|
|
34
36
|
|
|
35
37
|
[project.urls]
|
|
36
38
|
Homepage = "https://github.com/featurecreep-cron/secretscreen"
|
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
Best-effort defense-in-depth. Not a security boundary.
|
|
4
4
|
|
|
5
|
+
Also ships a CLI for shell use — `secretscreen FILE...` redacts and prints,
|
|
6
|
+
`--audit` reports findings without values. See README.md.
|
|
7
|
+
|
|
5
8
|
Five detection layers:
|
|
6
9
|
1. Key-name denylist — substring match against known secret key patterns.
|
|
7
10
|
2. Structured value parsing — JSON, Python literals, INI, DSN, URL query params.
|
|
@@ -34,4 +37,4 @@ __all__ = [
|
|
|
34
37
|
"redact_pair",
|
|
35
38
|
]
|
|
36
39
|
|
|
37
|
-
__version__ = "0.
|
|
40
|
+
__version__ = "0.3.0"
|
|
@@ -16,7 +16,7 @@ from secretscreen._keys import (
|
|
|
16
16
|
matches_key_pattern,
|
|
17
17
|
)
|
|
18
18
|
from secretscreen._parsers import extract_pairs
|
|
19
|
-
from secretscreen._urls import has_url_credentials,
|
|
19
|
+
from secretscreen._urls import has_url_credentials, redact_url_credentials
|
|
20
20
|
|
|
21
21
|
REDACTED = "[REDACTED]"
|
|
22
22
|
|
|
@@ -173,14 +173,28 @@ def audit_dict(
|
|
|
173
173
|
# Prevents stack overflow from crafted nested JSON/Python literals.
|
|
174
174
|
_MAX_DETECT_DEPTH = 3
|
|
175
175
|
|
|
176
|
-
# Maximum value length for the value-scanning layers (2-5).
|
|
177
|
-
#
|
|
178
|
-
#
|
|
179
|
-
#
|
|
180
|
-
#
|
|
181
|
-
#
|
|
182
|
-
#
|
|
183
|
-
|
|
176
|
+
# Maximum value length for the value-scanning layers (2-5). Prevents DoS via large
|
|
177
|
+
# inputs hitting 221+ regex patterns, at least one of which backtracks badly.
|
|
178
|
+
#
|
|
179
|
+
# The threshold is set from measured worst-case input — random high-entropy text,
|
|
180
|
+
# which is what a secret-shaped blob looks like — not from a run of one character.
|
|
181
|
+
# Cost is roughly quadratic above ~128KB:
|
|
182
|
+
#
|
|
183
|
+
# 64KB 0.57s 256KB 14s
|
|
184
|
+
# 128KB 1.00s 1MB 107s
|
|
185
|
+
#
|
|
186
|
+
# This was originally 1MB, chosen against a benign benchmark (a run of 'x', which
|
|
187
|
+
# is ~500x faster at the same size). That admitted exactly the input that hurts:
|
|
188
|
+
# a value one byte under the cap pinned a core for nearly two minutes. 64KB matches
|
|
189
|
+
# MAX_PARSE_LENGTH in _parsers.py, which already bounded layer 2 — so this only
|
|
190
|
+
# narrows layers 3-5, and only for values big enough to be data dumps, not config.
|
|
191
|
+
#
|
|
192
|
+
# Layer 1 (key-name match) is deliberately exempt: it reads only the key, so an
|
|
193
|
+
# oversized value under a secret-named key is still redacted. Residual gap: an
|
|
194
|
+
# oversized value under an innocuous key name is not scanned and passes through
|
|
195
|
+
# unredacted. Callers that print values (e.g. a CLI) should surface that skip
|
|
196
|
+
# rather than let it look screened.
|
|
197
|
+
_MAX_DETECT_LENGTH = 65_536 # 64 KB
|
|
184
198
|
|
|
185
199
|
|
|
186
200
|
def _detect(key: str, value: str, config: ScreenConfig, _depth: int = 0) -> Finding | None:
|
|
@@ -303,7 +317,7 @@ def _apply_redaction(
|
|
|
303
317
|
Used by both redact_pair and _redact_recursive.
|
|
304
318
|
"""
|
|
305
319
|
if finding.layer == "url_credentials":
|
|
306
|
-
return
|
|
320
|
+
return redact_url_credentials(value, config.replacement)
|
|
307
321
|
|
|
308
322
|
if finding.layer == "structured_parsing":
|
|
309
323
|
return _redact_structured(value, config, cached_pairs)
|
|
@@ -107,13 +107,17 @@ def _parse_dsn(value: str) -> list[tuple[str, str]]:
|
|
|
107
107
|
|
|
108
108
|
|
|
109
109
|
def _parse_url_query(value: str) -> list[tuple[str, str]]:
|
|
110
|
-
"""Extract pairs from URL query parameters.
|
|
110
|
+
"""Extract pairs from URL query parameters and embedded credentials.
|
|
111
|
+
|
|
112
|
+
Credentials are collected whether or not the URL carries a query string.
|
|
113
|
+
Returning early on an empty query — as this did previously — made the
|
|
114
|
+
credential extraction below unreachable for every URL without a ``?``,
|
|
115
|
+
which is most of them.
|
|
116
|
+
"""
|
|
111
117
|
if "://" not in value and "?" not in value:
|
|
112
118
|
return []
|
|
113
119
|
|
|
114
120
|
parsed = urlsplit(value)
|
|
115
|
-
if not parsed.query:
|
|
116
|
-
return []
|
|
117
121
|
|
|
118
122
|
pairs: list[tuple[str, str]] = []
|
|
119
123
|
for k, values in parse_qs(parsed.query).items():
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""URL credential detection and partial redaction.
|
|
2
|
+
|
|
3
|
+
Layer 4: detect and redact credentials embedded in URLs.
|
|
4
|
+
Only the credential portion is replaced — username, host, path are preserved
|
|
5
|
+
for debugging utility, except where the username *is* the credential.
|
|
6
|
+
|
|
7
|
+
Credentials appear in two positions:
|
|
8
|
+
|
|
9
|
+
- ``scheme://user:password@host`` — the classic form. The password is the
|
|
10
|
+
secret regardless of scheme.
|
|
11
|
+
- ``scheme://TOKEN@host`` — userinfo with no password. Notification and
|
|
12
|
+
push services (shoutrrr, apprise) use this shape almost universally:
|
|
13
|
+
``discord://TOKEN@id``, ``ntfy://tk_xxx@ntfy.sh``, ``telegram://TOKEN@telegram``.
|
|
14
|
+
|
|
15
|
+
Only the second form needs a scheme judgement, because ``user@host`` is an
|
|
16
|
+
identity rather than a secret for the familiar transports — ``git@github.com``,
|
|
17
|
+
``https://user@github.com/repo.git``. Those are listed explicitly and every
|
|
18
|
+
other scheme is treated as credential-bearing, so a notification service
|
|
19
|
+
nobody here has heard of fails closed rather than printing its token.
|
|
20
|
+
|
|
21
|
+
Secrets in the *path* (``gotify://host/TOKEN``) are out of scope: detecting
|
|
22
|
+
them would require guessing that a long path segment is a token, which fires
|
|
23
|
+
on ordinary URLs. Those are a job for an explicit key rule.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
from urllib.parse import SplitResult, urlsplit, urlunsplit
|
|
29
|
+
|
|
30
|
+
# Default replacement — matches _core.REDACTED but _urls is a leaf module,
|
|
31
|
+
# so we define our own default to avoid circular imports.
|
|
32
|
+
_DEFAULT_REPLACEMENT = "[REDACTED]"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# Multi-scheme URL prefixes that wrap a standard URL.
|
|
36
|
+
# urlsplit treats these as the scheme, making credentials invisible.
|
|
37
|
+
_URL_WRAPPERS = ("jdbc:", "odbc:")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# Schemes where a username with no password is an identity, not a secret.
|
|
41
|
+
# Databases are included: a bare role name carries nothing, and the
|
|
42
|
+
# password form is caught by the password branch regardless of scheme.
|
|
43
|
+
_PLAIN_USERINFO_SCHEMES = frozenset(
|
|
44
|
+
{
|
|
45
|
+
"http",
|
|
46
|
+
"https",
|
|
47
|
+
"ftp",
|
|
48
|
+
"ftps",
|
|
49
|
+
"ssh",
|
|
50
|
+
"sftp",
|
|
51
|
+
"git",
|
|
52
|
+
"rsync",
|
|
53
|
+
"postgres",
|
|
54
|
+
"postgresql",
|
|
55
|
+
"mysql",
|
|
56
|
+
"mariadb",
|
|
57
|
+
"redis",
|
|
58
|
+
"rediss",
|
|
59
|
+
"mongodb",
|
|
60
|
+
"mongodb+srv",
|
|
61
|
+
"amqp",
|
|
62
|
+
"amqps",
|
|
63
|
+
}
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# Credential positions, in the order they are checked.
|
|
67
|
+
_KIND_PASSWORD = "password"
|
|
68
|
+
_KIND_USERINFO = "userinfo"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _strip_url_wrapper(value: str) -> str:
|
|
72
|
+
"""Strip multi-scheme prefixes so urlsplit can parse credentials."""
|
|
73
|
+
lower = value.lower()
|
|
74
|
+
for prefix in _URL_WRAPPERS:
|
|
75
|
+
if lower.startswith(prefix):
|
|
76
|
+
return value[len(prefix) :]
|
|
77
|
+
return value
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _netloc_safe(replacement: str) -> str:
|
|
81
|
+
"""Strip characters that make a replacement token unparseable inside a netloc.
|
|
82
|
+
|
|
83
|
+
``urlsplit`` treats any ``[`` in the netloc as the start of an IPv6 literal
|
|
84
|
+
and raises, so the default ``[REDACTED]`` written into the userinfo position
|
|
85
|
+
produces output that cannot be read back. Screening already-screened data
|
|
86
|
+
would then collapse the whole URL to the bare token — no leak, but the host
|
|
87
|
+
and path are lost for no reason. Redaction has to be idempotent.
|
|
88
|
+
"""
|
|
89
|
+
stripped = replacement
|
|
90
|
+
for char in "[]@/?#":
|
|
91
|
+
stripped = stripped.replace(char, "")
|
|
92
|
+
return stripped or "REDACTED"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _credential_kind(parsed: SplitResult) -> str | None:
|
|
96
|
+
"""Classify where the credential sits in a parsed URL, or None if clean.
|
|
97
|
+
|
|
98
|
+
An empty password (``foo://user:@host``) is not a secret, so it falls
|
|
99
|
+
through to the userinfo rule rather than redacting nothing of value.
|
|
100
|
+
"""
|
|
101
|
+
if not parsed.scheme:
|
|
102
|
+
return None
|
|
103
|
+
if parsed.password:
|
|
104
|
+
return _KIND_PASSWORD
|
|
105
|
+
if parsed.username and parsed.scheme.lower() not in _PLAIN_USERINFO_SCHEMES:
|
|
106
|
+
return _KIND_USERINFO
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def has_url_credentials(value: str) -> bool:
|
|
111
|
+
"""Check if a value contains a URL with embedded credentials.
|
|
112
|
+
|
|
113
|
+
A value that looks like a URL but cannot be parsed counts as
|
|
114
|
+
credential-bearing. urlsplit rejects malformed IPv6 brackets and invalid
|
|
115
|
+
ports, and ``http://[user:pw@host`` is both unparseable and a credential —
|
|
116
|
+
reporting it clean let it print verbatim. Redaction already failed closed
|
|
117
|
+
on the same input, so the two halves disagreed and the safe half never ran.
|
|
118
|
+
"""
|
|
119
|
+
if "://" not in value:
|
|
120
|
+
return False
|
|
121
|
+
try:
|
|
122
|
+
return _credential_kind(urlsplit(_strip_url_wrapper(value))) is not None
|
|
123
|
+
except (ValueError, AttributeError):
|
|
124
|
+
return True
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def redact_url_credentials(value: str, replacement: str = _DEFAULT_REPLACEMENT) -> str:
|
|
128
|
+
"""Replace only the credential portion of a URL.
|
|
129
|
+
|
|
130
|
+
Preserves host, path, query, and fragment for debugging. The username is
|
|
131
|
+
preserved when the password is the secret, and replaced when the username
|
|
132
|
+
itself is the credential (``discord://TOKEN@id``).
|
|
133
|
+
|
|
134
|
+
Returns the value unchanged when there is no credential to remove, and the
|
|
135
|
+
bare replacement when the URL cannot be parsed at all — an unparseable
|
|
136
|
+
value must not be echoed.
|
|
137
|
+
"""
|
|
138
|
+
try:
|
|
139
|
+
raw = _strip_url_wrapper(value)
|
|
140
|
+
prefix = value[: len(value) - len(raw)] # preserve original prefix casing
|
|
141
|
+
parsed = urlsplit(raw)
|
|
142
|
+
kind = _credential_kind(parsed)
|
|
143
|
+
if kind is None:
|
|
144
|
+
return value
|
|
145
|
+
|
|
146
|
+
token = _netloc_safe(replacement)
|
|
147
|
+
if kind == _KIND_PASSWORD:
|
|
148
|
+
new_userinfo = f"{parsed.username or ''}:{token}"
|
|
149
|
+
else:
|
|
150
|
+
new_userinfo = token
|
|
151
|
+
|
|
152
|
+
host = parsed.hostname or ""
|
|
153
|
+
# Re-add brackets for IPv6 addresses
|
|
154
|
+
if host and ":" in host:
|
|
155
|
+
host = f"[{host}]"
|
|
156
|
+
port_str = f":{parsed.port}" if parsed.port else ""
|
|
157
|
+
new_netloc = f"{new_userinfo}@{host}{port_str}"
|
|
158
|
+
|
|
159
|
+
return prefix + urlunsplit(
|
|
160
|
+
(
|
|
161
|
+
parsed.scheme,
|
|
162
|
+
new_netloc,
|
|
163
|
+
parsed.path,
|
|
164
|
+
parsed.query,
|
|
165
|
+
parsed.fragment,
|
|
166
|
+
)
|
|
167
|
+
)
|
|
168
|
+
except (ValueError, AttributeError):
|
|
169
|
+
return _DEFAULT_REPLACEMENT
|
|
@@ -59,7 +59,7 @@ class TestRedactMode:
|
|
|
59
59
|
def test_partial_url_redaction_keeps_structure(self, tmp_path, capsys) -> None:
|
|
60
60
|
main([_write(tmp_path, "sample.env", SAMPLE_ENV)])
|
|
61
61
|
out = capsys.readouterr().out
|
|
62
|
-
assert "postgres://admin:
|
|
62
|
+
assert "postgres://admin:REDACTED@db.internal:5432/prod" in out
|
|
63
63
|
|
|
64
64
|
def test_custom_replacement(self, tmp_path, capsys) -> None:
|
|
65
65
|
main([_write(tmp_path, "s.env", "DB_PASSWORD=hunter2\n"), "--replacement", "XXX"])
|
|
@@ -189,7 +189,7 @@ class TestFormats:
|
|
|
189
189
|
def test_dsn_format(self, tmp_path, capsys) -> None:
|
|
190
190
|
main([_write(tmp_path, "dsn.txt", "postgres://admin:s3cr3t@db:5432/prod\n"), "--format", "dsn"])
|
|
191
191
|
out = capsys.readouterr().out
|
|
192
|
-
assert out.strip() == "postgres://admin:
|
|
192
|
+
assert out.strip() == "postgres://admin:REDACTED@db:5432/prod"
|
|
193
193
|
|
|
194
194
|
@pytest.mark.parametrize(
|
|
195
195
|
("name", "content", "marker"),
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""Tests for core orchestration — redact_pair, redact_dict, audit_pair, audit_dict."""
|
|
2
2
|
|
|
3
3
|
from secretscreen import Finding, Mode, audit_dict, audit_pair, redact_dict, redact_pair
|
|
4
|
+
from secretscreen._core import _MAX_DETECT_LENGTH
|
|
4
5
|
|
|
5
6
|
|
|
6
7
|
class TestRedactPair:
|
|
@@ -303,6 +304,35 @@ class TestSecurityFixes:
|
|
|
303
304
|
assert finding is not None
|
|
304
305
|
assert finding.layer == "key_pattern"
|
|
305
306
|
|
|
307
|
+
def test_worst_case_input_at_the_cap_stays_sub_second(self) -> None:
|
|
308
|
+
"""The cap must be set against adversarial input, not a run of one character.
|
|
309
|
+
|
|
310
|
+
At least one vendored gitleaks pattern backtracks: cost is roughly quadratic
|
|
311
|
+
above ~128KB on random high-entropy text (what a secret-shaped blob looks
|
|
312
|
+
like). The original 1MB cap allowed a ~107s scan. A run of 'x' is ~500x
|
|
313
|
+
faster at the same size, which is why it was not a safe benchmark.
|
|
314
|
+
"""
|
|
315
|
+
import random
|
|
316
|
+
import time
|
|
317
|
+
|
|
318
|
+
random.seed(0)
|
|
319
|
+
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/+="
|
|
320
|
+
at_cap = "".join(random.choices(alphabet, k=_MAX_DETECT_LENGTH))
|
|
321
|
+
|
|
322
|
+
start = time.perf_counter()
|
|
323
|
+
redact_pair("BLOB", at_cap)
|
|
324
|
+
elapsed = time.perf_counter() - start
|
|
325
|
+
|
|
326
|
+
# Measured ~0.57s at 64KB. 5s leaves headroom for slow CI without letting a
|
|
327
|
+
# future cap increase quietly reintroduce a multi-minute scan.
|
|
328
|
+
assert elapsed < 5.0, f"scan at the cap took {elapsed:.1f}s — is _MAX_DETECT_LENGTH too high?"
|
|
329
|
+
|
|
330
|
+
def test_cap_matches_the_parser_bound(self) -> None:
|
|
331
|
+
"""Layer 2 was already bounded at 64KB; keeping both at one value is simpler."""
|
|
332
|
+
from secretscreen._parsers import MAX_PARSE_LENGTH
|
|
333
|
+
|
|
334
|
+
assert _MAX_DETECT_LENGTH == MAX_PARSE_LENGTH
|
|
335
|
+
|
|
306
336
|
def test_large_value_layer_one_is_cheap(self) -> None:
|
|
307
337
|
"""Layer 1 on an oversized value must not fall through to the regex layers."""
|
|
308
338
|
import time
|
|
@@ -326,7 +356,7 @@ class TestSecurityFixes:
|
|
|
326
356
|
|
|
327
357
|
# Same URL under the cap is redacted normally.
|
|
328
358
|
small_url = "postgres://user:pw@host/db"
|
|
329
|
-
assert redact_pair("DATABASE_URL", small_url) == "postgres://user:
|
|
359
|
+
assert redact_pair("DATABASE_URL", small_url) == "postgres://user:REDACTED@host/db"
|
|
330
360
|
|
|
331
361
|
def test_deeply_nested_dict_does_not_crash(self) -> None:
|
|
332
362
|
"""MEDIUM-4: redact_dict should handle deeply nested dicts without RecursionError."""
|
|
@@ -361,18 +391,18 @@ class TestSecurityFixes:
|
|
|
361
391
|
|
|
362
392
|
def test_jdbc_url_redacted(self) -> None:
|
|
363
393
|
"""LOW-1: JDBC URLs should have passwords redacted."""
|
|
364
|
-
from secretscreen._urls import
|
|
394
|
+
from secretscreen._urls import redact_url_credentials
|
|
365
395
|
|
|
366
|
-
result =
|
|
396
|
+
result = redact_url_credentials("jdbc:postgresql://admin:S3cr3t@prod-db:5432/main")
|
|
367
397
|
assert "S3cr3t" not in result
|
|
368
398
|
assert "admin" in result
|
|
369
399
|
assert result.startswith("jdbc:")
|
|
370
400
|
|
|
371
401
|
def test_ipv6_url_redaction_valid(self) -> None:
|
|
372
402
|
"""LOW-2: IPv6 URL redaction should produce valid URLs."""
|
|
373
|
-
from secretscreen._urls import
|
|
403
|
+
from secretscreen._urls import redact_url_credentials
|
|
374
404
|
|
|
375
|
-
result =
|
|
405
|
+
result = redact_url_credentials("redis://user:secret@[::1]:6379/0")
|
|
376
406
|
assert "secret" not in result
|
|
377
407
|
assert "[" in result # brackets preserved
|
|
378
408
|
assert "::1" in result
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""Tests for URL credential detection (Layer 4)."""
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from secretscreen._urls import has_url_credentials, redact_url_credentials
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TestUrlCredentialDetection:
|
|
9
|
+
"""URL credential detection."""
|
|
10
|
+
|
|
11
|
+
@pytest.mark.parametrize(
|
|
12
|
+
"url",
|
|
13
|
+
[
|
|
14
|
+
"postgres://admin:secret@localhost:5432/mydb",
|
|
15
|
+
"mysql://root:password@db.host/database",
|
|
16
|
+
"redis://:secretpass@redis.host:6379/0",
|
|
17
|
+
"https://user:pass@api.example.com/v1",
|
|
18
|
+
],
|
|
19
|
+
)
|
|
20
|
+
def test_detects_url_credentials(self, url: str) -> None:
|
|
21
|
+
assert has_url_credentials(url) is True
|
|
22
|
+
|
|
23
|
+
@pytest.mark.parametrize(
|
|
24
|
+
"url",
|
|
25
|
+
[
|
|
26
|
+
"https://example.com",
|
|
27
|
+
"postgres://localhost:5432/mydb",
|
|
28
|
+
"redis://redis.host:6379/0",
|
|
29
|
+
"not a url at all",
|
|
30
|
+
"",
|
|
31
|
+
"/var/lib/data",
|
|
32
|
+
],
|
|
33
|
+
)
|
|
34
|
+
def test_ignores_urls_without_credentials(self, url: str) -> None:
|
|
35
|
+
assert has_url_credentials(url) is False
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class TestUserinfoCredentials:
|
|
39
|
+
"""Userinfo with no password — the shape notification services use.
|
|
40
|
+
|
|
41
|
+
``discord://TOKEN@id`` has a username and no password, so a password-only
|
|
42
|
+
check reports it clean and the token prints verbatim.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
@pytest.mark.parametrize(
|
|
46
|
+
("url", "secret"),
|
|
47
|
+
[
|
|
48
|
+
("discord://Mzk4NjYxMTIzNDU2.GxYzAb.tokenvalue@1234567890", "Mzk4NjYxMTIzNDU2.GxYzAb.tokenvalue"),
|
|
49
|
+
("ntfy://tk_ab12cd34@ntfy.sh", "tk_ab12cd34"),
|
|
50
|
+
("telegram://110201543:AAHdqTcv@telegram", "AAHdqTcv"),
|
|
51
|
+
("matrix://user:pass@matrix.org", "pass"),
|
|
52
|
+
("pushover://shoutrrr:apptoken@usertoken", "apptoken"),
|
|
53
|
+
("teams://token@ntfy.example.com", "token"),
|
|
54
|
+
],
|
|
55
|
+
)
|
|
56
|
+
def test_notification_schemes_are_credentials(self, url: str, secret: str) -> None:
|
|
57
|
+
assert has_url_credentials(url) is True
|
|
58
|
+
assert secret not in redact_url_credentials(url)
|
|
59
|
+
|
|
60
|
+
@pytest.mark.parametrize(
|
|
61
|
+
"url",
|
|
62
|
+
[
|
|
63
|
+
"https://username@github.com/org/repo.git",
|
|
64
|
+
"ssh://git@github.com/org/repo.git",
|
|
65
|
+
"git://git@example.com/repo",
|
|
66
|
+
"ftp://anonymous@ftp.example.com/pub",
|
|
67
|
+
"postgres://appuser@db.lan:5432/nextcloud",
|
|
68
|
+
"redis://cacheuser@cache.lan:6379/0",
|
|
69
|
+
"mongodb://reader@mongo.lan/analytics",
|
|
70
|
+
],
|
|
71
|
+
)
|
|
72
|
+
def test_plain_userinfo_schemes_are_identities_not_secrets(self, url: str) -> None:
|
|
73
|
+
"""A bare username on a familiar transport is an identity, not a token."""
|
|
74
|
+
assert has_url_credentials(url) is False
|
|
75
|
+
assert redact_url_credentials(url) == url
|
|
76
|
+
|
|
77
|
+
def test_unknown_scheme_fails_closed(self) -> None:
|
|
78
|
+
"""A scheme nobody anticipated is treated as credential-bearing."""
|
|
79
|
+
assert has_url_credentials("someservice://abc123token@host") is True
|
|
80
|
+
|
|
81
|
+
def test_password_wins_over_plain_scheme(self) -> None:
|
|
82
|
+
"""The scheme judgement applies only to userinfo with no password."""
|
|
83
|
+
url = "https://user:s3cr3t@api.example.com/v1"
|
|
84
|
+
assert has_url_credentials(url) is True
|
|
85
|
+
result = redact_url_credentials(url)
|
|
86
|
+
assert "s3cr3t" not in result
|
|
87
|
+
assert "user" in result
|
|
88
|
+
|
|
89
|
+
def test_scheme_match_is_case_insensitive(self) -> None:
|
|
90
|
+
assert has_url_credentials("HTTPS://username@github.com/repo") is False
|
|
91
|
+
assert has_url_credentials("DISCORD://tokenvalue@1234567890") is True
|
|
92
|
+
|
|
93
|
+
def test_empty_password_falls_through_to_userinfo_rule(self) -> None:
|
|
94
|
+
"""``foo://user:@host`` has no secret in the password position."""
|
|
95
|
+
assert has_url_credentials("https://user:@host/path") is False
|
|
96
|
+
assert has_url_credentials("discord://tokenvalue:@host") is True
|
|
97
|
+
|
|
98
|
+
def test_empty_username_with_password(self) -> None:
|
|
99
|
+
result = redact_url_credentials("redis://:secretpass@redis.host:6379/0")
|
|
100
|
+
assert "secretpass" not in result
|
|
101
|
+
assert "redis.host" in result
|
|
102
|
+
assert "6379" in result
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class TestUrlPasswordRedaction:
|
|
106
|
+
"""URL credential partial redaction."""
|
|
107
|
+
|
|
108
|
+
def test_postgres_url(self) -> None:
|
|
109
|
+
result = redact_url_credentials("postgres://admin:secret@localhost:5432/mydb")
|
|
110
|
+
assert "secret" not in result
|
|
111
|
+
assert "admin" in result
|
|
112
|
+
assert "localhost" in result
|
|
113
|
+
assert "5432" in result
|
|
114
|
+
assert "REDACTED" in result
|
|
115
|
+
|
|
116
|
+
def test_preserves_path_and_query(self) -> None:
|
|
117
|
+
result = redact_url_credentials("https://user:pass@host/path?q=1#frag")
|
|
118
|
+
assert "/path" in result
|
|
119
|
+
assert "q=1" in result
|
|
120
|
+
assert "frag" in result
|
|
121
|
+
assert "pass" not in result
|
|
122
|
+
|
|
123
|
+
def test_custom_replacement(self) -> None:
|
|
124
|
+
result = redact_url_credentials("postgres://admin:secret@host/db", replacement="***")
|
|
125
|
+
assert "***" in result
|
|
126
|
+
assert "secret" not in result
|
|
127
|
+
|
|
128
|
+
def test_no_password_returns_unchanged(self) -> None:
|
|
129
|
+
url = "postgres://localhost/mydb"
|
|
130
|
+
assert redact_url_credentials(url) == url
|
|
131
|
+
|
|
132
|
+
def test_userinfo_redaction_preserves_everything_else(self) -> None:
|
|
133
|
+
result = redact_url_credentials("gotify://apptoken@gotify.lan:8080/message?priority=5#top")
|
|
134
|
+
assert "apptoken" not in result
|
|
135
|
+
assert "gotify.lan" in result
|
|
136
|
+
assert "8080" in result
|
|
137
|
+
assert "/message" in result
|
|
138
|
+
assert "priority=5" in result
|
|
139
|
+
assert "top" in result
|
|
140
|
+
|
|
141
|
+
def test_userinfo_redaction_drops_the_username(self) -> None:
|
|
142
|
+
"""The username IS the secret here, so preserving it would defeat the point."""
|
|
143
|
+
result = redact_url_credentials("discord://tokenvalue123@987654321")
|
|
144
|
+
assert "tokenvalue123" not in result
|
|
145
|
+
assert "987654321" in result
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class TestUrlRedactionEdgeCases:
|
|
149
|
+
"""Malformed, unusual, and adversarial URL shapes."""
|
|
150
|
+
|
|
151
|
+
def test_ipv6_host_keeps_brackets(self) -> None:
|
|
152
|
+
result = redact_url_credentials("redis://user:secret@[::1]:6379/0")
|
|
153
|
+
assert "[::1]" in result
|
|
154
|
+
assert "secret" not in result
|
|
155
|
+
|
|
156
|
+
def test_ipv6_host_with_userinfo_only(self) -> None:
|
|
157
|
+
result = redact_url_credentials("discord://tokenvalue@[2001:db8::1]:8443/path")
|
|
158
|
+
assert "[2001:db8::1]" in result
|
|
159
|
+
assert "tokenvalue" not in result
|
|
160
|
+
|
|
161
|
+
@pytest.mark.parametrize("wrapper", ["jdbc:", "odbc:", "JDBC:"])
|
|
162
|
+
def test_wrapped_schemes_with_userinfo(self, wrapper: str) -> None:
|
|
163
|
+
"""Wrapper prefixes hide the real scheme from urlsplit."""
|
|
164
|
+
result = redact_url_credentials(f"{wrapper}postgresql://admin:S3cr3t@prod-db:5432/main")
|
|
165
|
+
assert "S3cr3t" not in result
|
|
166
|
+
assert result.startswith(wrapper)
|
|
167
|
+
|
|
168
|
+
def test_missing_host(self) -> None:
|
|
169
|
+
result = redact_url_credentials("discord://tokenvalue@")
|
|
170
|
+
assert "tokenvalue" not in result
|
|
171
|
+
|
|
172
|
+
def test_percent_encoded_password_is_removed(self) -> None:
|
|
173
|
+
"""urlsplit decodes userinfo; the encoded form must not survive either."""
|
|
174
|
+
result = redact_url_credentials("postgres://admin:p%40ssw0rd@db.lan/app")
|
|
175
|
+
assert "p%40ssw0rd" not in result
|
|
176
|
+
assert "p@ssw0rd" not in result
|
|
177
|
+
|
|
178
|
+
def test_unparseable_url_returns_replacement_not_the_value(self) -> None:
|
|
179
|
+
"""A value we cannot parse must never be echoed back verbatim."""
|
|
180
|
+
# An invalid port makes urlsplit raise when .port is read.
|
|
181
|
+
result = redact_url_credentials("discord://tokenvalue@host:notaport/path")
|
|
182
|
+
assert "tokenvalue" not in result
|
|
183
|
+
|
|
184
|
+
def test_scheme_relative_and_garbage_inputs(self) -> None:
|
|
185
|
+
for value in ["://no-scheme@host", "http://", "://", "a://"]:
|
|
186
|
+
redact_url_credentials(value) # must not raise
|
|
187
|
+
|
|
188
|
+
def test_redaction_is_idempotent(self) -> None:
|
|
189
|
+
"""Re-screening already-screened output must be stable."""
|
|
190
|
+
once = redact_url_credentials("discord://tokenvalue@1234567890")
|
|
191
|
+
twice = redact_url_credentials(once)
|
|
192
|
+
assert once == twice
|
|
193
|
+
|
|
194
|
+
def test_password_redaction_is_idempotent(self) -> None:
|
|
195
|
+
once = redact_url_credentials("postgres://admin:secret@db.lan/app")
|
|
196
|
+
twice = redact_url_credentials(once)
|
|
197
|
+
assert once == twice
|
|
198
|
+
|
|
199
|
+
def test_no_scheme_is_not_a_credential(self) -> None:
|
|
200
|
+
assert has_url_credentials("user:password@host/path") is False
|
|
201
|
+
|
|
202
|
+
@pytest.mark.parametrize(
|
|
203
|
+
"url",
|
|
204
|
+
[
|
|
205
|
+
"http://[user:s3cr3t@internal.lan/db", # unclosed IPv6 bracket
|
|
206
|
+
"discord://tokenvalue@[::1", # truncated IPv6 literal
|
|
207
|
+
],
|
|
208
|
+
)
|
|
209
|
+
def test_unparseable_url_shapes_fail_closed(self, url: str) -> None:
|
|
210
|
+
"""A URL-looking value we cannot parse must be treated as a credential.
|
|
211
|
+
|
|
212
|
+
Reporting it clean let the whole value print verbatim, because the
|
|
213
|
+
redaction half — which does fail closed — was never reached.
|
|
214
|
+
"""
|
|
215
|
+
assert has_url_credentials(url) is True
|
|
216
|
+
assert "s3cr3t" not in redact_url_credentials(url)
|
|
217
|
+
assert "tokenvalue" not in redact_url_credentials(url)
|
|
218
|
+
|
|
219
|
+
def test_unparseable_url_is_redacted_end_to_end(self) -> None:
|
|
220
|
+
from secretscreen import audit_pair, redact_pair
|
|
221
|
+
|
|
222
|
+
value = "http://[user:s3cr3t@internal.lan/db"
|
|
223
|
+
assert audit_pair("NOTIFY", value) is not None
|
|
224
|
+
assert "s3cr3t" not in redact_pair("NOTIFY", value)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
class TestNetlocReplacementToken:
|
|
228
|
+
"""The replacement token is stripped of URL-structural characters.
|
|
229
|
+
|
|
230
|
+
Inside a netloc the default ``[REDACTED]`` cannot be used verbatim: any
|
|
231
|
+
``[`` makes urlsplit read the netloc as an IPv6 literal and raise, so the
|
|
232
|
+
redacted output would be unreadable on a second pass. Redaction inside a
|
|
233
|
+
URL therefore prints ``REDACTED`` without brackets. This is deliberate and
|
|
234
|
+
pinned here, because it is the one place the token differs from the rest
|
|
235
|
+
of the output.
|
|
236
|
+
"""
|
|
237
|
+
|
|
238
|
+
def test_default_token_loses_its_brackets_inside_a_url(self) -> None:
|
|
239
|
+
assert redact_url_credentials("postgres://admin:secret@db.lan/app") == "postgres://admin:REDACTED@db.lan/app"
|
|
240
|
+
|
|
241
|
+
def test_redacted_output_is_reparseable(self) -> None:
|
|
242
|
+
from urllib.parse import urlsplit
|
|
243
|
+
|
|
244
|
+
for url in ["postgres://admin:secret@db.lan/app", "discord://tokenvalue@1234567890"]:
|
|
245
|
+
urlsplit(redact_url_credentials(url)) # must not raise
|
|
246
|
+
|
|
247
|
+
@pytest.mark.parametrize("replacement", ["***", "<hidden>", "[hidden]", "XXX"])
|
|
248
|
+
def test_custom_replacements_survive_sanitisation(self, replacement: str) -> None:
|
|
249
|
+
result = redact_url_credentials("discord://tokenvalue@123", replacement=replacement)
|
|
250
|
+
assert "tokenvalue" not in result
|
|
251
|
+
assert replacement.strip("[]") in result
|
|
252
|
+
|
|
253
|
+
def test_replacement_of_only_structural_characters_falls_back(self) -> None:
|
|
254
|
+
"""A replacement that sanitises to nothing must not produce empty userinfo."""
|
|
255
|
+
result = redact_url_credentials("discord://tokenvalue@123", replacement="[]")
|
|
256
|
+
assert "tokenvalue" not in result
|
|
257
|
+
assert "REDACTED" in result
|
|
258
|
+
|
|
259
|
+
@pytest.mark.parametrize(
|
|
260
|
+
("replacement", "expected"),
|
|
261
|
+
[("a@b", "discord://ab@123"), ("x/y", "discord://xy@123"), ("@", "discord://REDACTED@123")],
|
|
262
|
+
)
|
|
263
|
+
def test_replacement_containing_netloc_delimiters(self, replacement: str, expected: str) -> None:
|
|
264
|
+
"""'@' and '/' would re-split the netloc, not just break the IPv6 check."""
|
|
265
|
+
assert redact_url_credentials("discord://tokenvalue@123", replacement=replacement) == expected
|
|
266
|
+
|
|
267
|
+
@pytest.mark.parametrize("url", ["discord://1234567890/path", "gotify://gotify.lan:8080/message"])
|
|
268
|
+
def test_credential_bearing_scheme_without_userinfo_is_untouched(self, url: str) -> None:
|
|
269
|
+
"""The scheme rule applies to userinfo, not to the scheme alone."""
|
|
270
|
+
assert has_url_credentials(url) is False
|
|
271
|
+
assert redact_url_credentials(url) == url
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
class TestLayerOneUrlInteraction:
|
|
275
|
+
"""Keys that match a secret pattern *and* end in a safe '_url' suffix.
|
|
276
|
+
|
|
277
|
+
The suffix vetoes layer 1's name match, so these reach layer 4 and get
|
|
278
|
+
partial redaction rather than whole-value replacement. Pinned because the
|
|
279
|
+
two rules interact and neither file makes that obvious on its own.
|
|
280
|
+
"""
|
|
281
|
+
|
|
282
|
+
@pytest.mark.parametrize("key", ["NOTIFY_TOKEN_URL", "WEBHOOK_SECRET_URL", "APP_PASSWORD_URL"])
|
|
283
|
+
def test_userinfo_credential_under_safe_suffix_key(self, key: str) -> None:
|
|
284
|
+
from secretscreen import redact_pair
|
|
285
|
+
|
|
286
|
+
result = redact_pair(key, "discord://tokenvalue@123")
|
|
287
|
+
assert "tokenvalue" not in result
|
|
288
|
+
assert "123" in result # partial, not whole-value replacement
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
"""URL credential detection and partial redaction.
|
|
2
|
-
|
|
3
|
-
Layer 4: detect and redact passwords embedded in URLs.
|
|
4
|
-
Only the password portion is replaced — username, host, path are preserved
|
|
5
|
-
for debugging utility.
|
|
6
|
-
"""
|
|
7
|
-
|
|
8
|
-
from __future__ import annotations
|
|
9
|
-
|
|
10
|
-
from urllib.parse import urlsplit, urlunsplit
|
|
11
|
-
|
|
12
|
-
# Default replacement — matches _core.REDACTED but _urls is a leaf module,
|
|
13
|
-
# so we define our own default to avoid circular imports.
|
|
14
|
-
_DEFAULT_REPLACEMENT = "[REDACTED]"
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
# Multi-scheme URL prefixes that wrap a standard URL.
|
|
18
|
-
# urlsplit treats these as the scheme, making credentials invisible.
|
|
19
|
-
_URL_WRAPPERS = ("jdbc:", "odbc:")
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
def _strip_url_wrapper(value: str) -> str:
|
|
23
|
-
"""Strip multi-scheme prefixes so urlsplit can parse credentials."""
|
|
24
|
-
lower = value.lower()
|
|
25
|
-
for prefix in _URL_WRAPPERS:
|
|
26
|
-
if lower.startswith(prefix):
|
|
27
|
-
return value[len(prefix) :]
|
|
28
|
-
return value
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
def has_url_credentials(value: str) -> bool:
|
|
32
|
-
"""Check if a value contains a URL with embedded credentials."""
|
|
33
|
-
if "://" not in value:
|
|
34
|
-
return False
|
|
35
|
-
try:
|
|
36
|
-
parsed = urlsplit(_strip_url_wrapper(value))
|
|
37
|
-
return bool(parsed.scheme and parsed.password)
|
|
38
|
-
except (ValueError, AttributeError):
|
|
39
|
-
return False
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
def redact_url_password(value: str, replacement: str = _DEFAULT_REPLACEMENT) -> str:
|
|
43
|
-
"""Replace only the password portion of a credential URL.
|
|
44
|
-
|
|
45
|
-
Preserves username, host, path, query, and fragment for debugging.
|
|
46
|
-
"""
|
|
47
|
-
try:
|
|
48
|
-
raw = _strip_url_wrapper(value)
|
|
49
|
-
prefix = value[: len(value) - len(raw)] # preserve original prefix casing
|
|
50
|
-
parsed = urlsplit(raw)
|
|
51
|
-
if not parsed.password:
|
|
52
|
-
return value
|
|
53
|
-
|
|
54
|
-
user = parsed.username or ""
|
|
55
|
-
host = parsed.hostname or ""
|
|
56
|
-
# Re-add brackets for IPv6 addresses
|
|
57
|
-
if host and ":" in host:
|
|
58
|
-
host = f"[{host}]"
|
|
59
|
-
port_str = f":{parsed.port}" if parsed.port else ""
|
|
60
|
-
new_netloc = f"{user}:{replacement}@{host}{port_str}"
|
|
61
|
-
|
|
62
|
-
return prefix + urlunsplit(
|
|
63
|
-
(
|
|
64
|
-
parsed.scheme,
|
|
65
|
-
new_netloc,
|
|
66
|
-
parsed.path,
|
|
67
|
-
parsed.query,
|
|
68
|
-
parsed.fragment,
|
|
69
|
-
)
|
|
70
|
-
)
|
|
71
|
-
except (ValueError, AttributeError):
|
|
72
|
-
return _DEFAULT_REPLACEMENT
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
"""Tests for URL credential detection (Layer 4)."""
|
|
2
|
-
|
|
3
|
-
import pytest
|
|
4
|
-
|
|
5
|
-
from secretscreen._urls import has_url_credentials, redact_url_password
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
class TestUrlCredentialDetection:
|
|
9
|
-
"""URL credential detection."""
|
|
10
|
-
|
|
11
|
-
@pytest.mark.parametrize(
|
|
12
|
-
"url",
|
|
13
|
-
[
|
|
14
|
-
"postgres://admin:secret@localhost:5432/mydb",
|
|
15
|
-
"mysql://root:password@db.host/database",
|
|
16
|
-
"redis://:secretpass@redis.host:6379/0",
|
|
17
|
-
"https://user:pass@api.example.com/v1",
|
|
18
|
-
],
|
|
19
|
-
)
|
|
20
|
-
def test_detects_url_credentials(self, url: str) -> None:
|
|
21
|
-
assert has_url_credentials(url) is True
|
|
22
|
-
|
|
23
|
-
@pytest.mark.parametrize(
|
|
24
|
-
"url",
|
|
25
|
-
[
|
|
26
|
-
"https://example.com",
|
|
27
|
-
"postgres://localhost:5432/mydb",
|
|
28
|
-
"redis://redis.host:6379/0",
|
|
29
|
-
"not a url at all",
|
|
30
|
-
"",
|
|
31
|
-
"/var/lib/data",
|
|
32
|
-
],
|
|
33
|
-
)
|
|
34
|
-
def test_ignores_urls_without_credentials(self, url: str) -> None:
|
|
35
|
-
assert has_url_credentials(url) is False
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
class TestUrlPasswordRedaction:
|
|
39
|
-
"""URL password partial redaction."""
|
|
40
|
-
|
|
41
|
-
def test_postgres_url(self) -> None:
|
|
42
|
-
result = redact_url_password("postgres://admin:secret@localhost:5432/mydb")
|
|
43
|
-
assert "secret" not in result
|
|
44
|
-
assert "admin" in result
|
|
45
|
-
assert "localhost" in result
|
|
46
|
-
assert "5432" in result
|
|
47
|
-
assert "[REDACTED]" in result
|
|
48
|
-
|
|
49
|
-
def test_preserves_path_and_query(self) -> None:
|
|
50
|
-
result = redact_url_password("https://user:pass@host/path?q=1#frag")
|
|
51
|
-
assert "/path" in result
|
|
52
|
-
assert "q=1" in result
|
|
53
|
-
assert "frag" in result
|
|
54
|
-
assert "pass" not in result
|
|
55
|
-
|
|
56
|
-
def test_custom_replacement(self) -> None:
|
|
57
|
-
result = redact_url_password("postgres://admin:secret@host/db", replacement="***")
|
|
58
|
-
assert "***" in result
|
|
59
|
-
assert "secret" not in result
|
|
60
|
-
|
|
61
|
-
def test_no_password_returns_unchanged(self) -> None:
|
|
62
|
-
url = "postgres://localhost/mydb"
|
|
63
|
-
assert redact_url_password(url) == url
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|