Security review
Contract
| Field | Bound contract | |---|---| | Trigger | Changes touch auth, input parsing, dependencies, network I/O, or pre-release of a public-facing service; or a PR, commit, diff, or baseline is supplied for security regressions, blast radius, changed-code test gaps, or adversarial review of what changed; or the user asks for a security review, vulnerability audit, OWASP review, or review of injection, XSS, authentication, authorization, or cryptography of a supplied file, diff, or component (mode confirmed); or an API, configuration schema, cryptographic interface, authentication surface, or library design is questioned for misuse resistance, secure-by-default behavior, or footguns, inline or as a delegated specialist analysis (mode edges). | | Authority | Reversible local. Write set: one review report file. Rollback: delete the report file. No remote mutation. Modes confirmed and edges are read-only: no file, VCS, credential, paid, published, deployed, or remote mutation; findings are reported in chat or returned to the delegating caller. | | Side effect | A security-audit report; differential mode reads Git history for blame and regression checks and always writes the report file. No code edits; secret scanning reads and never mutates credentials. Modes confirmed and edges write nothing: the findings report is returned in the conversation or to the delegating caller. | | Done | Full mode: audit report with STRIDE findings, OWASP walkthrough, supply-chain results, and severity contract (critical and high block merge). Differential mode: every in-scope change risk-classified at the declared depth, with evidence-backed findings, test gaps, blast radius, historical context, exploit paths where warranted, limitations, and a recommendation. Confirmed mode: only HIGH-confidence findings reported, each with attacker-controlled input confirmed, or a cleared report stating no high-confidence vulnerabilities were identified. Edges mode: security-relevant choice points checked across the seven edge cases with each reported edge carrying category, severity, location, reproducible misuse, and a misuse-resistant recommendation; specialist mode completes the four analysis phases with an exploitability determination per finding. |
Not for
- Adding security controls during construction: use security-hardening.
- Verifying a named security allegation as true or false positive: use security-finding-verification.
- Running CodeQL analysis, building or reusing a CodeQL database, or modeling project-specific sources and sinks: use codeql-security-analysis.
Inputs
- Mode: full, differential, confirmed, or edges; default full. Differential applies when a PR, commit, diff, or baseline is supplied for regressions, blast radius, gaps, or adversarial review. Differential needs a baseline to compare; greenfield code with no baseline, documentation-only changes, and formatting-only changes use full mode. Confirmed applies when the user asks for a security review or vulnerability audit of a named target and expects only high-confidence, data-flow-confirmed findings reported in chat. Edges applies when a surface is audited for misuse resistance or footguns,
inlineby default;delegation: specialistselects the isolated delegated analysis when a caller explicitly assigns it. - Change set: diff, commit range, or file list under audit. Required for full mode.
- Baseline: differential comparison reference; defaults to the merge base or parent commit. Optional.
- Depth: full and differential modes only; full depth applies unless the user explicitly requests quick triage and accepts the residual risk. Optional. Confirmed and edges ignore it: confirmed mode never reduces its data-flow checks, and edges mode never reduces its seven-edge-case or specialist checks.
- Ecosystem context: language family, framework, dependency manager. Optional; inferred from repo if absent.
- Scope hint: specific concern (auth, crypto, injection, XSS, supply-chain). Optional; in full mode its absence selects the full STRIDE/OWASP walk; in confirmed mode it narrows the review focus to the named concern.
- Review target: mode confirmed; the file, diff, or code component to review. Required. Reporting scope is bounded to the supplied target; the entire reachable codebase is research scope.
- Code surface and target specification: mode edges; the API surface, configuration schema, cryptographic interface, authentication surface, or library design under audit, and the element within it to examine. Both required. Specialist delegation adds: caller-named scope (required; bounded by what the caller names — the skill refuses to expand it and does not discover additional files or symbols), language context (optional; inferred from file extensions), and severity floor (optional; defaults to all findings).
Procedure
Prioritize risk and use evidence. Focus on auth, crypto, external calls, value transfer, and validation removal. Back every finding with evidence, line numbers, and attack scenarios. Classify by risk, not size; a small diff can carry a critical regression. In full and differential review, familiarity is not coverage, explicit baseline context is built, Git history is never skipped, blast radius is calculated rather than guessed, missing tests elevate severity, and refactors are HIGH until proven LOW. In differential mode the report file is always written. Steps 1 through 8 apply to full and differential modes only; confirmed mode runs step 9 and edges mode runs step 10, then both continue at steps 11 and 12.
- Bound scope. Modes full and differential: identify every file in the change set and map each to a trust boundary (external input, internal service, data store, credential surface). Mode differential: extract the change set from the target (
git diff <base>..<head> --stat,git log <base>..<head> --oneline,git diff <base>..<head> --name-only, orgh pr view <number> --json files,additions,deletions) and risk-score each changed file: HIGH for auth, crypto, external calls, value transfer, validation removal; MEDIUM for business logic, state changes, new public APIs; LOW for comments, tests, UI, logging. Done when: every file is mapped to a trust boundary and, in differential mode, every changed file carries a risk score. - Baseline context. Mode differential: before mutation analysis, capture system-wide invariants, trust boundaries and privilege levels, validation patterns, call graphs for critical functions, state flows, and external trust assumptions; store the record for cross-reference, then return to the head commit. Read both versions of each changed file and record BEFORE, AFTER, behavioral CHANGE, and SECURITY implication per diff region. Git-blame removed code (
git log -S "removed_code" --all --oneline,git blame <baseline> -- file): removed code from "fix", "security", or "CVE" commits is CRITICAL; recently added then removed is HIGH; code added, removed for security, and re-added is a REGRESSION (git log -S "added_code" --all -p). Done when: baseline context is stored, removed code is blamed with red flags classified, regressions are checked, and every diff region has the four-field record. - STRIDE walk. Mode full: for each component touching a trust boundary, apply the six-question template:
- Spoofing: Who is the principal? How is identity proven? Can the credential be forged, replayed, or stolen? Is MFA/mutual-auth enforced?
- Tampering: What inputs cross the trust boundary? Are they validated against an explicit schema? Are messages integrity-protected?
- Repudiation: Are security-relevant actions logged with actor + timestamp + outcome? Are logs append-only/tamper-evident?
- Information Disclosure: What data is returned in error paths, logs, telemetry? Are PII/secrets ever serialized? Are timing side-channels addressed?
- Denial of Service: Are inputs bounded (size, count, depth)? Is parsing resource-limited? Are external calls rate-limited?
- Elevation of Privilege: What privilege does the new code execute under? Is least privilege honored? Can input alter privilege? Mode differential: the walk is skipped; trust-boundary coverage comes from the baseline context and risk scores. Done when: full mode answers all six STRIDE questions per trust-boundary component; differential mode records trust coverage from baseline context.
- OWASP Top 10 walkthrough. Mode full: trace authorization policy (Broken Access Control); grep for weak primitives MD5, SHA1, DES, Math.random (Cryptographic Failures); check unparameterized queries, shell concat, template eval (Injection); cross-check STRIDE findings (Insecure Design); check TLS, CORS, CSP, cookie flags, debug toggles (Security Misconfiguration); run ecosystem CVE scanner (Vulnerable Components); check token TTL, refresh, session fixation, MFA (Auth Failures); check lockfile pinned, signature-verified artifacts (Integrity Failures); check audit log coverage, alert on auth-fail (Logging Failures); check egress allowlist, SSRF guard on URL inputs (SSRF). Done when: every OWASP category has a pass/fail verdict.
- Supply-chain scan. Mode full: run the per-ecosystem CVE scanner and secrets/history scanner from the dep-audit-tooling matrix. Done when: CVE count, secrets found, and SBOM status are recorded.
- Test coverage analysis. Mode differential: separate production-code changes from test changes; search for covering tests per changed function; apply risk elevation: new function with no tests raises MEDIUM to HIGH, modified validation with unchanged tests is HIGH, complex logic over 20 lines with no tests is HIGH. Done when: production and test changes are separated, covering tests are located per changed function, and risk elevation is applied.
- Blast radius analysis. Mode differential: count callers per modified function (adapted to the language) and classify: 1 to 5 LOW, 6 to 20 MEDIUM, 21 to 50 HIGH, 50+ CRITICAL; combine risk score and blast class into a priority bucket, with deep analysis for high-risk high-blast changes and standard analysis for the rest. Escalate to adversarial analysis regardless of requested depth when removed code comes from "security", "CVE", or "fix" commits, access control modifiers are removed, validation is removed without replacement, external calls are added without checks, or high blast radius combines with a HIGH risk change. Done when: every modified function has a caller count, blast classification, and priority bucket, and escalations are marked.
- Deep context and adversarial analysis. Mode differential, HIGH RISK changes only: map entry conditions, state reads and writes, external calls, return values, and side effects; trace internal calls recursively and external calls across trust boundaries, checking reentrancy; identify invariants the change must preserve and run a Five-Whys root-cause (why changed, why the original existed, why it might break, why this approach, why it could fail in production); find repeated validation patterns and flag removals that break defense-in-depth. Run the five-step adversarial method inline or delegate it to a subagent: attacker model (who, what access, where they interact); concrete attack vectors (entry point, attack sequence, proof of accessibility verified in code, never assumed); exploitability rating (EASY, MEDIUM, HARD); complete exploit scenario with exact commands, file:line references, and quantified impact, never "could cause issues"; baseline cross-reference (violated invariant, broken trust boundary, bypassed validation, regressed fix). Done when: every HIGH RISK change has the deep-context map, Five-Whys, and all five adversarial steps with accessibility verified.
- Confirmed-mode data-flow gate. Mode confirmed: reporting scope is bounded to the supplied file, diff, or component; the entire reachable codebase is research scope used to confirm or refute each candidate. Detect the context from the supplied target before flagging: code type (API routes, frontend/templates, file handling, crypto/secrets, serialization, external requests, business workflows, config/headers/CORS, CI/CD dependencies, error handling, logging) and language or framework from file extensions and imports. For each candidate issue, research the data flow before flagging: where the input actually comes from; whether it is server-controlled (framework settings such as
django.conf.settings.*, environment variables, config files, framework constants, and hardcoded internal values are safe unless user input reaches them — a URL, path, or redirect target sourced from settings or config is not an SSRF, path-traversal, or open-redirect finding) or attacker-controlled (request params, body, and headers, unsigned cookies, URL path segments, file upload content and names, database content from other users, WebSocket messages); whether validation, sanitization, or allowlisting exists upstream; and which framework protections apply. Classify every candidate: HIGH (vulnerable pattern plus attacker-controlled input confirmed), MEDIUM (vulnerable pattern, input source unclear — record as Needs verification, never reported as a finding), LOW (theoretical, best-practice, or defense-in-depth — do not report). Do not flag test files (unless explicitly reviewing test security), dead or commented code, documentation strings, patterns using constants or server-controlled configuration, or code paths requiring prior authentication (note the auth requirement instead of flagging). Framework-mitigated patterns are safe unless the unsafe variant is present: auto-escaped template output (Django{{ variable }}, React{variable}, Vue{{ variable }}) and ORM parameterized queries (cursor.execute("...%s", (input,)),Model.objects.filter(id=input)) are safe; flag only|safe,{% autoescape off %},mark_safe(user_input),dangerouslySetInnerHTML={{__html: userInput}},v-html="userInput",.raw(),.extra(), orRawSQL()carrying string interpolation or user input. Always flag unconditionally when present:eval/execon user input, unsafe deserialization (pickle.loads,yaml.loadwithoutsafe_load, PHPunserialize, JavaObjectInputStream),shell=Trueorchild_process.execwith user input,innerHTML/dangerouslySetInnerHTML/v-htmlwith user input, SQL built by string interpolation or template literals with user input,os.systemwith user input, and hardcoded secrets, API keys, AWS secret keys, or private keys. Confirm exploitability per candidate before reporting: the framework does not mitigate it and no upstream validation or sanitization library (DOMPurify, bleach, and similar) neutralizes the input. Done when: code type and language or framework are detected, every candidate has a traced data flow, a HIGH/MEDIUM/LOW classification, and confirmed or refuted exploitability, and only HIGH-confidence findings are reported. - Edges-mode misuse-resistance walk. Mode edges, inline: enumerate every choice point in the target — parameters, return values, configuration keys, defaults, error paths, and state transitions — and test each against the seven edge cases: zero (0, false, equivalent), empty (empty string, empty collection, uninitialized state), null (null, None, nil, undefined, untyped zero value), negative (negative number or unvalidated signed integer), default (implementation-defined or unspecified default), type confusion (value of a different type than expected), and failure (error, exception, or unavailable). Mode edges, specialist: record the caller-named targets, bound the scope, and scan it — never traversing directories, following imports, or fetching remote content beyond what the caller explicitly names — for the four misuse categories: authentication and session-management anti-patterns (hardcoded credentials, weak or missing authentication checks, insecure session-token generation, missing or broken authorization guards, overly permissive default ACLs); cryptographic API misuse (predictable random sources, weak cipher or hash selection, ECB mode on block ciphers, missing authenticated encryption, hardcoded keys or IVs, incorrect key length, lack of salt for password hashing); configuration anti-patterns (excessive privileges, debug mode in production, disabled security controls, default credentials in config, credential leakage in logs or environment, insecure protocol or port defaults); and interface contract violations (missing null-checks on returned objects, unchecked array or buffer bounds, unvalidated external input passed to dangerous sinks, missing error handling on security-critical calls). Classify each concrete, reproducible misuse as input validation, cryptographic misuse, authentication/authorization bypass, resource exhaustion, insecure defaults, state machine violation, or other. Specialist mode validates exploitability per misuse: reachable from a realistic entry point without requiring an attacker to first introduce additional code or permissions; any pre-existing compensating control that reduces practical impact; and whether it is latent (present but unreachable with the current call graph), recorded as Exploitable, Likely Exploitable, Unlikely Exploitable, Not Exploitable, or Latent. Record per finding the exact file and line number, a one-sentence reproducible misuse example, a one-sentence security impact, and a concrete misuse-resistant recommendation; specialist mode's recommendation identifies the correct API, configuration, or pattern, states the minimum change required, and does not widen the attack surface. Done when: inline mode has tested every choice point against all seven edge cases, specialist mode has scanned every misuse category across the named scope, and every finding carries category, severity, location, misuse, impact, recommendation, and — in specialist mode — an exploitability determination.
- Severity grading. Assign each finding Critical/High/Medium/Low/Informational. Full and differential modes enforce the merge gate: critical and high block merge. Confirmed and edges report findings without a merge gate; the confirmed report is chat-only and the specialist report returns to the delegating caller. Mode confirmed grades HIGH-confidence findings: Critical (direct exploit, severe impact, no auth required: RCE, SQL injection reaching data, auth bypass, hardcoded secrets), High (exploitable with conditions, significant impact: stored XSS, SSRF to metadata, IDOR to sensitive data), Medium (specific conditions required, moderate impact: reflected XSS, CSRF on state-changing actions, path traversal), Low (defense-in-depth, minimal direct impact: missing headers, verbose errors, weak algorithms in non-critical context). Mode edges grades misuses: critical (direct privilege escalation or data loss), high (information disclosure or degraded integrity), medium (availability impact or escalation path), low (defense-in-depth violation or increased attack surface); specialist may assign Info and assigns Critical only when a single misuse instance is exploitable without prerequisite conditions or additional context. Done when: every finding has a severity.
- Compile report. Mode full: structured findings with severity, location, description, remediation owner. Mode differential: write the report file with the sections in § Output; no verbal-only delivery. Mode confirmed and mode edges: emit the chat report described in § Output; no files are written. Done when: the report carries all findings and every section for its mode.
Failure and recovery
- Incomplete change set: report what was audited and what was skipped; do not widen scope.
- Tool unavailable: note the missing scanner; proceed with manual review; flag as gap in report.
- Ambiguous trust boundary: document the ambiguity; flag for human review; do not assume safety.
- Scope creep: stop at the declared boundary; file separate findings for out-of-scope concerns.
- Missing baseline or unreadable diff (differential): stop; report the exact target or baseline that could not be resolved; do not invent a baseline.
- No Git history (differential): regression and historical-context analysis cannot complete; record the limitation, lower confidence, and do not fabricate blame output.
- Scope exceeds declared depth (differential): analyze the HIGH RISK subset at full depth, surface-scan MEDIUM, exclude LOW; record coverage percentage and confidence; never claim full analysis when scope-limited.
- Delegated adversarial phase does not converge (differential): keep findings that reached concrete impact, mark the rest non-converged with the blocker, and do not inflate severity.
- Evidence-less finding: discard it; every finding cites specific line numbers and commits; vague warnings are not findings.
- Partial result: the report states what was analyzed, what was excluded, and the confidence level; the done predicate holds only for the in-scope subset actually analyzed.
- Candidate lacks confirmed attacker control (confirmed): classify MEDIUM, record it as Needs verification with the open question, and never promote it to HIGH. Data-flow research (step 9) is mandatory before flagging; reporting on pattern matching alone is a contract failure.
- No high-confidence findings (confirmed): return the cleared report stating no high-confidence vulnerabilities were identified; do not fabricate findings to fill the report.
- Supplied target unreachable or unreadable (confirmed): report exactly what was inaccessible and stop; do not widen scope, guess at unreachable code, or report findings without evidence. Remediation is stated as a recommendation in the report only; the read-only authority is never breached.
- No target provided (edges): stop without findings and state that the target was not specified; specialist mode returns
error: no-targetsand stops. - Unbounded scope (edges, specialist): the caller named a directory or glob — stop and ask for an explicit file list; do not auto-expand.
- Unreadable named target (edges, specialist): record it as "Unreadable: [filename]" in the report and continue with the remaining targets.
- No security-relevant edge cases (edges): return an empty findings report stating no sharp edges were found; specialist mode appends "No misuse patterns detected in the named scope."
- Missing source code (edges): the referenced code cannot be located — stop and state which target could not be examined.
- Partial specialist analysis (edges): the four phases cannot complete for a target — report findings up to the failure point and annotate the incomplete finding with "Phase N incomplete: [reason]." Never present a partial specialist report as complete.
Output
Mode full: a structured audit report with executive summary (finding counts by severity), STRIDE findings table (threat class, component, severity, description, remediation owner), OWASP walkthrough (pass/fail per category), supply-chain scan results (CVE count, secrets found, SBOM status), and merge gate decision (block if critical/high present, else pass).
Mode differential: a markdown report file with sections in this order: Executive Summary (severity distribution, overall risk, recommendation, key metrics), What Changed (commit range, per-file table with status word: PASS clean, WARN non-blocking finding, FAIL blocking critical or high finding), Critical Findings (per HIGH/CRITICAL issue with file:line, blast radius, historical context, attack scenario, fix), Test Coverage Analysis, Blast Radius Analysis, Historical Context, Recommendations (immediate, before production, technical debt), Analysis Methodology (strategy, coverage, limitations, confidence), Appendices. Severity words: Critical, High, Medium, Low.
Mode confirmed: a chat-only markdown report titled ## Security Review: [File/Component Name]: Summary (count by severity, risk level, confidence) → Findings ([VULN-NNN] [Type] (Severity) with Location, Confidence, Issue, Impact, Evidence, Fix) → Needs Verification ([VERIFY-NNN] with Location and Question). A cleared report states "No high-confidence vulnerabilities identified."
Mode edges: a structured findings report with one entry per sharp edge (severity, category, location, misuse, impact, recommendation; specialist mode adds the exploitability determination and a per-severity totals line), sorted by severity descending, returned in the conversation or to the delegating caller with no filesystem writes, no VCS operations, and no remote calls; an empty findings report with a confirmation message when no edges are found.