# http4k security audit: orchestrator brief

You drive a full security audit across all http4k modules at one pinned commit.
You dispatch per-module sub-agents, collect their JSON returns, and write the
roll-up. You don't audit any module yourself.

## Pinned commit

Resolve once: `git -C . rev-parse master`. Call
the result `<SHA>`. Every sub-agent gets the same SHA. No pull / rebase / merge
mid-run.

## Module enumeration

Find every `build.gradle.kts` under the repo, excluding the repo root and
anything under `gradle/gradle-plugins/`, `build/`, or `out/`. For each surviving
directory compute:

- `<MODULE_PATH>` — directory path relative to the repo root (e.g.
  `core/multipart`). Must not be absolute.
- `<MODULE_NAME>` — `<MODULE_PATH>` with `/` swapped for `-`.

## Skip rules

Three reasons, applied in both the pre-filter and inside each sub-agent:

- `<MODULE_PATH>/src/main` doesn't exist → `bom-or-aggregator`
- `<MODULE_NAME>` matches `*-testing`, `*-fake`, or `*-test-*` → `testing-module`
- module's entire production surface is `Insecure*` / `Unsafe*`, in `.insecure.`
  / `.unsafe.` packages, or KDoc-flagged "do not use in production" →
  `insecure-by-design` (sub-agent only — requires reading source)

Pre-filter the first two before dispatch and record them as `no-op` with the
matching reason. Sub-agents re-check all three.

## Fan-out

One `Agent` call per module, **all in a single assistant turn** — hundreds of
parallel calls in one message. The runtime queues what it can't run concurrently.
No batching, no waiting between waves, no per-module orchestration between
dispatches.

Every call uses `subagent_type: "general-purpose"` and `isolation: "worktree"`.
Without isolation, parallel sub-agents would clobber each other's checkouts.

Each sub-agent prompt is:

1. Preamble: `You are auditing module <MODULE_NAME> at <MODULE_PATH>, pinned to commit <SHA>.`
2. The per-module brief below, verbatim between the BEGIN/END fences, with
   `<MODULE_NAME>`, `<MODULE_PATH>`, `<SHA>` substituted everywhere.

Sub-agents do their own reading, test-writing, committing, pushing, and
PR-opening. Their final message is a single fenced JSON block per the return
contract — nothing else.

## Failure handling

- **Unparseable / crashed return** → record `errored` with zero counts and
  `prUrl: null`:

  ```json
  {
    "module": "<MODULE_NAME>", "sha": "<SHA>", "status": "errored",
    "reason": "<short reason>", "verified": 0, "likely": 0, "speculative": 0,
    "maxSeverity": null, "prUrl": null
  }
  ```

- **Valid JSON, `status: "audited"`, missing `prUrl`** → record `errored` with
  `prUrl: null` and `reason` set to a short failure description, but **preserve
  the returned `verified`, `likely`, `speculative`, and `maxSeverity`**. The
  audit work isn't lost just because the PR step failed.

Do not retry. One failed module doesn't affect any other.

## Roll-up

Once every module has either returned or been recorded as errored, write
`AUDIT-SUMMARY.md`:

- **Header**: pinned `<SHA>`, run date, and five disjoint bucket counts that sum
  to the total enumerated:
  - `pre-filter no-op` — skipped before dispatch
  - `sub-agent no-op` — returned `no-op`
  - `cleared` — `audited`, V + L = 0
  - `with findings` — `audited`, V + L > 0
  - `errored` — orchestrator-recorded failure

  Plus aggregate Verified / Likely / Speculative summed across every module with
  non-zero counts (audited + errored-with-preserved-counts).
- **Sections, in order**: `Critical`, `High`, `Medium`, `Low`, `Cleared`,
  `No-op`, `Errored`. Each module appears under its `maxSeverity` bucket, or
  `Cleared` if V + L = 0, or `No-op` / `Errored` per status.
- Bullet format:
  `- [<MODULE_NAME>](<prUrl>) — V:<verified> L:<likely> S:<speculative>`.
  For `No-op` and `Errored`, omit the link and append ` — <reason>`.
- No prose between sections.

That's the whole job: resolve SHA, enumerate, pre-filter, fan out, collect JSON
returns, write the roll-up. Don't read source. Don't audit yourself.

--- BEGIN PER-MODULE BRIEF ---

# http4k security audit: per-module brief

You are auditing `<MODULE_NAME>` at `<MODULE_PATH>`, pinned to `<SHA>`. If any
of those three is unresolved, stop and surface the missing input.

You run inside an isolated git worktree. CWD is the worktree root;
`<MODULE_PATH>` is relative to it. Branches and checkouts don't affect other
sub-agents, but the underlying `.git` is shared so pushed refs are visible to
`gh`.

Your output is one draft PR with a `SECURITY-AUDIT.md` plus failing tests for
any Verified findings. You don't fix anything. CI is expected red on PRs with
Verified findings; cleared PRs leave CI green.

## Setup

1. `git checkout <SHA>` if not already there (detached HEAD is expected).
2. **Skip-and-exit** — return the contract with `status: "no-op"` and the
   matching reason without opening a PR if:
   - `<MODULE_PATH>/src/main` doesn't exist → `bom-or-aggregator`
   - `<MODULE_NAME>` matches `*-testing`, `*-fake`, or `*-test-*` →
     `testing-module`
   - The module's entire production surface is `Insecure*` / `Unsafe*` classes,
     under `.insecure.` / `.unsafe.` packages, or KDoc-flagged "do not use in
     production" → `insecure-by-design`. Single matching classes inside an
     otherwise-normal module: skip the class, audit the rest.

## What counts as a finding

- A real security bug at a trust boundary: code that parses, decodes,
  deserialises, signs, verifies, renders, or routes attacker-controlled bytes
  (request body / headers / query / path / cookies / forms, callback URIs,
  upstream responses, file uploads).
- A class is on the boundary if it ships a `ServerFilter`, `RoutingHttpHandler`,
  `Body.Lens`, auth provider/verifier, credential decoder, template renderer,
  (de)serialiser, or crypto primitive — even if the module doesn't bind a
  listener.
- A finding needs both a concrete exploit path and a concrete impact (DoS,
  replay, info disclosure, RCE, auth bypass, supply-chain compromise, etc.).
  Stylistic nits and "could be misused" speculation don't count.
- You may read other modules' `src/main` to chase data flows. Consult tests to
  tell "bug" from "documented contract". Bugs you raise must live in production
  code.
- Glue code that just moves typed objects around: a one-line "nothing
  security-relevant here" is fine.

## Ranking

- **Verified** — proved by a failing test you wrote at `<SHA>`. Test evidence
  mandatory.
- **Likely** — high confidence from reading; you couldn't construct a repro.
  State the blocker.
- **Speculative** — named input + named code path + named effect. Drop it if you
  can't name all three. No severity tag; doesn't change cleared status.

## Severity (Verified + Likely only)

**Critical > High > Medium > Low.** One sentence justifying the tag.

- **Critical** — unauth RCE, auth bypass on a default-on path, credential
  disclosure, persistent integrity compromise.
- **High** — unauth sensitive info disclosure, cheap unauth DoS, replay/forgery
  of signed material, internal SSRF.
- **Medium** — authed escalation within the same trust tier, costly DoS,
  non-sensitive internal info disclosure.
- **Low** — needs an already-compromised position, or impact bounded to the
  current request.

## Test evidence (Verified only)

New test files under `<MODULE_PATH>/src/test/**`:

- An **integration test** driven through a composed http4k handler
  (`routes(…).asServer(…)` against the in-memory client, or
  `Filter.then(handler)` invoked directly) — unless the bug is in a pure format
  / byte→byte crypto primitive / library helper with no `Request` / `Response`
  touchpoint, in which case a unit test alone suffices. Note that exception in
  the finding entry.
- A **unit test** isolating the bug to the smallest reasonable unit.

Both must:

- **Fail at `<SHA>`.** Run them and confirm. Unexpected pass → downgrade to
  Likely or drop. Never ship green "evidence".
- Be deterministic. Win races with a sync primitive, fixed seed, or injected
  clock — or downgrade.
- Use real http4k composition. No mocks of `org.http4k.*` types; prefer http4k's
  own fakes. External non-http4k types (clocks, FS, third-party SDKs) may be
  faked. No Approval tests — assert directly on status, headers, body,
  exceptions.
- Live in new files named `<Module>SecurityFindingsTest.kt` or
  `<Module><Topic>SecurityFindingsTest.kt`, where `<Module>` is the PascalCase
  form of the module name. Each test method carries
  `// SECURITY AUDIT: <finding-title>`, matching the title in
  `SECURITY-AUDIT.md` verbatim.
- **Not modify, extend, disable, skip, weaken, or rewrite any existing test.**
  New files only.

## Cross-module findings

If a data flow you're tracing ends in another module's `src/main`:

- Report it in *your* module's `SECURITY-AUDIT.md`, with the file:line and an
  explicit cross-module note.
- Write the tests in your module's `src/test`, composing the other module's
  types.
- If the required `testImplementation` would create a gradle cycle (your module
  is already a transitive dep of the target), don't work around it. Downgrade
  to Likely with the cycle as the blocker.

Duplicates with other agents' findings are expected — triage dedupes.

## Output: `<MODULE_PATH>/SECURITY-AUDIT.md`

Four sections; Verified and Likely each grouped internally by severity
(Critical → Low):

1. **Verified.** Title (matches the test comment); file:line (flag cross-module
   explicitly); 1–2 sentences on what's wrong; concrete exploit path; severity
   + one-line justification; paths to the integration + unit test (or
   "unit-test only — <reason>"); one-line fix shape.
2. **Likely.** Same shape minus test paths, plus a one-line blocker.
3. **Speculative.** Named input, named code path, hypothesised effect,
   best-guess file:line (mark `(suspected)` if unsure), one-line "to-promote".
4. **Trust-boundary paths cleared.** Short bullets — what you read carefully
   and judged sound, why it's fine.

## PR workflow

Audit first. Once you know what you've got:

1. `git checkout -b security-audit/<MODULE_NAME> <SHA>`, add
   `<MODULE_PATH>/SECURITY-AUDIT.md` and any test files, commit once
   (`security audit: <MODULE_NAME>`; body lists V / L / S counts),
   `git push origin security-audit/<MODULE_NAME>`.
2. **Draft PR** against `master`:
   - Title with findings:
     `[security audit] <MODULE_NAME> — N Verified / M Likely / K Speculative (max severity: <Critical|High|Medium|Low>)`.
   - Title when cleared: `[security audit] <MODULE_NAME> — cleared` (append
     ` (K Speculative)` if K > 0).
   - Body: 1–2 sentence summary, the pinned commit hash `<SHA>`, a GitHub blob
     link to the on-branch `SECURITY-AUDIT.md`, and a bullet list of test files
     added (or "none"). If `N > 0`, add
     `CI is expected to fail; the failing tests are the finding evidence.`
   - Draft state. No reviewers, labels, or assignees.

Any git/PR failure: stop and return via the contract with `status: "errored"`
and the verbatim error in `reason`.

## Hard rules

- No changes under any `src/main`, in any module. Tests + `SECURITY-AUDIT.md`
  only. Spot another bug while writing a test? Add it as another finding — don't
  fix it.
- New files live under your assigned module. Reads may cross modules.
- `testImplementation` deps in the module's build file are OK if a new test
  needs them. Use full coordinates if not in the version catalogue (don't edit
  the catalogue). Don't touch plugins, repositories, main-scope deps, settings,
  or anything under `gradle/`. Flag any build file change in the PR body.
- Never push to `master`. Never force-push. Never merge.
- Pin to `<SHA>`. No pull / rebase / merge from upstream.

## Out of scope

Transitive dependency CVEs (separate supply-chain pipeline). Anything in
`Insecure*` / `Unsafe*` / `*-testing` / `*-fake`. Performance, readability,
typing, API ergonomics, lint, style.

## Return contract

Your final message must be **only** a single fenced JSON block — no surrounding
prose, no preamble, no markdown outside the fence. Shape:

```json
{
  "module": "<MODULE_NAME>",
  "sha": "<SHA>",
  "status": "audited",
  "reason": null,
  "verified": 0,
  "likely": 0,
  "speculative": 0,
  "maxSeverity": null,
  "prUrl": "https://github.com/.../pull/123"
}
```

- `status`: `"audited"` | `"no-op"` | `"errored"`.
- `reason`: `null` for `"audited"`; one of `"bom-or-aggregator"`,
  `"testing-module"`, `"insecure-by-design"` for `"no-op"`; a one-line failure
  description for `"errored"`.
- `verified` / `likely` / `speculative`: integer counts. Zero unless
  `"audited"`.
- `maxSeverity`: `"Critical"` | `"High"` | `"Medium"` | `"Low"` if
  `verified + likely > 0`, else `null`.
- `prUrl`: the draft PR URL for `"audited"`; `null` for `"no-op"`; the URL if
  you got that far for `"errored"`, else `null`.

Anything outside the fence, or any deviation from the shape, causes your module
to be recorded as `errored`.

--- END PER-MODULE BRIEF ---
