secretscreen 0.2.1__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.
Files changed (40) hide show
  1. {secretscreen-0.2.1 → secretscreen-0.3.0}/.gitignore +5 -0
  2. {secretscreen-0.2.1 → secretscreen-0.3.0}/PKG-INFO +20 -7
  3. {secretscreen-0.2.1 → secretscreen-0.3.0}/README.md +11 -0
  4. {secretscreen-0.2.1 → secretscreen-0.3.0}/pyproject.toml +6 -4
  5. {secretscreen-0.2.1 → secretscreen-0.3.0}/src/secretscreen/__init__.py +4 -1
  6. {secretscreen-0.2.1 → secretscreen-0.3.0}/src/secretscreen/_core.py +2 -2
  7. {secretscreen-0.2.1 → secretscreen-0.3.0}/src/secretscreen/_parsers.py +7 -3
  8. secretscreen-0.3.0/src/secretscreen/_urls.py +169 -0
  9. {secretscreen-0.2.1 → secretscreen-0.3.0}/tests/test_cli.py +2 -2
  10. {secretscreen-0.2.1 → secretscreen-0.3.0}/tests/test_core.py +5 -5
  11. secretscreen-0.3.0/tests/test_urls.py +288 -0
  12. secretscreen-0.2.1/src/secretscreen/_urls.py +0 -72
  13. secretscreen-0.2.1/tests/test_urls.py +0 -63
  14. {secretscreen-0.2.1 → secretscreen-0.3.0}/.github/FUNDING.yml +0 -0
  15. {secretscreen-0.2.1 → secretscreen-0.3.0}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
  16. {secretscreen-0.2.1 → secretscreen-0.3.0}/.github/dependabot.yml +0 -0
  17. {secretscreen-0.2.1 → secretscreen-0.3.0}/.github/pull_request_template.md +0 -0
  18. {secretscreen-0.2.1 → secretscreen-0.3.0}/.github/workflows/ci.yml +0 -0
  19. {secretscreen-0.2.1 → secretscreen-0.3.0}/.github/workflows/codeql.yml +0 -0
  20. {secretscreen-0.2.1 → secretscreen-0.3.0}/.github/workflows/dependabot-automerge.yml +0 -0
  21. {secretscreen-0.2.1 → secretscreen-0.3.0}/.github/workflows/publish.yml +0 -0
  22. {secretscreen-0.2.1 → secretscreen-0.3.0}/.github/workflows/scorecard.yml +0 -0
  23. {secretscreen-0.2.1 → secretscreen-0.3.0}/CODE_OF_CONDUCT.md +0 -0
  24. {secretscreen-0.2.1 → secretscreen-0.3.0}/CONTRIBUTING.md +0 -0
  25. {secretscreen-0.2.1 → secretscreen-0.3.0}/LICENSE +0 -0
  26. {secretscreen-0.2.1 → secretscreen-0.3.0}/NOTICE +0 -0
  27. {secretscreen-0.2.1 → secretscreen-0.3.0}/SECURITY.md +0 -0
  28. {secretscreen-0.2.1 → secretscreen-0.3.0}/docs/audits/security-audit-2026-04-05.md +0 -0
  29. {secretscreen-0.2.1 → secretscreen-0.3.0}/src/secretscreen/_cli.py +0 -0
  30. {secretscreen-0.2.1 → secretscreen-0.3.0}/src/secretscreen/_entropy.py +0 -0
  31. {secretscreen-0.2.1 → secretscreen-0.3.0}/src/secretscreen/_formats.py +0 -0
  32. {secretscreen-0.2.1 → secretscreen-0.3.0}/src/secretscreen/_keys.py +0 -0
  33. {secretscreen-0.2.1 → secretscreen-0.3.0}/src/secretscreen/gitleaks.toml +0 -0
  34. {secretscreen-0.2.1 → secretscreen-0.3.0}/src/secretscreen/py.typed +0 -0
  35. {secretscreen-0.2.1 → secretscreen-0.3.0}/tests/__init__.py +0 -0
  36. {secretscreen-0.2.1 → secretscreen-0.3.0}/tests/test_architecture.py +0 -0
  37. {secretscreen-0.2.1 → secretscreen-0.3.0}/tests/test_entropy.py +0 -0
  38. {secretscreen-0.2.1 → secretscreen-0.3.0}/tests/test_formats.py +0 -0
  39. {secretscreen-0.2.1 → secretscreen-0.3.0}/tests/test_keys.py +0 -0
  40. {secretscreen-0.2.1 → secretscreen-0.3.0}/tests/test_parsers.py +0 -0
@@ -14,3 +14,8 @@ build/
14
14
  *.swo
15
15
  .env
16
16
  .venv/
17
+
18
+ # coverage artifacts
19
+ .coverage
20
+ .coverage.*
21
+ htmlcov/
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: secretscreen
3
- Version: 0.2.1
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,>=1.10; extra == 'dev'
26
- Requires-Dist: pytest-cov>=5.0; extra == 'dev'
27
- Requires-Dist: pytest>=7.0; extra == 'dev'
28
- Requires-Dist: ruff<0.17,>=0.4; extra == 'dev'
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
@@ -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
@@ -4,15 +4,16 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "secretscreen"
7
- version = "0.2.1"
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>=7.0", "pytest-cov>=5.0", "ruff>=0.4,<0.17", "mypy>=1.10,<3"]
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.2.1"
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, redact_url_password
19
+ from secretscreen._urls import has_url_credentials, redact_url_credentials
20
20
 
21
21
  REDACTED = "[REDACTED]"
22
22
 
@@ -317,7 +317,7 @@ def _apply_redaction(
317
317
  Used by both redact_pair and _redact_recursive.
318
318
  """
319
319
  if finding.layer == "url_credentials":
320
- return redact_url_password(value, config.replacement)
320
+ return redact_url_credentials(value, config.replacement)
321
321
 
322
322
  if finding.layer == "structured_parsing":
323
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:[REDACTED]@db.internal:5432/prod" in out
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:[REDACTED]@db:5432/prod"
192
+ assert out.strip() == "postgres://admin:REDACTED@db:5432/prod"
193
193
 
194
194
  @pytest.mark.parametrize(
195
195
  ("name", "content", "marker"),
@@ -356,7 +356,7 @@ class TestSecurityFixes:
356
356
 
357
357
  # Same URL under the cap is redacted normally.
358
358
  small_url = "postgres://user:pw@host/db"
359
- assert redact_pair("DATABASE_URL", small_url) == "postgres://user:[REDACTED]@host/db"
359
+ assert redact_pair("DATABASE_URL", small_url) == "postgres://user:REDACTED@host/db"
360
360
 
361
361
  def test_deeply_nested_dict_does_not_crash(self) -> None:
362
362
  """MEDIUM-4: redact_dict should handle deeply nested dicts without RecursionError."""
@@ -391,18 +391,18 @@ class TestSecurityFixes:
391
391
 
392
392
  def test_jdbc_url_redacted(self) -> None:
393
393
  """LOW-1: JDBC URLs should have passwords redacted."""
394
- from secretscreen._urls import redact_url_password
394
+ from secretscreen._urls import redact_url_credentials
395
395
 
396
- result = redact_url_password("jdbc:postgresql://admin:S3cr3t@prod-db:5432/main")
396
+ result = redact_url_credentials("jdbc:postgresql://admin:S3cr3t@prod-db:5432/main")
397
397
  assert "S3cr3t" not in result
398
398
  assert "admin" in result
399
399
  assert result.startswith("jdbc:")
400
400
 
401
401
  def test_ipv6_url_redaction_valid(self) -> None:
402
402
  """LOW-2: IPv6 URL redaction should produce valid URLs."""
403
- from secretscreen._urls import redact_url_password
403
+ from secretscreen._urls import redact_url_credentials
404
404
 
405
- result = redact_url_password("redis://user:secret@[::1]:6379/0")
405
+ result = redact_url_credentials("redis://user:secret@[::1]:6379/0")
406
406
  assert "secret" not in result
407
407
  assert "[" in result # brackets preserved
408
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