Scope Hardening Pass Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: Make engine/scope.py (and the recon fetches that trust it) fail closed — out-of-scope hosts in normal program-page syntax actually deny, recon can’t silently promote or escape scope — with softer defaults (warn, don’t hard-stop).
Architecture: Two independent commits. (1) scope.py: one normalization point for every rule source, IPv6-aware CIDR, soft-fail on a bad deny regex, start/end heading detection, all surfaced through a new Scope.warnings channel. (2) recon.py: a single-hop redirect follower gated by the scope predicate, plus a no-redirect auth sweep. The casual (non-engine) path is untouched.
Tech Stack: Python 3.9 stdlib (ipaddress, re, urllib.parse), unittest. requests optional (CI has none).
Spec: docs/superpowers/specs/2026-11-22-scope-hardening-design.md
Global Constraints
- Python 3.9-compatible (CI runs 3.9 + 3.12). No walrus-in-comprehension or 3.10+ syntax.
- Every file open is UTF-8 (
scope.jsonincluded). scripts/hunt.ps1stays ASCII-only (no non-ASCII bytes).- No client identifiers; examples use
example.com/2001:db8::/32(RFC 3849) only. scripts/scan_identifiers.py,scripts/check_doc_counts.py,scripts/lint_skills.py,engine/scope.py --selftest, the fullengine/+tests/suites, and everyruntime-tests.ymlstep stay green.- Deny wins, default deny — unchanged. No change to verdict thresholds, exit codes, or the
_selftestcontract (extend it, don’t weaken it). Scope.in_scope_host/reject_reasonkeep their current signatures and return types.
Review Focus
- A valid out-of-scope
re:rule still matches after the soft-fail path is added (softening bad regexes must not break good ones). → Task 3. - An in-scope rule with a port/path is widened to host and still matches its host (normalization applies to in-scope, not only deny). → Task 1.
- An IPv4 CIDR rule vs an IPv6 host, and an IPv6 CIDR rule vs an IPv4 host → no match, no exception. → Task 2.
- A same-host redirect is still followed (coverage) while an off-host redirect is not (safety). → Task 6.
- A
scope.mdwhose only scope-ish heading is the recon one →in_scopeempty, default-deny holds, hint warning present. → Task 4.
Task 1: Scope.warnings + one normalization point for every rule source
Files:
- Modify:
engine/scope.py(Scope.__init__,_scope_from_md; remove_rule_from_token) - Test:
engine/test_scope_rule_normalization.py(create)
Interfaces:
- Produces:
Scope.warnings: list[str](populated during construction);_normalize_rule(rule: str) -> strmodule function. -
Consumes: nothing from other tasks.
-
Step 1: Write failing tests in
engine/test_scope_rule_normalization.py. AScopewhose out-of-scope rules are written asadmin.example.com:8443,https://admin.example.com,admin.example.com/panel,admin.example.com.,admin.example.com,, andhttps://*.corp.example.com, within_scope=["example.com"], denieshttps://admin.example.com/for the first four and deniesx.corp.example.comfor the wildcard. Asserts.in_scope_host("https://admin.example.com/") is False. Assert an in-scope rulehttps://app.example.com/loginstill matchesapp.example.com(in_scope_host("http://app.example.com/x") is True). Assert a port/path rule records a “widened to host” string ins.warnings. -
Step 2: Run, verify fail. Run:
python3 -m unittest engine.test_scope_rule_normalization -vExpected: FAIL (hosts come back in scope;warningsattribute missing). -
Step 3: Implement. Add
self.warnings = []toScope.__init__. Add module fn_normalize_rule(rule): keepre:prefix rules,*.wildcards, and CIDR (contains/andipaddress.ip_network(rule, strict=False)parses) unchanged; otherwise reduce to host — strip wrapping backticks/quotes, strip a trailing./,/;,urlparseout scheme/userinfo/port/path, lowercase. If the raw rule carried a port or path, append a warningf"scope rule {raw!r} widened to host {host!r} (scope is per-host)". Run bothin_scopeandout_of_scopethrough_normalize_rulein__init__(after the existing empty-strip filter). In_scope_from_md, replace the_rule_from_token(pat)call withpat(normalization now happens in__init__) and delete_rule_from_token. -
Step 4: Run, verify pass. Run:
python3 -m unittest engine.test_scope_rule_normalization -vExpected: PASS. -
Step 5: Run the scope suite + selftest. Run:
python3 -m unittest discover -s engine -p 'test_scope*' -v && python3 engine/scope.py --selftestExpected: all PASS (existing scope.md/malformed/regex tests unaffected). - Step 6: Commit
fix(scope): normalize every rule source to host; add Scope.warnings.
Task 2: IPv6-aware CIDR matching in _match
Files:
- Modify:
engine/scope.py(_match) - Test:
engine/test_scope_rule_normalization.py(extend)
Interfaces:
-
Consumes:
_normalize_rule(Task 1) keeps CIDR rules intact. -
Step 1: Write failing tests.
Scope(in_scope=["2001:db8::/32"])→in_scope_host("https://[2001:db8::1]/") is True.Scope(in_scope=["10.0.0.0/8"])→in_scope_host("https://[2001:db8::1]/") is False(IPv4 rule, IPv6 host, no exception).Scope(in_scope=["2001:db8::/32"])→in_scope_host("https://10.1.2.3/") is False(IPv6 rule, IPv4 host). -
Step 2: Run, verify fail. Run:
python3 -m unittest engine.test_scope_rule_normalization -vExpected: FAIL (IPv6 CIDR not recognized — currentisdigit()check excludes colons). -
Step 3: Implement. In
_match, replace the"/" in p and p.replace(".","").replace("/","").isdigit()CIDR branch with: attemptnet = ipaddress.ip_network(p, strict=False)insidetry/except ValueError; on success returnipaddress.ip_address(host) in netinside a nestedtry/except ValueError(an IP-family mismatch or a non-IP host →False, never raises). Keep ordering so a bare domain that isn’t a network still falls through to the host-suffix match. -
Step 4: Run, verify pass. Run:
python3 -m unittest engine.test_scope_rule_normalization -vExpected: PASS. -
Step 5: Selftest + scope suite. Run:
python3 engine/scope.py --selftest && python3 -m unittest discover -s engine -p 'test_scope*'Expected: PASS (existing IPv4 CIDR cases unchanged). -
Step 6: Commit
fix(scope): recognize IPv6 CIDR rules via ipaddress.
Task 3: Soft-fail a bad out-of-scope regex
Files:
- Modify:
engine/scope.py(Scope.__init__) - Test:
engine/test_scope_rule_normalization.py(extend)
Interfaces:
-
Consumes:
Scope.warnings(Task 1),_normalize_rule(Task 1). -
Step 1: Write failing tests. (a)
Scope(in_scope=["example.com"], out_of_scope=["re:(unclosed"])constructs without raising, records a warning mentioninginvalidandre:(unclosed, and the run continues —in_scope_host("https://example.com/") is True. (b) A valid deny regex still works:Scope(in_scope=["example.com"], out_of_scope=["re:^admin\\.example\\.com$"])→in_scope_host("https://admin.example.com/") is False. (c) The bad rule’s literal remainder is treated as a host rule: assert there:rule was replaced (nore:-prefixed entry survives inout_of_scope). -
Step 2: Run, verify fail. Run:
python3 -m unittest engine.test_scope_rule_normalization -vExpected: FAIL (no warning recorded;re:rule kept verbatim and silently matches nothing). -
Step 3: Implement. In
__init__, after normalization, pre-compile eachout_of_scoperule that starts withre:. Onre.error, append a warningf"out-of-scope regex {rule!r} is invalid: {err} — treating as a literal host rule; fix it to restore regex matching", then replace that entry with_normalize_rule(rule[3:]). Leave in-scope bad-regex behavior as-is (it already fails closed inside_match; add a warning there too if cheap, but do not change its match result). -
Step 4: Run, verify pass. Run:
python3 -m unittest engine.test_scope_rule_normalization -vExpected: PASS. -
Step 5: Selftest. Run:
python3 engine/scope.py --selftestExpected: PASS. -
Step 6: Commit
fix(scope): soft-fail an invalid out-of-scope regex (warn, treat as host).
Task 4: Heading start/end detection + recon hint + scaffolder copy
Files:
- Modify:
engine/scope.py(_scope_from_md),scripts/hunt.sh,scripts/hunt.ps1 - Test:
engine/test_scope_md_rules.py(extend — file exists)
Interfaces:
- Consumes:
Scope.warnings(Task 1). -
Produces:
_section_of(label: str) -> "in" | "out" | Nonehelper inscope.py. -
Step 1: Write failing tests in
engine/test_scope_md_rules.py. Build ascope.mdwhose only scope-ish heading is## Recon-seeded live hosts (from cbh manifest — VERIFY in-scope before testing)with bullets- jira.example.comand- legacy.example.com, plus a real## In scopesection listing onlyapp.example.com. Assert_scope_from_md(path).in_scope_host("https://jira.example.com/") is Falseand... app.example.com ... is True, and that a warning names the recon heading + the count2. Add asserts that## In-Scope Assets,## **Out of scope:**,## Assets in scope,### In scope (web)still open their sections, and a heading mentioning scope only mid-sentence closes the current section. Add a test that reads the appended heading string out ofscripts/hunt.shand asserts it contains noin-scope/in scopesubstring. -
Step 2: Run, verify fail. Run:
python3 -m unittest engine.test_scope_md_rules -vExpected: FAIL (recon hosts come back in scope; scaffolder heading still contains “in-scope”). -
Step 3: Implement. Add
_section_of(label): strip leading#, surrounding bold**/backticks, a trailing:and a trailing ` (…)parenthetical, lowercase, trim. Return“in”if it starts or ends within scope/in-scope,“out”if it starts or ends without of scope/out-of-scope, elseNone. In_scope_from_md, on a heading line computesec = _section_of(…); setsection = secwhen non-None; whenNoneandhashes <= 2, close (section = None); deeper headings keep the section. When a heading mentions a scope phrase but_section_ofreturnsNone(mid-sentence), remember its label + count the bullets that follow it; after parsing, if any such bullets were seen, append a warningf”{n} recon-seeded host(s) found under {label!r} — add them to ‘## In scope’ to test them.”. Updatescripts/hunt.sh(line ~273) andscripts/hunt.ps1(line ~281) heading to## Recon-seeded live hosts (from cbh manifest — UNVERIFIED; add to ‘## In scope’ before testing); keephunt.ps1ASCII (use-not—`). -
Step 4: Run, verify pass. Run:
python3 -m unittest engine.test_scope_md_rules -vExpected: PASS. -
Step 5: ASCII + identifier guards. Run:
python3 -c "print(open('scripts/hunt.ps1','rb').read().isascii())" && python3 scripts/scan_identifiers.pyExpected:Truethen 0 matches. - Step 6: Commit
fix(scope): open a section only on a start/end scope heading; hint recon hosts.
Task 5: Surface Scope.warnings in the CLI and the engine
Files:
- Modify:
engine/scope.py(_main),engine/engine.py(afterScope.load) - Test:
engine/test_scope_rule_normalization.py(extend — CLI stderr)
Interfaces:
-
Consumes:
Scope.warnings(Task 1). -
Step 1: Write failing test. Invoke
scope.pyin a subprocess with--out-of-scope 're:(bad'--in-scope example.com example.comand assert the invalid-regex warning text appears on stderr (not stdout, so--json-style stdout consumers stay clean) and exit code is unchanged (0, host in scope). -
Step 2: Run, verify fail. Run:
python3 -m unittest engine.test_scope_rule_normalization -vExpected: FAIL (nothing printed to stderr). -
Step 3: Implement. In
_main, after ascopeis built from any source, print eachscope.warningsline tosys.stderrbefore the per-target verdicts. Inengine.py, right afterself.scope = Scope.load(scope_path)(line ~55), emitfor w in self.scope.warnings: self.eng.log(f"scope: ⚠ {w}")(guard withgetattr(self.scope, "warnings", [])for forward-compat). Keep stdout verdicts byte-for-byte unchanged. -
Step 4: Run, verify pass. Run:
python3 -m unittest engine.test_scope_rule_normalization -vExpected: PASS. -
Step 5: Engine mock run. Run:
python3 engine/engine.py --scope engine/engagement.example.json --mockExpected: exit 0, no traceback. -
Step 6: Commit
fix(scope): surface scope warnings on stderr and in the engine log.
Task 6: One-hop, scope-gated recon redirects
Files:
- Modify:
engine/recon.py(_getboth backends,_probe,spa_recon,platform_recon,openapi_recon,prune_inert_params) - Modify:
engine/test_openapi_readonly.py(repoint the redirect patch) - Test:
engine/test_recon_redirect_scope.py(create)
Interfaces:
- Consumes:
scope.in_scope_host(existing). -
Produces:
_follow(url, allow, timeout)helper;_get(url, timeout=20, allow=None)and_probe(url, timeout=12, allow=None)gain an optional predicate. -
Step 1: Write failing tests in
engine/test_recon_redirect_scope.py, using a fake transport (monkeypatch the module opener /_probe) that maps an in-scope seed to a302whoseLocationis an off-host URL. Assert: (a)spa_reconwith aScope(in_scope=["example.com"])never fetchesevil.com/robots.txt(off-host landing is not adopted asbase); (b) a same-host302(http://app.example.com/→https://app.example.com/home) is followed; (c)auth_enforcement_sweepis covered in Task 7, not here. Include one real-loopback test for the stdlib backend and one for thecurlbackend (unittest.skipUnless(shutil.which("curl"))). Tests must pass with and withoutrequests. -
Step 2: Run, verify fail. Run:
python3 -m unittest engine.test_recon_redirect_scope -vExpected: FAIL (off-host robots.txt fetched; redirects followed unconditionally). -
Step 3: Implement. Add
_follow(url, allow, timeout): issue one non-redirecting request at a time (requests:allow_redirects=False; stdlib: aurllib.request.OpenerDirectorwith noHTTPRedirectHandler, module-level_OPENER; curl: drop-L), walk at mostMAX_REDIRECTS = 5hops, following a3xxLocationonly whileallow is None or allow(next_url); return the last response reached in scope. Route both_getbackends and_probethrough it; add the optionalallow=param (defaultNone= follow nothing beyond the first hop’s own-host chain — safe default). Inspa_recon, after_get(seed, allow=scope.in_scope_host), re-checkscope.in_scope_host(final)before derivingbase/fetching robots+sitemap; passallow=scope.in_scope_hostto the JS and robots/sitemap_getcalls. Inplatform_recon/openapi_recon,continueon a seed that is notscope.in_scope_host, and passallow=scope.in_scope_hostinto their_probecalls;prune_inert_paramspasses the predicate through if it has one (keep its current signature; thread scope only if already available — otherwise leave prune following nothing). Inengine/test_openapi_readonly.py, repointpatch("urllib.request.urlopen", ...)to patch the newrecon._OPENER.open(assertions unchanged). -
Step 4: Run, verify pass. Run:
python3 -m unittest engine.test_recon_redirect_scope engine.test_openapi_readonly -vExpected: PASS. -
Step 5: Full engine suite. Run:
python3 -m unittest discover -s engineExpected: PASS (no redirect regression elsewhere). - Step 6: Commit
fix(engine): follow recon redirects one hop at a time, inside scope.
Task 7: Auth-enforcement sweep stops following redirects
Files:
- Modify:
engine/recon.py(auth_enforcement_sweep) - Test:
engine/test_recon_redirect_scope.py(extend)
Interfaces:
-
Consumes:
_OPENER/ no-redirect opener (Task 6). -
Step 1: Write failing test. A declared-secured GET op whose handler responds
302 → /login(login page returns200). Assert the sweep does not add anauth-bypassitem (a redirect to login is enforcement) and does not request theLocationtarget. -
Step 2: Run, verify fail. Run:
python3 -m unittest engine.test_recon_redirect_scope -vExpected: FAIL (currenturlopenfollows the 302, grades the login page’s 200 as “not enforced”). -
Step 3: Implement. Replace the
urllib.request.urlopen(req, ...)call inauth_enforcement_sweepwith the no-redirect opener from Task 6, so a3xxis graded as itself (codestays30x, which is not in the(200,201,202,204,422)“reached handler” set). No other logic change. -
Step 4: Run, verify pass. Run:
python3 -m unittest engine.test_recon_redirect_scope -vExpected: PASS. -
Step 5: Full engine + tests + runtime gates. Run:
python3 -m unittest discover -s engine && python3 -m unittest discover -s tests && python3 scripts/scan_identifiers.py && python3 scripts/check_doc_counts.pyExpected: all PASS / 0 matches / 0 errors. -
Step 6: Commit
fix(engine): auth sweep grades a 3xx as enforcement, never chases Location. Add aCHANGELOG.mdentry under Fixed covering both scope.py and recon.py fixes in the same commit.
Self-review notes
- Spec coverage: #182 → Tasks 1–3 + 5; #198 → Task 4; #181 → Tasks 6–7. All five design changes mapped.
- Type consistency:
_normalize_rule(T1) used by T2/T3;Scope.warnings(T1) consumed by T3/T4/T5;_OPENER/_follow(T6) consumed by T7. No name drift. - Review Focus: each of the five lines has an owning task’s test (T3, T1, T2, T6, T4).
- Proportion: plan carries signatures, test assertions, and exact file/line targets; no function bodies transcribed. Design doc holds the prose rationale.