Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(security): read a truncated digest or a cache key's md5 as an id, not a weak hash (#4201)

Raghav Chamadiya36a60a81c2e1
diff --git a/packages/core/src/repowise/core/analysis/security/patterns.py b/packages/core/src/repowise/core/analysis/security/patterns.py
index 1d570ef6e..9e4d84bcd 100644
--- a/packages/core/src/repowise/core/analysis/security/patterns.py
+++ b/packages/core/src/repowise/core/analysis/security/patterns.py
@@ -11,7 +11,7 @@ import re
# the same way ``HEALTH_ANALYZER_VERSION`` forces a full health re-score
# (#3072). Without this, a scanner fix only ever reaches a file a user
# happens to edit.
-SECURITY_SCANNER_VERSION = 3
+SECURITY_SCANNER_VERSION = 4
# ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/analysis/security/refinements.py b/packages/core/src/repowise/core/analysis/security/refinements.py
index f79269960..0ee454986 100644
--- a/packages/core/src/repowise/core/analysis/security/refinements.py
+++ b/packages/core/src/repowise/core/analysis/security/refinements.py
@@ -63,6 +63,43 @@ def _call_text(masked: list[str], lineno: int, start: int, limit: int = 600) ->
return code
+# ``.hexdigest()[:8]`` or ``.digest("hex").slice(0, 8)`` right after the call.
+_TRUNCATED_DIGEST = re.compile(
+ r"\A(?:\s*\.\s*update\s*\([^()]*(?:\([^()]*\)[^()]*)*\))*"
+ r"\s*\.\s*(?:hex)?digest\s*\([^()]*\)\s*"
+ r"(?:\[\s*0?\s*:\s*(\d{1,2})\s*\]|\.\s*(?:slice|substring|substr)\s*\(\s*0\s*,\s*(\d{1,2})\s*\))"
+)
+_ID_PREFIX_MAX = 16 # longer is most of the digest
+# The assignment target of a digest that names content.
+_DIGEST_KEY_NAME = re.compile(
+ r"(?i)(?<![a-z])(?:e_?tag|cache_?key|slug)s?"
+ r"""(?:["']?\s*:\s*|(?:\s*:\s*[\w.|<>\[\] ]+)?\s*=(?!=))[^=:]*\Z"""
+)
+_CREDENTIAL_WORD = re.compile(
+ r"(?i)passw|pwd|\bpw\b|\bpass\b|salt|\botp\b|bearer|secret|token|credential"
+ r"|api_?key|auth(?!or)"
+)
+
+
+def _weak_hash_is_an_id(line: str, masked: list[str], lineno: int, start: int) -> bool:
+ """Whether the weak hash at *start* on *line* is a declared non-security
+ use: ``usedforsecurity=False``, a digest truncated to a short prefix where
+ it is computed, or one assigned to a cache key, ETag or slug. A line that
+ names a credential is only ever exempt by ``usedforsecurity=False``."""
+ call = _call_text(masked, lineno, start)
+ if _NOT_FOR_SECURITY.search(call):
+ return True
+ # ``hashlib.md5`` passed to ``hmac.new`` names a MAC's algorithm, not an id.
+ if _CREDENTIAL_WORD.search(line) or "(" not in call:
+ return False
+ if "\n" not in call:
+ code = masked[lineno - 1] if lineno <= len(masked) else line
+ cut = _TRUNCATED_DIGEST.match(code[start + len(call) :])
+ if cut and int(cut.group(1) or cut.group(2)) <= _ID_PREFIX_MAX:
+ return True
+ return bool(_DIGEST_KEY_NAME.search(line[:start]))
+
+
_TS_TYPE_VALUE = re.compile(
r"(?:string|number|boolean|any|unknown|never|undefined|null|TrustedHTML)\b"
r"(?:\s*\|\s*[\w$.]+)*\s*"
diff --git a/packages/core/src/repowise/core/analysis/security/scanner.py b/packages/core/src/repowise/core/analysis/security/scanner.py
index 6ddc8e2d8..5f5bf3e3f 100644
--- a/packages/core/src/repowise/core/analysis/security/scanner.py
+++ b/packages/core/src/repowise/core/analysis/security/scanner.py
@@ -39,11 +39,10 @@ from .patterns import (
SECRET_KINDS,
)
from .refinements import (
- _NOT_FOR_SECURITY,
- _call_text,
_interpolates_sql_value,
_is_html_type_annotation,
_match_starting_in,
+ _weak_hash_is_an_id,
)
from .suppression import IGNORE_TOKEN, _allowlisted_lines, marker_silences
@@ -113,11 +112,9 @@ def scan_source(file_path: str, source: str, symbols: Iterable[Any] = ()) -> lis
if match and not _interpolates_sql_value(line, match.start(), lines, lineno):
match = None
elif kind == "weak_hash":
- # Written in code, and not declared a non-security use.
+ # Written in code, and not a declared or visible id (refinements).
match = _match_starting_in(pattern, line, masked_line(lineno, line))
- if match and _NOT_FOR_SECURITY.search(
- _call_text(mask()[1], lineno, match.start())
- ):
+ if match and _weak_hash_is_an_id(line, mask()[1], lineno, match.start()):
match = None
elif kind in _KEYWORD_KINDS:
# ``password = "..."`` in a comment or docstring is an example.
diff --git a/tests/unit/analysis/test_security_scan.py b/tests/unit/analysis/test_security_scan.py
index 2117859c6..6fc01bcd8 100644
--- a/tests/unit/analysis/test_security_scan.py
+++ b/tests/unit/analysis/test_security_scan.py
@@ -691,6 +691,26 @@ class TestScanFile:
("a.py", 'key = hashlib.sha1(f"({a})".encode(), usedforsecurity=False)\n', False),
("a.py", 'key = hashlib.sha1(b"usedforsecurity=False")\n', True),
("a.py", "key = hashlib.sha1(\n text.encode()\n)\nok = sha256(b, usedforsecurity=False)\n", True),
+ # Cut to a few characters where it is computed, or kept as a key: an id.
+ ("a.py", "short = hashlib.md5(name.encode()).hexdigest()[:8]\n", False),
+ ("a.py", "short = hashlib.sha1(name.encode()).hexdigest()[0:12]\n", False),
+ ("a.js", 'const id = crypto.createHash("md5").update(s).digest("hex").slice(0, 8);\n', False),
+ ("a.py", "etag = hashlib.md5(body).hexdigest()\n", False),
+ ("a.py", "cache_key = hashlib.sha1(url.encode()).hexdigest()\n", False),
+ ("a.ts", 'const cacheKey = createHash("md5").update(url).digest("hex");\n', False),
+ ("a.py", 'slug = title + "-" + md5(title.encode()).hexdigest()\n', False),
+ # A credential stays a finding, truncated or named as a key.
+ ("a.py", "pw = hashlib.md5(password.encode()).hexdigest()[:8]\n", True),
+ ("a.py", "cache_key = hashlib.md5(token).hexdigest()\n", True),
+ ("a.py", "digest = hashlib.md5(data).hexdigest()[8:]\n", True),
+ ("a.py", "full = hashlib.md5(data).digest()\n", True),
+ ("a.py", "pw = hashlib.md5(p.encode()).hexdigest()[:8]\n", True),
+ ("a.py", "whole = hashlib.md5(data).hexdigest()[:32]\n", True),
+ ("a.py", "mac = hmac.new(k, m, hashlib.md5).hexdigest()[:8]\n", True),
+ ("a.py", "if cache_key in seen: h = hashlib.md5(data).hexdigest()\n", True),
+ ("a.ts", 'const cacheKey: string = createHash("md5").update(url).digest("hex");\n', False),
+ ("a.py", 'row = {"etag": hashlib.md5(body).hexdigest()}\n', False),
+ ("a.py", "author_slug = hashlib.md5(name.encode()).hexdigest()\n", False),
],
)
def test_weak_hash_is_an_algorithm_in_use(self, path: str, source: str, expected: bool) -> None: