diff --git a/.cursor/README.md b/.cursor/README.md index 6da8407..0a1202b 100644 --- a/.cursor/README.md +++ b/.cursor/README.md @@ -91,7 +91,7 @@ Multi-phase code review against task specs. Produces structured findings with ve ### security -OWASP-based security testing and audit. +5-phase OWASP-based security audit: dependency scan, static analysis, OWASP Top 10 review, infrastructure review, consolidated report with severity-ranked findings. Integrated into autopilot as an optional step before deploy. ### retrospective @@ -150,7 +150,7 @@ Or just use `/autopilot` to run steps 0-5 automatically. | **implement** | "implement", "start implementation" | `_docs/03_implementation/` | | **code-review** | "code review", "review code" | Verdict: PASS / FAIL / PASS_WITH_WARNINGS | | **refactor** | "refactor", "improve code" | `_docs/04_refactoring/` | -| **security** | "security audit", "OWASP" | Security findings report | +| **security** | "security audit", "OWASP", "vulnerability scan" | `_docs/05_security/` | | **document** | "document", "document codebase", "reverse-engineer docs" | `_docs/02_document/` + `_docs/00_problem/` + `_docs/01_solution/` | | **deploy** | "deploy", "CI/CD", "observability" | `_docs/04_deploy/` | | **retrospective** | "retrospective", "retro" | `_docs/05_metrics/` | @@ -184,6 +184,7 @@ _docs/ ├── 03_implementation/ — batch reports, FINAL report ├── 04_deploy/ — containerization, CI/CD, environments, observability, procedures, scripts ├── 04_refactoring/ — baseline, discovery, analysis, execution, hardening +├── 05_security/ — dependency scan, static analysis, OWASP review, infrastructure, report └── 05_metrics/ — retro_[YYYY-MM-DD].md ``` diff --git a/.cursor/rules/openapi.mdc b/.cursor/rules/openapi.mdc index b19cedb..eb597d5 100644 --- a/.cursor/rules/openapi.mdc +++ b/.cursor/rules/openapi.mdc @@ -1,7 +1,6 @@ --- description: "OpenAPI/Swagger API documentation standards — applied when editing API spec files" globs: ["**/openapi*", "**/swagger*"] -alwaysApply: false --- # OpenAPI diff --git a/.cursor/skills/autopilot/SKILL.md b/.cursor/skills/autopilot/SKILL.md index 4a06f08..72a333c 100644 --- a/.cursor/skills/autopilot/SKILL.md +++ b/.cursor/skills/autopilot/SKILL.md @@ -111,13 +111,14 @@ This skill activates when the user wants to: │ GREENFIELD FLOW (flows/greenfield.md): │ │ Step 0 Problem → Step 1 Research → Step 2 Plan │ │ → Step 3 Decompose → [SESSION] → Step 4 Implement │ -│ → Step 5 Run Tests → Step 6 Deploy → DONE │ +│ → Step 5 Run Tests → 5b Security (opt) → Step 6 Deploy │ +│ → DONE │ │ │ │ EXISTING CODE FLOW (flows/existing-code.md): │ │ Pre-Step Document → 2b Test Spec → 2c Decompose Tests │ │ → [SESSION] → 2d Implement Tests → 2e Refactor │ │ → 2f New Task → [SESSION] → 2g Implement │ -│ → 2h Run Tests → 2i Deploy → DONE │ +│ → 2h Run Tests → 2hb Security (opt) → 2i Deploy → DONE │ │ │ │ STATE: _docs/_autopilot_state.md (see state.md) │ │ PROTOCOLS: choice format, Jira auth, errors (see protocols.md) │ diff --git a/.cursor/skills/autopilot/flows/existing-code.md b/.cursor/skills/autopilot/flows/existing-code.md index 465a61e..1da7e83 100644 --- a/.cursor/skills/autopilot/flows/existing-code.md +++ b/.cursor/skills/autopilot/flows/existing-code.md @@ -14,6 +14,7 @@ Workflow for projects with an existing codebase. Starts with documentation, prod | 2f | New Task | new-task/SKILL.md | Steps 1–8 (loop) | | 2g | Implement | implement/SKILL.md | (batch-driven, no fixed sub-steps) | | 2h | Run Tests | (autopilot-managed) | Unit tests → Integration/blackbox tests | +| 2hb | Security Audit | security/SKILL.md | Phase 1–5 (optional) | | 2i | Deploy | deploy/SKILL.md | Steps 1–7 | After Step 2i, the existing-code workflow is complete. @@ -119,7 +120,7 @@ Action: Run the full test suite to verify the implementation before deployment. 2. **Integration / blackbox tests**: if `docker-compose.test.yml` or an equivalent test environment exists, spin it up and run the integration test suite 3. **Report results**: present a summary of passed/failed/skipped tests -If all tests pass → auto-chain to Step 2i (Deploy). +If all tests pass → auto-chain to Step 2hb (Security Audit). If tests fail → present using Choose format: @@ -137,8 +138,29 @@ If tests fail → present using Choose format: --- +**Step 2hb — Security Audit (optional)** +Condition: the autopilot state shows Step 2h (Run Tests) is completed AND the autopilot state does NOT show Step 2hb (Security Audit) as completed or skipped AND (`_docs/04_deploy/` does not exist or is incomplete) + +Action: Present using Choose format: + +``` +══════════════════════════════════════ + DECISION REQUIRED: Run security audit before deploy? +══════════════════════════════════════ + A) Run security audit (recommended for production deployments) + B) Skip — proceed directly to deploy +══════════════════════════════════════ + Recommendation: A — catches vulnerabilities before production +══════════════════════════════════════ +``` + +- If user picks A → Read and execute `.cursor/skills/security/SKILL.md`. After completion, auto-chain to Step 2i (Deploy). +- If user picks B → Mark Step 2hb as `skipped` in the state file, auto-chain to Step 2i (Deploy). + +--- + **Step 2i — Deploy** -Condition: the autopilot state shows Step 2h (Run Tests) is completed AND (`_docs/04_deploy/` does not exist or is incomplete) +Condition: the autopilot state shows Step 2h (Run Tests) is completed AND (Step 2hb is completed or skipped) AND (`_docs/04_deploy/` does not exist or is incomplete) Action: Read and execute `.cursor/skills/deploy/SKILL.md` @@ -177,5 +199,6 @@ Action: The project completed a full cycle. Present status and loop back to New | Refactor (Step 2e) | Auto-chain → New Task (Step 2f) | | New Task (Step 2f) | **Session boundary** — suggest new conversation before Implement | | Implement (Step 2g) | Auto-chain → Run Tests (Step 2h) | -| Run Tests (Step 2h, all pass) | Auto-chain → Deploy (Step 2i) | +| Run Tests (Step 2h, all pass) | Auto-chain → Security Audit choice (Step 2hb) | +| Security Audit (Step 2hb, done or skipped) | Auto-chain → Deploy (Step 2i) | | Deploy (Step 2i) | **Workflow complete** — existing-code flow done | diff --git a/.cursor/skills/autopilot/flows/greenfield.md b/.cursor/skills/autopilot/flows/greenfield.md index 8276183..807a0af 100644 --- a/.cursor/skills/autopilot/flows/greenfield.md +++ b/.cursor/skills/autopilot/flows/greenfield.md @@ -1,6 +1,6 @@ # Greenfield Workflow -Workflow for new projects built from scratch. Flows linearly: Problem → Research → Plan → Decompose → Implement → Run Tests → Deploy. +Workflow for new projects built from scratch. Flows linearly: Problem → Research → Plan → Decompose → Implement → Run Tests → Security Audit (optional) → Deploy. ## Step Reference Table @@ -8,10 +8,11 @@ Workflow for new projects built from scratch. Flows linearly: Problem → Resear |------|-----------|------------------------|---------------------------------------| | 0 | Problem | problem/SKILL.md | Phase 1–4 | | 1 | Research | research/SKILL.md | Mode A: Phase 1–4 · Mode B: Step 0–8 | -| 2 | Plan | plan/SKILL.md | Step 1–6 | +| 2 | Plan | plan/SKILL.md | Step 1–6 + Final | | 3 | Decompose | decompose/SKILL.md | Step 1–4 | | 4 | Implement | implement/SKILL.md | (batch-driven, no fixed sub-steps) | | 5 | Run Tests | (autopilot-managed) | Unit tests → Integration/blackbox tests | +| 5b | Security Audit | security/SKILL.md | Phase 1–5 (optional) | | 6 | Deploy | deploy/SKILL.md | Step 1–7 | ## Detection Rules @@ -76,7 +77,7 @@ If `_docs/02_document/` exists but is incomplete (has some artifacts but no `FIN --- **Step 3 — Decompose** -Condition: `_docs/02_document/` contains `architecture.md` AND `_docs/02_document/components/` has at least one component AND `_docs/02_tasks/` does not exist or has no task files (excluding `_dependencies_table.md`) AND (workspace has no source code files OR the user explicitly chose normal workflow in Step 2c) +Condition: `_docs/02_document/` contains `architecture.md` AND `_docs/02_document/components/` has at least one component AND `_docs/02_tasks/` does not exist or has no task files (excluding `_dependencies_table.md`) Action: Read and execute `.cursor/skills/decompose/SKILL.md` @@ -102,7 +103,7 @@ Action: Run the full test suite to verify the implementation before deployment. 2. **Integration / blackbox tests**: if `docker-compose.test.yml` or an equivalent test environment exists, spin it up and run the integration test suite 3. **Report results**: present a summary of passed/failed/skipped tests -If all tests pass → auto-chain to Step 6 (Deploy). +If all tests pass → auto-chain to Step 5b (Security Audit). If tests fail → present using Choose format: @@ -120,8 +121,29 @@ If tests fail → present using Choose format: --- +**Step 5b — Security Audit (optional)** +Condition: the autopilot state shows Step 5 (Run Tests) is completed AND the autopilot state does NOT show Step 5b (Security Audit) as completed or skipped AND (`_docs/04_deploy/` does not exist or is incomplete) + +Action: Present using Choose format: + +``` +══════════════════════════════════════ + DECISION REQUIRED: Run security audit before deploy? +══════════════════════════════════════ + A) Run security audit (recommended for production deployments) + B) Skip — proceed directly to deploy +══════════════════════════════════════ + Recommendation: A — catches vulnerabilities before production +══════════════════════════════════════ +``` + +- If user picks A → Read and execute `.cursor/skills/security/SKILL.md`. After completion, auto-chain to Step 6 (Deploy). +- If user picks B → Mark Step 5b as `skipped` in the state file, auto-chain to Step 6 (Deploy). + +--- + **Step 6 — Deploy** -Condition: the autopilot state shows Step 5 (Run Tests) is completed AND (`_docs/04_deploy/` does not exist or is incomplete) +Condition: the autopilot state shows Step 5 (Run Tests) is completed AND (Step 5b is completed or skipped) AND (`_docs/04_deploy/` does not exist or is incomplete) Action: Read and execute `.cursor/skills/deploy/SKILL.md` @@ -142,5 +164,6 @@ Action: Report project completion with summary. If the user runs autopilot again | Plan | Auto-chain → Decompose | | Decompose | **Session boundary** — suggest new conversation before Implement | | Implement | Auto-chain → Run Tests (Step 5) | -| Run Tests (all pass) | Auto-chain → Deploy (Step 6) | +| Run Tests (all pass) | Auto-chain → Security Audit choice (Step 5b) | +| Security Audit (done or skipped) | Auto-chain → Deploy (Step 6) | | Deploy | Report completion | diff --git a/.cursor/skills/autopilot/protocols.md b/.cursor/skills/autopilot/protocols.md index 2a6ab5e..f1b8fec 100644 --- a/.cursor/skills/autopilot/protocols.md +++ b/.cursor/skills/autopilot/protocols.md @@ -106,6 +106,101 @@ All error situations that require user input MUST use the **Choose A / B / C / D | User wants to go back to a previous step | Use Choose format: A) re-run (with overwrite warning), B) stay on current step | | User asks "where am I?" without wanting to continue | Show Status Summary only, do not start execution | +## Error Recovery Protocol + +### Stuck Detection + +When executing a sub-skill, monitor for these signals: + +- Same artifact overwritten 3+ times without meaningful change +- Sub-skill repeatedly asks the same question after receiving an answer +- No new artifacts saved for an extended period despite active execution + +### Recovery Actions (ordered) + +1. **Re-read state**: read `_docs/_autopilot_state.md` and cross-check against `_docs/` folders +2. **Retry current sub-step**: re-read the sub-skill's SKILL.md and restart from the current sub-step +3. **Escalate**: after 2 failed retries, present diagnostic summary to user using Choose format: + +``` +══════════════════════════════════════ + RECOVERY: [skill name] stuck at [sub-step] +══════════════════════════════════════ + A) Retry with fresh context (new conversation) + B) Skip this sub-step with warning + C) Abort and fix manually +══════════════════════════════════════ + Recommendation: A — fresh context often resolves stuck loops +══════════════════════════════════════ +``` + +### Circuit Breaker + +If the same autopilot step fails 3 consecutive times across conversations: + +- Record the failure pattern in the state file's `Blockers` section +- Do NOT auto-retry on next invocation +- Present the blocker and ask user for guidance before attempting again + +## Context Management Protocol + +### Principle + +Disk is memory. Never rely on in-context accumulation — read from `_docs/` artifacts, not from conversation history. + +### Minimal Re-Read Set Per Skill + +When re-entering a skill (new conversation or context refresh): + +- Always read: `_docs/_autopilot_state.md` +- Always read: the active skill's `SKILL.md` +- Conditionally read: only the `_docs/` artifacts the current sub-step requires (listed in each skill's Context Resolution section) +- Never bulk-read: do not load all `_docs/` files at once + +### Mid-Skill Interruption + +If context is filling up during a long skill (e.g., document, implement): + +1. Save current sub-step progress to the skill's artifact directory +2. Update `_docs/_autopilot_state.md` with exact sub-step position +3. Suggest a new conversation: "Context is getting long — recommend continuing in a fresh conversation for better results" +4. On re-entry, the skill's resumability protocol picks up from the saved sub-step + +### Large Artifact Handling + +When a skill needs to read large files (e.g., full solution.md, architecture.md): + +- Read only the sections relevant to the current sub-step +- Use search tools (Grep, SemanticSearch) to find specific sections rather than reading entire files +- Summarize key decisions from prior steps in the state file so they don't need to be re-read + +## Rollback Protocol + +### Implementation Steps (git-based) + +Handled by `/implement` skill — each batch commit is a rollback checkpoint via `git revert`. + +### Planning/Documentation Steps (artifact-based) + +For steps that produce `_docs/` artifacts (problem, research, plan, decompose, document): + +1. **Before overwriting**: if re-running a step that already has artifacts, the sub-skill's prerequisite check asks the user (resume/overwrite/skip) +2. **Rollback to previous step**: use Choose format: + +``` +══════════════════════════════════════ + ROLLBACK: Re-run [step name]? +══════════════════════════════════════ + A) Re-run the step (overwrites current artifacts) + B) Stay on current step +══════════════════════════════════════ + Warning: This will overwrite files in _docs/[folder]/ +══════════════════════════════════════ +``` + +3. **Git safety net**: artifacts are committed with each autopilot step completion. To roll back: `git log --oneline _docs/` to find the commit, then `git checkout -- _docs//` +4. **State file rollback**: when rolling back artifacts, also update `_docs/_autopilot_state.md` to reflect the rolled-back step (set it to `in_progress`, clear completed date) + ## Status Summary On every invocation, before executing any skill, present a status summary built from the state file (with folder scan fallback). Use the template matching the active flow (see Flow Resolution in SKILL.md). @@ -122,6 +217,7 @@ On every invocation, before executing any skill, present a status summary built Step 3 Decompose [DONE (N tasks) / IN PROGRESS / NOT STARTED] Step 4 Implement [DONE / IN PROGRESS (batch M of ~N) / NOT STARTED] Step 5 Run Tests [DONE (N passed, M failed) / IN PROGRESS / NOT STARTED] + Step 5b Security Audit [DONE / SKIPPED / IN PROGRESS / NOT STARTED] Step 6 Deploy [DONE / IN PROGRESS / NOT STARTED] ═══════════════════════════════════════════════════ Current: Step N — Name @@ -144,6 +240,7 @@ On every invocation, before executing any skill, present a status summary built Step 2f New Task [DONE (N tasks) / IN PROGRESS / NOT STARTED] Step 2g Implement [DONE / IN PROGRESS (batch M of ~N) / NOT STARTED] Step 2h Run Tests [DONE (N passed, M failed) / IN PROGRESS / NOT STARTED] + Step 2hb Security Audit [DONE / SKIPPED / IN PROGRESS / NOT STARTED] Step 2i Deploy [DONE / IN PROGRESS / NOT STARTED] ═══════════════════════════════════════════════════ Current: Step N — Name diff --git a/.cursor/skills/autopilot/state.md b/.cursor/skills/autopilot/state.md index db20bcc..884c62f 100644 --- a/.cursor/skills/autopilot/state.md +++ b/.cursor/skills/autopilot/state.md @@ -10,16 +10,16 @@ The autopilot persists its state to `_docs/_autopilot_state.md`. This file is th # Autopilot State ## Current Step -step: [0-6 or "2b" / "2c" / "2d" / "2e" / "2f" / "2g" / "2h" / "2i" or "done"] -name: [Problem / Research / Plan / Blackbox Test Spec / Decompose Tests / Implement Tests / Refactor / New Task / Implement / Run Tests / Deploy / Decompose / Done] -status: [not_started / in_progress / completed] +step: [0-6 or "2b" / "2c" / "2d" / "2e" / "2f" / "2g" / "2h" / "2hb" / "2i" or "5b" or "done"] +name: [Problem / Research / Plan / Blackbox Test Spec / Decompose Tests / Implement Tests / Refactor / New Task / Implement / Run Tests / Security Audit / Deploy / Decompose / Done] +status: [not_started / in_progress / completed / skipped] sub_step: [optional — sub-skill internal step number + name if interrupted mid-step] ## Step ↔ SubStep Reference (include the step reference table from the active flow file) When updating `Current Step`, always write it as: - step: N ← autopilot step (0–6 or 2b/2c/2d/2e/2f/2g/2h/2i) + step: N ← autopilot step (0–6 or 2b/2c/2d/2e/2f/2g/2h/2hb/2i or 5b) sub_step: M ← sub-skill's own internal step/phase number + name Example: step: 2 diff --git a/.cursor/skills/plan/SKILL.md b/.cursor/skills/plan/SKILL.md index f7045bf..ef4b3a1 100644 --- a/.cursor/skills/plan/SKILL.md +++ b/.cursor/skills/plan/SKILL.md @@ -55,7 +55,7 @@ Read `steps/01_artifact-management.md` for directory structure, save timing, sav ## Progress Tracking -At the start of execution, create a TodoWrite with all steps (1 through 6). Update status as each step completes. +At the start of execution, create a TodoWrite with all steps (1 through 6 plus Final). Update status as each step completes. ## Workflow @@ -125,3 +125,31 @@ Read and follow `steps/07_quality-checklist.md`. | File structure within templates | PROCEED | | Contradictions between input files | ASK user | | Risk mitigation requires architecture change | ASK user | + +## Methodology Quick Reference + +``` +┌────────────────────────────────────────────────────────────────┐ +│ Solution Planning (6-Step + Final) │ +├────────────────────────────────────────────────────────────────┤ +│ PREREQ: Data Gate (BLOCKING) │ +│ → verify AC, restrictions, input_data, solution exist │ +│ │ +│ 1. Integration Tests → blackbox-test-spec/SKILL.md │ +│ [BLOCKING: user confirms test coverage] │ +│ 2. Solution Analysis → architecture, data model, deployment │ +│ [BLOCKING: user confirms architecture] │ +│ 3. Component Decomp → component specs + interfaces │ +│ [BLOCKING: user confirms components] │ +│ 4. Review & Risk → risk register, iterations │ +│ [BLOCKING: user confirms mitigations] │ +│ 5. Test Specifications → per-component test specs │ +│ 6. Jira Epics → epic per component + bootstrap │ +│ ───────────────────────────────────────────────── │ +│ Final: Quality Checklist → FINAL_report.md │ +├────────────────────────────────────────────────────────────────┤ +│ Principles: Single Responsibility · Dumb code, smart data │ +│ Save immediately · Ask don't assume │ +│ Plan don't code │ +└────────────────────────────────────────────────────────────────┘ +``` diff --git a/.cursor/skills/plan/templates/final-report.md b/.cursor/skills/plan/templates/final-report.md index 404dee3..0e27016 100644 --- a/.cursor/skills/plan/templates/final-report.md +++ b/.cursor/skills/plan/templates/final-report.md @@ -1,6 +1,6 @@ # Final Planning Report Template -Use this template after completing all 5 steps and the quality checklist. Save as `_docs/02_document/FINAL_report.md`. +Use this template after completing all 6 steps and the quality checklist. Save as `_docs/02_document/FINAL_report.md`. --- diff --git a/.cursor/skills/security/SKILL.md b/.cursor/skills/security/SKILL.md index 5be5701..1e35084 100644 --- a/.cursor/skills/security/SKILL.md +++ b/.cursor/skills/security/SKILL.md @@ -1,300 +1,347 @@ --- -name: security-testing -description: "Test for security vulnerabilities using OWASP principles. Use when conducting security audits, testing auth, or implementing security practices." -category: specialized-testing -priority: critical -tokenEstimate: 1200 -agents: [qe-security-scanner, qe-api-contract-validator, qe-quality-analyzer] -implementation_status: optimized -optimization_version: 1.0 -last_optimized: 2025-12-02 -dependencies: [] -quick_reference_card: true -tags: [security, owasp, sast, dast, vulnerabilities, auth, injection] -trust_tier: 3 -validation: - schema_path: schemas/output.json - validator_path: scripts/validate-config.json - eval_path: evals/security-testing.yaml +name: security +description: | + OWASP-based security audit skill. Analyzes codebase for vulnerabilities across dependency scanning, + static analysis, OWASP Top 10 review, and secrets detection. Produces a structured security report + with severity-ranked findings and remediation guidance. + Can be invoked standalone or as part of the autopilot flow (optional step before deploy). + Trigger phrases: + - "security audit", "security scan", "OWASP review" + - "vulnerability scan", "security check" + - "check for vulnerabilities", "pentest" +category: review +tags: [security, owasp, sast, vulnerabilities, auth, injection, secrets] +disable-model-invocation: true --- -# Security Testing +# Security Audit - -When testing security or conducting audits: -1. TEST OWASP Top 10 vulnerabilities systematically -2. VALIDATE authentication and authorization on every endpoint -3. SCAN dependencies for known vulnerabilities (npm audit) -4. CHECK for injection attacks (SQL, XSS, command) -5. VERIFY secrets aren't exposed in code/logs +Analyze the codebase for security vulnerabilities using OWASP principles. Produces a structured report with severity-ranked findings, remediation suggestions, and a security checklist verdict. -**Quick Security Checks:** -- Access control → Test horizontal/vertical privilege escalation -- Crypto → Verify password hashing, HTTPS, no sensitive data exposed -- Injection → Test SQL injection, XSS, command injection -- Auth → Test weak passwords, session fixation, MFA enforcement -- Config → Check error messages don't leak info +## Core Principles -**Critical Success Factors:** -- Think like an attacker, build like a defender -- Security is built in, not added at the end -- Test continuously in CI/CD, not just before release - +- **OWASP-driven**: use the current OWASP Top 10 as the primary framework — verify the latest version at https://owasp.org/www-project-top-ten/ at audit start +- **Evidence-based**: every finding must reference a specific file, line, or configuration +- **Severity-ranked**: findings sorted Critical > High > Medium > Low +- **Actionable**: every finding includes a concrete remediation suggestion +- **Save immediately**: write artifacts to disk after each phase; never accumulate unsaved work +- **Complement, don't duplicate**: the `/code-review` skill does a lightweight security quick-scan; this skill goes deeper -## Quick Reference Card +## Context Resolution -### When to Use -- Security audits and penetration testing -- Testing authentication/authorization -- Validating input sanitization -- Reviewing security configuration +**Project mode** (default): +- PROBLEM_DIR: `_docs/00_problem/` +- SOLUTION_DIR: `_docs/01_solution/` +- DOCUMENT_DIR: `_docs/02_document/` +- SECURITY_DIR: `_docs/05_security/` -### OWASP Top 10 -Use the most recent **stable** version of the OWASP Top 10. At the start of each security audit, research the current version at https://owasp.org/www-project-top-ten/ and test against all listed categories. Do not rely on a hardcoded list — the OWASP Top 10 is updated periodically and the current version must be verified. +**Standalone mode** (explicit target provided, e.g. `/security @src/api/`): +- TARGET: the provided path +- SECURITY_DIR: `_standalone/security/` -### Tools -| Type | Tool | Purpose | -|------|------|---------| -| SAST | SonarQube, Semgrep | Static code analysis | -| DAST | OWASP ZAP, Burp | Dynamic scanning | -| Deps | npm audit, Snyk | Dependency vulnerabilities | -| Secrets | git-secrets, TruffleHog | Secret scanning | +Announce the detected mode and resolved paths to the user before proceeding. -### Agent Coordination -- `qe-security-scanner`: Multi-layer SAST/DAST scanning -- `qe-api-contract-validator`: API security testing -- `qe-quality-analyzer`: Security code review +## Prerequisite Checks + +1. Codebase must contain source code files — **STOP if empty** +2. Create SECURITY_DIR if it does not exist +3. If SECURITY_DIR already contains artifacts, ask user: **resume, overwrite, or skip?** +4. If `_docs/00_problem/security_approach.md` exists, read it for project-specific security requirements + +## Progress Tracking + +At the start of execution, create a TodoWrite with all phases (1 through 5). Update status as each phase completes. + +## Workflow + +### Phase 1: Dependency Scan + +**Role**: Security analyst +**Goal**: Identify known vulnerabilities in project dependencies +**Constraints**: Scan only — no code changes + +1. Detect the project's package manager(s): `requirements.txt`, `package.json`, `Cargo.toml`, `*.csproj`, `go.mod` +2. Run the appropriate audit tool: + - Python: `pip audit` or `safety check` + - Node: `npm audit` + - Rust: `cargo audit` + - .NET: `dotnet list package --vulnerable` + - Go: `govulncheck` +3. If no audit tool is available, manually inspect dependency files for known CVEs using WebSearch +4. Record findings with CVE IDs, affected packages, severity, and recommended upgrade versions + +**Self-verification**: +- [ ] All package manifests scanned +- [ ] Each finding has a CVE ID or advisory reference +- [ ] Upgrade paths identified for Critical/High findings + +**Save action**: Write `SECURITY_DIR/dependency_scan.md` --- -## Key Vulnerability Tests +### Phase 2: Static Analysis (SAST) -### 1. Broken Access Control -```javascript -// Horizontal escalation - User A accessing User B's data -test('user cannot access another user\'s order', async () => { - const userAToken = await login('userA'); - const userBOrder = await createOrder('userB'); +**Role**: Security engineer +**Goal**: Identify code-level vulnerabilities through static analysis +**Constraints**: Analysis only — no code changes - const response = await api.get(`/orders/${userBOrder.id}`, { - headers: { Authorization: `Bearer ${userAToken}` } - }); - expect(response.status).toBe(403); -}); +Scan the codebase for these vulnerability patterns: -// Vertical escalation - Regular user accessing admin -test('regular user cannot access admin', async () => { - const userToken = await login('regularUser'); - expect((await api.get('/admin/users', { - headers: { Authorization: `Bearer ${userToken}` } - })).status).toBe(403); -}); -``` +**Injection**: +- SQL injection via string interpolation or concatenation +- Command injection (subprocess with shell=True, exec, eval, os.system) +- XSS via unsanitized user input in HTML output +- Template injection -### 2. Injection Attacks -```javascript -// SQL Injection -test('prevents SQL injection', async () => { - const malicious = "' OR '1'='1"; - const response = await api.get(`/products?search=${malicious}`); - expect(response.body.length).toBeLessThan(100); // Not all products -}); +**Authentication & Authorization**: +- Hardcoded credentials, API keys, passwords, tokens +- Missing authentication checks on endpoints +- Missing authorization checks (horizontal/vertical escalation paths) +- Weak password validation rules -// XSS -test('sanitizes HTML output', async () => { - const xss = ''; - await api.post('/comments', { text: xss }); +**Cryptographic Failures**: +- Plaintext password storage (no hashing) +- Weak hashing algorithms (MD5, SHA1 for passwords) +- Hardcoded encryption keys or salts +- Missing TLS/HTTPS enforcement - const html = (await api.get('/comments')).body; - expect(html).toContain('<script>'); - expect(html).not.toContain('