Files
Claude-BugHunter/scripts/test_scan_identifiers.py
6a530fb314 fix: five tooling/engine correctness bugs — classify, extract_json, secret_scan, osint roots, leak-guard (#221)
* fix(cbh): classify_url matches path/query, not hostname (#219)

Pattern triggers ran against the full URL, so a keyword in the hostname
(verify.example.com, cart.shop.example) matched a leading-slash path
pattern via the //. Match against parsed.path+query instead; the
previously-unused parsed is now the source of truth.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(engine): extract_json keeps the last top-level JSON value (#217)

The unfenced fallback used one greedy {.*} DOTALL span (first brace to
last), so any earlier brace in the reply — a curl payload in the prose —
made the whole span unparseable and the verdict was lost, re-running the
item as no-verdict. Scan top-level values with raw_decode and keep the
last. Fenced replies are unaffected.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(osint): secret_scan prunes skip dirs by name, always scans the root (#216)

The skip check tested each noisy-dir word as a substring of the whole
walked path, root included. So scanning ./dist, .github/ (contains .git),
or nightly-builds/ matched and skipped everything, printing nothing and
exiting 0 — a false clean in a leak guard. Prune os.walk's dirs by exact
name below the root instead; the requested root is always scanned.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(osint): derive enumeration roots from authorized scope (#213)

osint() and _expand_scope() took the enumeration apex by keeping a seed
host's last two labels. Under a multi-label public suffix that apex is
the suffix itself (example.co.uk -> co.uk), so subfinder/assetfinder/crt.sh
queried the whole suffix and the in-scope filter discarded the results;
--expand never enumerated the target at all. IP seeds became '3.4'. New
shared osint.enumeration_roots() takes roots from in-scope domain rules and
maps each seed to its shortest covering root (full hostname if uncovered),
with no public-suffix list.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(leak-guard): reject malformed denylist hashes (#212)

A committed .sha256 line that is not a 64-hex digest was loaded verbatim
as a 'hash' that no real sha256 can match — a silent false-negative in
the leak guard. load_denylist now validates each entry and fails closed
(exit 2) on a malformed one, naming the line to fix without printing its
content.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* docs(changelog): credit five tooling/engine bugfix reporters (#219,#217,#216,#213,#212)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(review): harden extract_json, classify_url, and the skill-linter denylist

Adversarial review of the five bugfixes surfaced four to fold:
- extract_json: a truncated top-level array let an inner element be
  returned as the verdict; stop at the first unparseable bracket instead
  of descending. Also widen the except to (ValueError, RecursionError) so
  deep nesting in the C scanner can't escape into the verdict path.
- classify_url: schemeless input (api.php.net/x) put the host in
  parsed.path, so .php still fired. Prefix // when there's no scheme.
- lint_skills.load_denylist: same malformed-hash fail-open as #212 in the
  skill linter — validate and fail closed there too.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-23 15:46:42 +05:30

113 lines
4.7 KiB
Python
Executable File

#!/usr/bin/env python3
"""Self-check for scan_identifiers.py. Stdlib and local Git only. No network.
Run: python3 scripts/test_scan_identifiers.py (exit 0 = pass)
Loads the scanner as a module, points its denylist path at a temp dir, and
asserts the three behaviors that matter:
1. a planted identifier is caught -> main() returns 1
2. a clean file is not caught -> main() returns 0
3. an empty/missing denylist fails CLOSED -> main() returns 2
"""
import hashlib
import importlib.util
import os
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
def load_module():
spec = importlib.util.spec_from_file_location(
"scan_identifiers", os.path.join(HERE, "scan_identifiers.py"))
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def main():
mod = load_module()
with tempfile.TemporaryDirectory() as tmp:
scripts = os.path.join(tmp, "scripts")
os.makedirs(scripts)
mod.SCRIPTS_DIR = scripts # redirect denylist lookup
mod.REPO = tmp
deny = os.path.join(scripts, ".identifier-denylist.sha256")
# Denylist with the hash of a fake identifier "acmecorp".
banned = hashlib.sha256("acmecorp".encode()).hexdigest()
with open(deny, "w") as fh:
fh.write("# test denylist\n" + banned + "\n")
leak = os.path.join(tmp, "leak.md")
with open(leak, "w") as fh:
fh.write("The target was AcmeCorp Ltd, an internal engagement.\n")
clean = os.path.join(tmp, "clean.md")
with open(clean, "w") as fh:
fh.write("Generic methodology, no client names here.\n")
# 1. planted identifier caught
assert mod.main([leak]) == 1, "expected hit (exit 1) on planted identifier"
# 2. clean file passes
assert mod.main([clean]) == 0, "expected clean (exit 0) on benign file"
# The staged snapshot can differ from the current working tree.
subprocess.run(["git", "init", "-q", tmp], check=True)
subprocess.run(["git", "-C", tmp, "add", "--", leak], check=True)
with open(leak, "w", encoding="utf-8") as fh:
fh.write("Working copy is clean.\n")
assert mod.main([]) == 0, "working-tree scan should see the clean file"
assert mod.main(["--staged"]) == 1, "staged scan must detect the staged identifier"
subprocess.run(["git", "-C", tmp, "add", "--", leak], check=True)
with open(leak, "w", encoding="utf-8") as fh:
fh.write("AcmeCorp only in the working copy.\n")
assert mod.main(["--staged"]) == 0, "unstaged identifiers must not block a clean commit"
# 3. case-insensitive: "ACMECORP" also caught
loud = os.path.join(tmp, "loud.md")
with open(loud, "w") as fh:
fh.write("ACMECORP everywhere\n")
assert mod.main([loud]) == 1, "expected case-insensitive hit"
# Test default tracked-path discovery; Git quotes non-ASCII by default.
unicode_leak = os.path.join(tmp, "notes-café.md")
with open(unicode_leak, "w", encoding="utf-8") as fh:
fh.write("An AcmeCorp synthetic fixture.\n")
subprocess.run(["git", "init", "-q", tmp], check=True)
subprocess.run(["git", "-C", tmp, "config", "core.quotePath", "true"], check=True)
subprocess.run(["git", "-C", tmp, "add", "--", unicode_leak], check=True)
assert mod.main([]) == 1, "expected tracked scan to inspect Unicode filename"
# 4. fail-closed on empty denylist
with open(deny, "w") as fh:
fh.write("# comments only, no hashes\n")
assert mod.main([clean]) == 2, "expected FAIL-CLOSED (exit 2) on empty denylist"
# 5. fail-closed on missing denylist
os.remove(deny)
assert mod.main([clean]) == 2, "expected FAIL-CLOSED (exit 2) on missing denylist"
# 6. a malformed denylist entry fails CLOSED (exit 2), names the line, not its content
import io
import contextlib
bad_token = "not-a-sha256-hash"
with open(deny, "w") as fh:
fh.write("# header\n" + banned + "\n" + bad_token + "\n")
err = io.StringIO()
try:
with contextlib.redirect_stderr(err):
rc = mod.main([clean])
except SystemExit as e:
rc = e.code
assert rc == 2, "expected FAIL-CLOSED (exit 2) on malformed denylist entry"
assert ":3" in err.getvalue(), "error must point to the offending line (3)"
assert bad_token not in err.getvalue(), "must not print the offending content"
print("PASS: scan_identifiers self-check (catch, clean, case-insensitive, fail-closed)")
return 0
if __name__ == "__main__":
sys.exit(main())