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.

fix(security-scan): report credentials, not examples of them (#2660)

Raghav Chamadiyacb245215d879
diff --git a/docs/layers/SECURITY.md b/docs/layers/SECURITY.md
index 36807d7bf..b8f68d544 100644
--- a/docs/layers/SECURITY.md
+++ b/docs/layers/SECURITY.md
@@ -51,21 +51,21 @@ Findings also appear on the Security tab of the code-health page, and at
Twenty-two patterns plus a symbol-name scan, giving twenty-three kinds across
three severities. Severity is a fixed property of the pattern, with one
-exception: a secret kind found in test material, or under a directory named
+exception: any finding in test material, or under a directory named
`test`, `tests`, `__tests__`, `__test__`, `fixtures`, `__fixtures__`, `spec`,
`specs`, `mock`, `mocks`, `__mocks__`, `example` or `examples`, is recorded at
-`low`, since those are mostly fake keys but a real one is still
-worth seeing. Nothing is scored, ranked, or aggregated.
+`low`. Keys there are mostly fake and calls there do not ship, but a real one
+is still worth seeing. Nothing is scored, ranked, or aggregated.
| Kind | Severity | Matches |
|------|----------|---------|
| `eval_call` | high | `eval(...)`, including a receiver chain (`vm.eval(`, `foo.bar.eval(`) |
-| `exec_call` | high | `exec(...)`, same receiver handling. Outside Python only in a file that names `child_process`, and there also `execFile` / `execSync` |
+| `exec_call` | high | `exec(...)`, same receiver handling. Outside Python only a call through a name bound to `child_process` (a namespace, a named import, or the `require` result), covering `execFile` / `execSync` too |
| `pickle_loads` | high | `pickle.loads` |
| `subprocess_shell_true` | high | `subprocess.*` with `shell=True`, including across physical lines |
| `os_system` | high | `os.system` |
-| `hardcoded_password` | high | an assignment of a quoted literal to a name containing `password`, any case |
-| `hardcoded_secret` | high | the same for a name containing `api_key`, `apikey`, `secret`, `token` or `access_key`. A snake_case value (a constant holding a key's name) or a template placeholder (`{{ ... }}`, `${...}`) is skipped, and a value one of the vendor kinds below already reports is not reported twice |
+| `hardcoded_password` | high | an assignment of a quoted literal to a name containing `password`, any case, where the name is code (not inside a comment, docstring or string) |
+| `hardcoded_secret` | high | the same for a name containing `api_key`, `apikey`, `secret`, `token` or `access_key`. A snake_case value (a constant holding a key's name) or a template placeholder (`{{ ... }}`, `${...}`, `$(...)`) is skipped, and a value one of the vendor kinds below already reports is not reported twice |
| `aws_access_key` | high | an AWS access key ID (`AKIA`/`ASIA` + 16 chars), regardless of variable name |
| `github_token` | high | a GitHub PAT, OAuth, app, or refresh token (`ghp_`/`gho_`/`ghu_`/`ghs_`/`ghr_`/`github_pat_`), regardless of variable name |
| `slack_token` | high | a Slack token (`xoxb-`, `xoxa-`, `xoxp-`, `xoxr-`, `xoxs-`), regardless of variable name |
@@ -78,7 +78,7 @@ worth seeing. Nothing is scored, ranked, or aggregated.
| `weak_hash` | low | the words `md5` or `sha1` |
| `unsafe_inner_html` | med | `__html:` (React's `dangerouslySetInnerHTML` shape) assigned a non-literal value |
| `template_literal_sql` | med | a JS/TS template literal containing `SELECT`+`FROM` or `UPDATE`+`SET` and an interpolation |
-| `public_env_secret` | high | a secret-shaped name (`API_KEY`, `SECRET`, `TOKEN`, `PASSWORD`) behind a `NEXT_PUBLIC_` or `VITE_` prefix, excluding `..._ANON_...` |
+| `public_env_secret` | high | a secret-shaped name (`API_KEY`, `SECRET`, `TOKEN`, `PASSWORD`) behind a `NEXT_PUBLIC_` or `VITE_` prefix, excluding `..._ANON_...`, outside comments |
| `new_function_call` | high | `new Function(...)` |
| `reject_unauthorized_false` | med | `rejectUnauthorized: false` |
| `security_sensitive_symbol` | low | a symbol whose name contains `auth`, `token`, `password`, `jwt`, `session` or `crypto` |
@@ -93,10 +93,25 @@ they are found by walking the AST, so a match is a real call rather than a
substring, with a bounded lexical fallback when the file does not parse. Other
languages get the lexical path, over source with comments and string literals
masked out, so an `eval(` inside a comment does not fire. Outside Python
-`exec_call` carries one more condition: the file has to name `child_process`,
-searched in raw source because the module usually arrives as a string literal
-that masking would blank. Every other pattern in the table is a plain regex over
-one line of raw source, comments included.
+`exec_call` carries one more condition: the call has to go through a name the
+file binds to `child_process`. The imports are read from raw source because the
+module arrives as a string literal that masking would blank.
+
+**Text that describes code is not code.** `pickle_loads`, `os_system`,
+`subprocess_shell_true` and `new_function_call` match over the same masked source, so a docstring or a
+comment naming the call does not fire. The two keyword secret kinds need their
+name to be code, so `password = "..."` in a doctest is an example, not a
+password, and `public_env_secret` ignores a comment naming the variable. The
+vendor key shapes (`aws_access_key` and the rest) still match anywhere,
+comments included, because a real key pasted into a comment is still a leak.
+Prose files (`.md`, `.mdx`, `.rst`, `.txt`, `.adoc`) are scanned for secret
+kinds only.
+
+**Examples of a credential are not one.** A keyword value that is elided or
+templated (`...`, a typographic ellipsis, `<your key>`, `your-`, `xxx`,
+`example`, `placeholder`, `dummy`, `fake`, `changeme`), shorter than eight
+characters, a short single-case word (`api_key="lmstudio"`, the dummy a local
+server's client requires), or a CSS custom property (`--chart-1`) is skipped.
**Two patterns see across lines.** `private_key_pem` needs the body line after
its header, and `subprocess.run(` opening on one line with
@@ -138,27 +153,24 @@ trufflehog; history mode below is complementary to those, not a replacement.
**Dependencies.** No CVE lookup, no advisory feed, no SBOM. Nothing here looks
outside your source.
-**False positives are expected.** `weak_hash` fires on the word `md5` anywhere,
-including in a comment explaining why md5 was removed. `hardcoded_password`
-fires on test fixtures and on empty placeholder credentials. The layer reports
-signals for a human to read, and it is tuned to say too much rather than too
-little.
+**False positives are still possible.** `weak_hash` fires on the word `md5`
+anywhere, including in a comment explaining why md5 was removed. The high
+kinds are tuned the other way: a `high` should be something to act on, so a
+match that is only probably real is dropped.
**Two of them are worth knowing before you read a report.**
`exec` is not a global in JavaScript; the name belongs to `RegExp.prototype.exec`,
so the receiver-chain prefix in the pattern would otherwise match
-`re.exec(expr)`, `/x/.exec(s)` and `cellPattern.exec(xml)` — ordinary parsing
-code — at `high`. Outside Python the kind is gated on the file naming
-`child_process`, which is where the dangerous call comes from. The gate is per
-file rather than per call, so a file that both spawns a process and parses text
-with regexes still reports every `exec(` in it. That residual is deliberate,
-and covered by a test rather than left implicit.
-
-The per-line patterns run on raw source, comments included. A comment that
-spells out a credential assignment reports itself as a `hardcoded_secret`, and
-`weak_hash` fires on a comment explaining why md5 was removed. Only the
-`eval`/`exec` path masks comments and string literals; nothing else does.
+`re.exec(expr)`, `/x/.exec(s)` and `cellPattern.exec(xml)` (ordinary parsing
+code) at `high`. Outside Python the kind is resolved through the file's own
+`child_process` bindings, which is where the dangerous call comes from: a
+file's own function named `exec`, or a regex `.exec` beside a `spawn` import,
+does not fire.
+
+The remaining per-line patterns (`weak_hash`, the SQL kinds, the TLS kinds,
+`unsafe_inner_html`) run on raw source, comments included,
+so `weak_hash` still fires on a comment explaining why md5 was removed.
**Five patterns for JavaScript and TypeScript, measured the same way as the
`exec_call` and secret-case fixes above** — a 17-repository, 1109-file corpus,
@@ -248,7 +260,7 @@ It judges what the change adds, not the repository:
change. A code smell added and removed inside the change does not count.
`--fail-on` names the lowest severity that fails (`high` by default, then
-`med`, `low`). A secret under a test, fixture, spec, mock or example path is
+`med`, `low`). A finding under a test, fixture, spec, mock or example path is
`low` (see above), so under the default it shows as a warning and does not
fail; pass `--fail-on low` to fail on those too. Exit codes are the ones every
repowise CI gate uses: `0` passed,
@@ -323,7 +335,7 @@ One table, `security_findings`, written by both scan paths:
|---|---|
| `file_path` | Repo-relative |
| `kind` | One of the kinds in the table above |
-| `severity` | `high`, `med`, `low`: fixed per pattern, except a secret kind in test material is `low` |
+| `severity` | `high`, `med`, `low`: fixed per pattern, except a finding in test material is `low`. The Overview reads `med` as `medium` |
| `snippet` | Matched line, trimmed to 120 characters, credential values masked (`AKIA****`); a symbol name for `security_sensitive_symbol`. The raw value is never stored |
| `line_number` | As of scan time; verified at serve time |
| `commit_sha` | Empty for working-tree rows, the introducing commit for history rows |
diff --git a/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py b/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py
index daf5f0d78..5f13ede5d 100644
--- a/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py
+++ b/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py
@@ -37,6 +37,9 @@ _QUOTED = re.compile(r"""["']([^"']*)["']""")
def _looks_like_code(path: str, snippet: str) -> bool:
+ # The scanner applies these checks to the raw value, so a fresh row already
+ # passed them. They stay for rows an older scanner stored: a row is only
+ # rewritten when its file is rescanned.
lowered = path.lower()
if lowered.endswith(tuple(DOC_EXTENSIONS)) or lowered.startswith("docs/") or "/docs/" in lowered:
return False
diff --git a/packages/core/src/repowise/core/analysis/security_scan.py b/packages/core/src/repowise/core/analysis/security_scan.py
index bd760355c..a55c404c6 100644
--- a/packages/core/src/repowise/core/analysis/security_scan.py
+++ b/packages/core/src/repowise/core/analysis/security_scan.py
@@ -47,9 +47,14 @@ _CREDENTIAL_SUBSTRING_PLACEHOLDERS: tuple[str, ...] = (
"your_",
"your-",
"...",
+ "\u2026", # a typographic ellipsis
"fixture",
)
+# Broader than ``is_test_related_path`` on purpose. That one asks whether a file
+# is a test and keeps bare ``fixtures/``, ``mocks/`` and ``spec/`` as production
+# outside a test tree; this asks whether a match there is probably fake, and a
+# ``high`` that is only probably real is not one to raise.
_LOW_SEVERITY_PATH_TOKENS: frozenset[str] = frozenset(
{
"test",
@@ -68,13 +73,16 @@ _LOW_SEVERITY_PATH_TOKENS: frozenset[str] = frozenset(
}
)
+# An angle-bracket slot (``sk-<your key>``) is a template, wherever it sits.
+_ANGLE_SLOT = re.compile(r"<[^<>]*>")
+
def _is_valid_credential_value(val: str) -> bool:
"""True when *val* is at least 8 chars and not a known placeholder."""
if len(val) < 8:
return False
v = val.lower().strip()
- if v.startswith("<") or v in _CREDENTIAL_EXACT_PLACEHOLDERS:
+ if v.startswith("<") or _ANGLE_SLOT.search(v) or v in _CREDENTIAL_EXACT_PLACEHOLDERS:
return False
return not any(p in v for p in _CREDENTIAL_SUBSTRING_PLACEHOLDERS)
@@ -110,11 +118,52 @@ _CALL_KINDS = frozenset(kind for _, kind, _ in _CALL_PATTERNS)
# ``exec_call`` hit outside Python was a regex match and none was a process
# spawn, so the kind was pure noise on those languages.
#
-# The dangerous call in JavaScript comes from ``child_process``, so that is what
-# gates it: a file that never names the module cannot spawn one. ``eval`` needs
-# no such gate — it is a genuine global there.
-_CHILD_PROCESS_IMPORT = re.compile(r"child_process|node:child_process")
-_JS_EXEC_CALL = re.compile(r"(?<![\w$])(?:[A-Za-z_$][\w$]*\s*\.\s*)*exec(?:File)?(?:Sync)?\s*\(")
+# The dangerous call in JavaScript comes from ``child_process``, so only a call
+# through a name bound to that module counts: a namespace (``cp.exec(``), a named
+# import (``exec(`` after ``import { exec } from "child_process"``) or the
+# ``require`` result itself. A file's own function named ``exec``, or a regex's
+# ``.exec`` next to an unrelated ``spawn`` import, is not a shell. ``eval`` needs
+# no such gate: it is a genuine global there.
+_CP_MODULE = r"""['"](?:node:)?child_process['"]"""
+_JS_NAME = r"[A-Za-z_$][\w$]*"
+_CP_NAMESPACE = re.compile(
+ rf"import\s+(?:\*\s*as\s+)?({_JS_NAME})\s*(?:,\s*\{{[^}}]*\}}\s*)?from\s*{_CP_MODULE}"
+ rf"|(?:const|let|var)\s+({_JS_NAME})\s*=\s*require\(\s*{_CP_MODULE}\s*\)"
+)
+_CP_NAMED = re.compile(
+ rf"import\s*(?:{_JS_NAME}\s*,\s*)?\{{([^}}]*)\}}\s*from\s*{_CP_MODULE}"
+ rf"|(?:const|let|var)\s*\{{([^}}]*)\}}\s*=\s*require\(\s*{_CP_MODULE}\s*\)"
+)
+_CP_REQUIRE_CALL = re.compile(
+ rf"require\(\s*{_CP_MODULE}\s*\)\s*\.\s*exec(?:File)?(?:Sync)?\s*\("
+)
+_EXEC_EXPORT = re.compile(r"exec(?:File)?(?:Sync)?")
+
+
+def _child_process_exec_calls(source: str, masked: str) -> list[int]:
+ """Offsets of ``child_process`` exec-family calls, found through the file's own bindings.
+
+ Imports are read from raw source because the module name is a string
+ literal, which masking blanks; calls are read from masked source, so a
+ comment or string naming one does not count.
+ """
+ namespaces = {n for m in _CP_NAMESPACE.finditer(source) for n in m.groups() if n}
+ functions: set[str] = set()
+ for m in _CP_NAMED.finditer(source):
+ for item in (m.group(1) or m.group(2)).split(","):
+ # ``exec as run`` (import) and ``exec: run`` (destructuring) rename.
+ parts = re.split(r"\s+as\s+|\s*:\s*", item.strip().removeprefix("type "))
+ if parts[0] and _EXEC_EXPORT.fullmatch(parts[0]):
+ functions.add(parts[-1].strip())
+ offsets = [m.start() for m in _CP_REQUIRE_CALL.finditer(source) if not masked[m.start()].isspace()]
+ names = [re.escape(n) for n in namespaces]
+ if names:
+ receiver = rf"(?<![\w$.])(?:{'|'.join(names)})\s*\.\s*exec(?:File)?(?:Sync)?\s*\("
+ offsets += [m.start() for m in re.finditer(receiver, masked)]
+ if functions:
+ bare = rf"(?<![\w$.])(?:{'|'.join(map(re.escape, functions))})\s*\("
+ offsets += [m.start() for m in re.finditer(bare, masked)]
+ return sorted(offsets)
_PATTERNS: list[tuple[re.Pattern, str, str]] = [
*_CALL_PATTERNS,
@@ -126,10 +175,6 @@ _PATTERNS: list[tuple[re.Pattern, str, str]] = [
# patterns walked straight past that form. Found by scanning a corpus in
# which a live n8n key sat unreported under exactly that spelling.
#
- # The wording above avoids spelling the matched form out literally: this
- # loop runs on raw source, comments included, so an example written out here
- # would make the file report itself.
- #
# Case-insensitivity is written as a scoped inline group rather than the
# ``re.IGNORECASE`` flag on purpose: ``_ANY_PATTERN`` below is built by
# concatenating these patterns' *source text*, which drops per-pattern
@@ -262,7 +307,9 @@ _SYMBOL_KEYWORDS = re.compile(r"\b(auth|token|password|jwt|session|crypto)\b", r
# Kinds that name a dangerous call. They are matched against source with
# comments and string literals blanked, so a docstring, a comment or a regex
# literal that merely mentions the call does not fire.
-_MASKED_KINDS = frozenset({"pickle_loads", "subprocess_shell_true", "os_system"})
+_MASKED_KINDS = frozenset(
+ {"pickle_loads", "subprocess_shell_true", "os_system", "new_function_call"}
+)
# Prose is documentation, not executable code. Only secret kinds scan it,
# because a key pasted into a README is still a leak.
@@ -298,18 +345,33 @@ SYMBOL_NAME_KINDS: frozenset[str] = frozenset({"security_sensitive_symbol"})
_KEYWORD_KINDS: frozenset[str] = frozenset({"hardcoded_password", "hardcoded_secret"})
# A snake_case name is a key's name (a constant holding its own name) and a
-# template placeholder is filled at render time; neither is a credential.
+# template placeholder or shell substitution is filled in when it runs; none of
+# them is a credential.
_KEY_NAME_VALUE = re.compile(r"[a-z_]*_[a-z_]*")
-_TEMPLATE_VALUE = re.compile(r"\{\{.*\}\}|\$\{[^}]*\}")
+_TEMPLATE_VALUE = re.compile(r"\{\{.*\}\}|\$\{[^}]*\}|\$\(.*\)")
def _is_secret_value(kind: str, val: str) -> bool:
"""True when *val*, captured by a *kind* pattern, looks like a real credential."""
if not _is_valid_credential_value(val):
return False
+ if kind not in _KEYWORD_KINDS:
+ return True
if kind == "hardcoded_secret" and _KEY_NAME_VALUE.fullmatch(val):
return False
- return not (kind in _KEYWORD_KINDS and _TEMPLATE_VALUE.fullmatch(val.strip()))
+ value = val.strip()
+ # A leading ``--`` is a CSS custom property or a CLI flag, not a key.
+ return not (_TEMPLATE_VALUE.fullmatch(value) or _is_plain_word(value) or value.startswith("--"))
+
+
+def _is_plain_word(value: str) -> bool:
+ """A dictionary-shaped word: the dummy a client insists on (``api_key="lmstudio"``).
+
+ Bounded, because a long run of letters in mixed or single case is as random
+ as any key.
+ """
+ single_case = value.islower() or value.isupper() or value.istitle()
+ return value.isalpha() and single_case and len(value) <= 20
def _redaction(val: str) -> str:
@@ -440,9 +502,17 @@ def _snippet(line: str) -> str:
return text[:cut]
-def _mask_comments_and_strings(source: str) -> str:
- """Blank common comments/strings while preserving offsets and newlines."""
+def _mask_comments_and_strings(source: str, *, strings: bool = True) -> str:
+ """Blank common comments (and strings, unless *strings* is false), keeping offsets.
+
+ Strings are still tracked when they are kept, so a ``#`` or ``//`` inside
+ one does not open a comment.
+ """
chars = list(source)
+
+ def blank(at: int, width: int = 1) -> None:
+ chars[at : at + width] = [" "] * width
+
i = 0
state = "code"
quote = ""
@@ -453,59 +523,64 @@ def _mask_comments_and_strings(source: str) -> str:
if source[i] == "\n":
state = "code"
else:
- chars[i] = " "
+ blank(i)
i += 1
continue
if state == "block_comment":
if source.startswith("*/", i):
- chars[i : i + 2] = [" ", " "]
+ blank(i, 2)
i += 2
state = "code"
else:
if source[i] != "\n":
- chars[i] = " "
+ blank(i)
i += 1
continue
if state == "string":
marker = quote * (3 if triple else 1)
if source.startswith(marker, i):
- chars[i : i + len(marker)] = [" "] * len(marker)
+ if strings:
+ blank(i, len(marker))
i += len(marker)
state = "code"
elif source[i] == "\\":
- chars[i] = " "
+ if strings:
+ blank(i)
if i + 1 < len(source):
- if source[i + 1] != "\n":
- chars[i + 1] = " "
+ if strings and source[i + 1] != "\n":
+ blank(i + 1)
i += 2
else:
i += 1
else:
- if source[i] != "\n":
- chars[i] = " "
+ if strings and source[i] != "\n":
+ blank(i)
i += 1
continue
if state == "template":
if source.startswith("${", i):
- chars[i : i + 2] = [" ", " "]
+ if strings:
+ blank(i, 2)
i += 2
template_depth = 1
state = "code"
elif source[i] == "`":
- chars[i] = " "
+ if strings:
+ blank(i)
i += 1
state = "code"
elif source[i] == "\\":
- chars[i] = " "
+ if strings:
+ blank(i)
if i + 1 < len(source):
- if source[i + 1] != "\n":
- chars[i + 1] = " "
+ if strings and source[i + 1] != "\n":
+ blank(i + 1)
i += 2
else:
i += 1
else:
- if source[i] != "\n":
- chars[i] = " "
+ if strings and source[i] != "\n":
+ blank(i)
i += 1
continue
@@ -513,29 +588,32 @@ def _mask_comments_and_strings(source: str) -> str:
template_depth += 1
i += 1
elif template_depth and source[i] == "}":
- chars[i] = " "
+ if strings:
+ blank(i)
template_depth -= 1
i += 1
if template_depth == 0:
state = "template"
elif source.startswith("//", i) or source[i] == "#":
width = 2 if source.startswith("//", i) else 1
- chars[i : i + width] = [" "] * width
+ blank(i, width)
i += width
state = "line_comment"
elif source.startswith("/*", i):
- chars[i : i + 2] = [" ", " "]
+ blank(i, 2)
i += 2
state = "block_comment"
elif source[i] == "`":
- chars[i] = " "
+ if strings:
+ blank(i)
i += 1
state = "template"
elif source[i] in {"'", '"'}:
quote = source[i]
triple = source.startswith(quote * 3, i)
width = 3 if triple else 1
- chars[i : i + width] = [" "] * width
+ if strings:
+ blank(i, width)
i += width
state = "string"
else:
@@ -603,11 +681,9 @@ def _call_findings(file_path: str, source: str) -> list[dict]:
for match in pattern.finditer(masked):
add(kind, severity, match.start())
- # The module name is searched in raw source on purpose: it arrives as a
- # string literal (``require("child_process")``), which masking blanks.
- if not is_python and _CHILD_PROCESS_IMPORT.search(source):
- for match in _JS_EXEC_CALL.finditer(masked):
- add("exec_call", "high", match.start())
+ if not is_python:
+ for offset in _child_process_exec_calls(source, masked):
+ add("exec_call", "high", offset)
return findings
@@ -623,6 +699,15 @@ def _is_missing_table_error(exc: Exception) -> bool:
return "no such table" in message or "does not exist" in message
+def _match_starting_in(pattern: re.Pattern, line: str, kept: str) -> re.Match | None:
+ """First match of *pattern* on *line* whose first character survived masking in *kept*."""
+ for match in pattern.finditer(line):
+ start = match.start()
+ if start < len(kept) and not kept[start].isspace():
+ return match
+ return None
+
+
def scan_source(file_path: str, source: str, symbols: Iterable[Any] = ()) -> list[dict]:
"""Scan *source* text and symbol names; return finding dicts. No I/O."""
findings: list[dict] = []
@@ -632,8 +717,13 @@ def scan_source(file_path: str, source: str, symbols: Iterable[Any] = ()) -> lis
if not is_prose:
findings.extend(_call_findings(file_path, source))
- masked = "" if is_prose else _mask_comments_and_strings(source)
+ # Prose has no comments or strings to set apart: its text is read as written.
+ masked = source if is_prose else _mask_comments_and_strings(source)
masked_lines = source_lines(masked)
+ # Comments alone: a public env name is often quoted (``ENV["NEXT_PUBLIC_KEY"]``).
+ comment_lines = (
+ lines if is_prose else source_lines(_mask_comments_and_strings(source, strings=False))
+ )
# Line-by-line pattern scan
is_low_sev_file = _is_low_severity_path(file_path)
@@ -641,6 +731,7 @@ def scan_source(file_path: str, source: str, symbols: Iterable[Any] = ()) -> lis
if not _ANY_PATTERN.search(line):
continue
code_line = masked_lines[lineno - 1] if lineno <= len(masked_lines) else line
+ uncommented = comment_lines[lineno - 1] if lineno <= len(comment_lines) else line
snippet: str | None = None
keyword_hits: list[tuple[dict, str]] = []
vendor_values: list[str] = []
@@ -649,7 +740,17 @@ def scan_source(file_path: str, source: str, symbols: Iterable[Any] = ()) -> lis
continue
if is_prose and kind not in SECRET_KINDS:
continue
- match = pattern.search(code_line if kind in _MASKED_KINDS else line)
+ if kind in _MASKED_KINDS:
+ match = pattern.search(code_line)
+ elif kind in _KEYWORD_KINDS:
+ # ``password = "..."`` in a comment or docstring is an example.
+ match = _match_starting_in(pattern, line, code_line)
+ elif kind == "public_env_secret":
+ # A comment naming the variable is not code reading it.
+ match = _match_starting_in(pattern, line, uncommented)
+ else:
+ # Vendor key shapes are real wherever they sit, comments included.
+ match = pattern.search(line)
if match:
value = line[slice(*_value_span(kind, match, line))] if match.groups() else ""
if kind in SECRET_KINDS:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
index 9d6b3af12..cba26e87b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
@@ -339,7 +339,8 @@ async def _get_security_signals(session: AsyncSession, repo_id: str, target: str
text(
"SELECT kind, severity, snippet FROM security_findings "
"WHERE repository_id = :repo_id AND file_path = :fp "
- "ORDER BY severity DESC, kind"
+ # Ranked, not alphabetical: text order puts ``high`` last.
+ "ORDER BY CASE severity WHEN 'high' THEN 0 WHEN 'med' THEN 1 ELSE 2 END, kind"
),
{"repo_id": repo_id, "fp": target},
)
diff --git a/packages/server/src/repowise/server/services/attention.py b/packages/server/src/repowise/server/services/attention.py
index cce0e7eb1..ae3788b59 100644
--- a/packages/server/src/repowise/server/services/attention.py
+++ b/packages/server/src/repowise/server/services/attention.py
@@ -8,12 +8,11 @@ from __future__ import annotations
from collections.abc import Awaitable, Callable
-from sqlalchemy import func, select
+from sqlalchemy import case, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.attention import (
PER_SOURCE_CAP,
- SEVERITY_RANK,
AttentionSource,
AttentionView,
DecisionAttentionInput,
@@ -142,14 +141,17 @@ async def _health_items(session: AsyncSession, repo_id: str) -> tuple[list[dict]
return items, int(total), ""
+#: The scanner's severity words on the attention ladder.
+_SECURITY_SEVERITY = {"high": "high", "med": "medium", "low": "low"}
+
+
async def _security_items(session: AsyncSession, repo_id: str) -> tuple[list[dict], int, str]:
"""Security findings, high severity first.
``SecurityFinding`` has no status column: rows are replaced wholesale by
each scan, so every stored row is open by construction and there is nothing
- to filter on. It also only ever writes ``high`` or ``low`` — the router's
- docstring mentions a ``med`` that the scanner never emits — so the two
- middle bands of the ladder are simply unused here.
+ to filter on. The scanner writes ``high``, ``med`` and ``low``; ``med`` is
+ the security layer's spelling of the ladder's ``medium``.
"""
rows = (
(
@@ -157,9 +159,13 @@ async def _security_items(session: AsyncSession, repo_id: str) -> tuple[list[dic
select(SecurityFinding)
.where(SecurityFinding.repository_id == repo_id)
.order_by(
- # `high` before anything else, then newest. Expressed as a
- # sort key rather than two queries.
- (SecurityFinding.severity != "high"),
+ # Most severe first, then newest. Expressed as a sort key
+ # rather than a query per band.
+ case(
+ (SecurityFinding.severity == "high", 0),
+ (SecurityFinding.severity == "med", 1),
+ else_=2,
+ ),
SecurityFinding.detected_at.desc(),
)
.limit(PER_SOURCE_CAP)
@@ -197,7 +203,7 @@ async def _security_items(session: AsyncSession, repo_id: str) -> tuple[list[dic
"description": (
f"{row.kind}{f' in commit {row.commit_sha[:7]}' if row.commit_sha else ''}"
),
- "severity": row.severity if row.severity in SEVERITY_RANK else "medium",
+ "severity": _SECURITY_SEVERITY.get(row.severity, "medium"),
"target_id": row.file_path,
"subtype": row.kind,
# Nothing separates two `high` secrets but recency, and a secret
diff --git a/tests/unit/analysis/test_security_scan.py b/tests/unit/analysis/test_security_scan.py
index 590ca4dbb..5c2dc1a59 100644
--- a/tests/unit/analysis/test_security_scan.py
+++ b/tests/unit/analysis/test_security_scan.py
@@ -151,9 +151,20 @@ class TestScanFile:
'import { execFile } from "node:child_process";\nexecFile(bin, args);\n',
{"exec_call"},
),
- # Regex parsing in a file that also spawns: the gate is per file, so
- # this is the residual false positive the gate cannot remove.
- ('require("child_process");\nconst m = /a/.exec(s);\n', {"exec_call"}),
+ ('import { exec as run } from "child_process";\nrun(cmd);\n', {"exec_call"}),
+ ('const { execSync: sh } = require("child_process");\nsh(cmd);\n', {"exec_call"}),
+ ('import * as cp from "node:child_process";\ncp.execFile(bin);\n', {"exec_call"}),
+ ('require("child_process").exec(cmd);\n', {"exec_call"}),
+ # A regex's ``.exec`` in a file that also spawns is not bound to the module.
+ ('require("child_process");\nconst m = /a/.exec(s);\n', set()),
+ # The file's own function named exec, beside an unrelated spawn import.
+ (
+ 'import { spawn } from "node:child_process";\n'
+ "function exec(args) { return spawn(bin, args); }\n"
+ "exec(args);\n",
+ set(),
+ ),
+ ('import * as cp from "child_process";\n// cp.exec(cmd)\n', set()),
],
)
def test_js_exec_is_reported_only_when_child_process_is_present(
@@ -459,6 +470,8 @@ class TestScanFile:
("const f = new Function(body);\n", True),
("const f = someFunction(a, b);\n", False),
("class Function extends Base {}\n", False),
+ ("// never use new Function(body) here\n", False),
+ ('const doc = "new Function(body)";\n', False),
],
)
def test_new_function_call(self, source: str, expected: bool) -> None:
@@ -982,3 +995,73 @@ class TestCallKindsIgnoreProseAndText:
def test_multiline_shell_true_in_a_string_does_not_fire(self) -> None:
source = 'TEMPLATE = """\nsubprocess.run(\n x,\n shell=True,\n)\n"""\n'
assert self._hits(source) == []
+
+
+class TestSecretPrecision:
+ """A secret kind fires on a credential, never on an example of one."""
+
+ _SECRET: ClassVar[set[str]] = {"hardcoded_secret", "hardcoded_password", "public_env_secret"}
+
+ def _kinds(self, source: str, path: str = "src/app.py") -> set[str]:
+ return {f["kind"] for f in scan_source(path, source) if f["kind"] in self._SECRET}
+
+ @pytest.mark.parametrize(
+ ("path", "source"),
+ [
+ ("src/app.py", 'emb = get_embedder("openai", api_key="sk-...")\n'),
+ ("README.md", 'export ANTHROPIC_API_KEY="sk-ant-…"\n'),
+ ("README.md", 'export OPENAI_API_KEY="your-key-here"\n'),
+ ("README.md", 'API_KEY="sk-<your key>"\n'),
+ ("README.md", 'SECRET="$(op read op://vault/app/secret)"\n'),
+ ("src/app.py", 'TOKEN = "xxxxxxxxxxxx"\n'),
+ ],
+ )
+ def test_elided_or_templated_values_are_not_secrets(self, path: str, source: str) -> None:
+ assert self._kinds(source, path) == set()
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ 'client = OpenAI(api_key="ollama")\n',
+ 'client = OpenAI(api_key="lmstudio")\n',
+ '<Bar token="--chart-1" />\n',
+ ],
+ )
+ def test_dummy_values_are_not_secrets(self, source: str) -> None:
+ assert self._kinds(source, "src/client.tsx") == set()
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ 'TOKEN = "sk-live-9f8a7b6c5d4e"\n',
+ 'API_KEY = "sk-a****"\n',
+ f'API_KEY = "{"q" * 40}"\n',
+ ],
+ )
+ def test_credential_shaped_values_still_fire(self, source: str) -> None:
+ assert self._kinds(source) == {"hardcoded_secret"}
+
+ def test_doctest_example_is_not_a_password(self) -> None:
+ source = (
+ "def mask(line):\n"
+ ' """\n'
+ " >>> mask(\"password = 'supersecret99'\")\n"
+ ' """\n'
+ )
+ assert self._kinds(source) == set()
+
+ def test_comment_naming_a_public_env_variable_is_not_a_leak(self) -> None:
+ source = "/**\n * Read from NEXT_PUBLIC_REPOWISE_API_KEY on the server.\n */\n"
+ assert self._kinds(source, "web/client.ts") == set()
+
+ def test_code_reading_a_public_env_secret_still_fires(self) -> None:
+ source = 'const k = process.env.NEXT_PUBLIC_API_KEY; // "NEXT_PUBLIC" is public\n'
+ assert self._kinds(source, "web/client.ts") == {"public_env_secret"}
+
+ def test_keyword_secret_after_a_comment_on_the_same_line_is_found_in_code(self) -> None:
+ source = 'password = "Tr0ub4dor&3x" # password = "example"\n'
+ assert self._kinds(source) == {"hardcoded_password"}
+
+ def test_vendor_key_in_a_comment_still_fires(self) -> None:
+ kinds = {f["kind"] for f in scan_source("src/app.py", "# AKIAQZXNRTVYWMPKLBHG\n")}
+ assert kinds == {"aws_access_key"}
diff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.py
index cf148ae5f..12da7c405 100644
--- a/tests/unit/server/mcp/test_risk.py
+++ b/tests/unit/server/mcp/test_risk.py
@@ -727,3 +727,32 @@ async def test_get_risk_card_reads_line_coverage_from_the_stored_report(setup_mc
assert card["line_coverage_pct"] == 61.5
assert card["branch_coverage_pct"] == 40.0
assert "coverage_pct" not in card
+
+
+async def test_security_signals_are_ranked_high_first(setup_mcp, session):
+ """Severity is ranked, not sorted as text (which would put `high` last)."""
+ from datetime import UTC, datetime
+
+ from repowise.core.persistence.models import SecurityFinding
+ from repowise.server.mcp_server.tool_risk.assessment import _get_security_signals
+
+ for line, (kind, severity) in enumerate(
+ [("weak_hash", "low"), ("tls_verify_false", "med"), ("pickle_loads", "high")], start=1
+ ):
+ session.add(
+ SecurityFinding(
+ repository_id="repo1",
+ file_path="src/auth/service.py",
+ kind=kind,
+ severity=severity,
+ snippet="",
+ line_number=line,
+ commit_sha="",
+ detected_at=datetime(2026, 9, 1, tzinfo=UTC),
+ )
+ )
+ await session.flush()
+
+ signals = await _get_security_signals(session, "repo1", "src/auth/service.py")
+ assert [s["severity"] for s in signals] == ["high", "med", "low"]
diff --git a/tests/unit/server/test_overview_attention.py b/tests/unit/server/test_overview_attention.py
index 63b594587..99e5b4bd0 100644
--- a/tests/unit/server/test_overview_attention.py
+++ b/tests/unit/server/test_overview_attention.py
@@ -507,3 +507,45 @@ async def test_health_leads_with_the_worst_file_not_the_worst_finding(
assert health[1]["severity"] == "low"
# The count is still findings, so the row can say how much the area holds.
assert result["by_source"]["health_finding"] == 7
+
+
+async def test_a_med_security_finding_is_medium_and_ranks_above_low(
+ client: AsyncClient, session_factory
+) -> None:
+ """The scanner writes `med`; the ladder reads `medium`, above a newer `low`."""
+ repo = await create_test_repo(client)
+ repo_id = repo["id"]
+ async with get_session(session_factory) as session:
+ for kind, severity, day in (("tls_verify_false", "med", 1), ("weak_hash", "low", 2)):
+ session.add(
+ SecurityFinding(
+ repository_id=repo_id,
+ file_path="src/net.py",
+ kind=kind,
+ severity=severity,
+ snippet="",
+ line_number=day,
+ commit_sha="",
+ detected_at=datetime(2026, 9, day, tzinfo=UTC),
+ )
+ )
+ await session.commit()
+
+ async with get_session(session_factory) as session:
+ result = await build_attention(
+ session,
+ repo_id,
+ decision_health={
+ "stale_decisions": [],
+ "proposed_awaiting_review": [],
+ "ungoverned_hotspots": [],
+ },
+ knowledge_silos=[],
+ )
+
+ security = [i for i in result["items"] if i["type"] == "security_finding"]
+ assert [(i["subtype"], i["severity"]) for i in security] == [
+ ("tls_verify_false", "medium"),
+ ("weak_hash", "low"),
+ ]