# Prove it: tests and local replay for security fixes

Part of Preflight v2 - protocol: https://zirkomirko.com/tools/preflight/agent.md

A fix you have not attacked is a guess. This file shows how to turn each finding into a test that attempts the attack, fails before the fix and passes after it. Hard rule 4 in `agent.md` applies to everything here: local machine only, test data only, one explainable request at a time.

## The standard: red, then green

1. Write the test first. It performs the attack and asserts the safe outcome (`401`, `403`, `404`, `400`, "balance unchanged", "nothing written").
2. Run it on the unfixed code. It must fail. Save the failure line as your "before".
3. Apply the fix. Run it again. It must pass. Save that line as your "after".
4. Run the whole suite. Nothing else may have broken.

If the test passes before the fix, either the test does not really attack, or the finding is wrong. Find out which before you continue.

Make the red reproducible: commit the tests on the fix branch **before** the first fix. Anyone can then check out that commit, run the suite and see the attacks succeed, and check out the tip and see them fail. Add a few "control" tests that show normal use still works (the owner can still read their own document, a correctly signed webhook is still applied): they pass before and after, and they catch a fix that simply breaks the feature.

Always assert the **effect**, not only the status code. "Returned 403" is weaker than "returned 403 and the row is unchanged". A handler that answers 403 after it already wrote to the database is still broken.

## Three levels, cheapest first

| Level | What it is | Use for | Needs |
|---|---|---|---|
| 1. Handler test | Import the route handler, server action or controller and call it with a crafted request. Outside services (database client, payment SDK, model SDK) are mocked or pointed at fakes. | Almost every authorization, validation, webhook, pricing and logic finding. | The project's test runner, or the language's built-in one |
| 2. Local replay | Start the app on `127.0.0.1` and send real HTTP requests. | Middleware, routing, headers, cookies, CORS, rate limits, anything the framework does before your handler. | Tier B consent and a safe local backend |
| 3. Policy test | SQL or rules tests run against a local database or emulator. | Supabase or Postgres row-level security, Firebase rules. | Local Supabase, a throwaway Postgres, or the Firebase emulator |

Prefer level 1 for the regression suite (fast, no network, runs in CI). Use level 2 for the before-and-after evidence in the report, and keep the replay script so the user can run it again.

If the project ships its own mocks or fakes for outside services, reuse them: start them from the test runner's global setup on a spare port, point the handlers' environment at that port in a setup file, and reset their state between tests. Stub the framework pieces a handler needs outside a real request (`next/headers`, `next/cache`) in the same setup file.

Things you cannot run here (a cloud setting, a CI workflow, Terraform, a mobile build) still deserve a tripwire: a small test that reads the file and fails if the dangerous value returns (`pull_request_target` with a checkout of PR code, `acl = "public-read"`, a `NEXT_PUBLIC_` name on a secret). It does not prove the live system is safe, so the finding stays `FIXED, NOT PROVEN HERE`, but it stops the same mistake from coming back unnoticed.

## Where tests go and what they are called

- Follow the project: its test folder, runner, file naming and helpers. Otherwise `tests/security/<area>.test.<ext>`.
- One `test()` per finding, named `PF-07 user B cannot read user A's invoice`.
- No secrets in tests. Use obvious fakes (`sk_test_fake`, `whsec_test_fake`). Read real names from `.env.example`, never real values.
- Tests must not need production, the network or a paid API.
- If there is no runner: `node --test` (Node 18+), `python -m unittest`, `go test`, `cargo test`, `php artisan test`, `bin/rails test`. Ask before adding a dependency.

## Recipes

### Unauthenticated or wrong-user request (Next.js route handler, level 1)

```ts
// tests/security/documents.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { GET } from '../../app/api/documents/[id]/route';

test('PF-07 user B cannot read user A\'s document', async () => {
  const req = new Request('http://localhost/api/documents/doc_of_A', {
    headers: { authorization: 'Bearer token-of-user-B' },   // test token your mock understands
  });
  const res = await GET(req, { params: Promise.resolve({ id: 'doc_of_A' }) });
  assert.ok([403, 404].includes(res.status));
  assert.equal((await res.text()).includes('secret title of A'), false);
});
```

Cover the set, not one case: no session, a valid session of the wrong user, the wrong tenant, the right user with the wrong role. For admin routes add "normal user gets 403".

### Express, Fastify (level 1 with an injected request)

```js
import request from 'supertest';          // only if the project already has it
import { app } from '../../src/app.js';   // export the app without calling listen()

test('PF-02 admin list needs an admin session', async () => {
  await request(app).get('/api/admin/users').expect(401);
  await request(app).get('/api/admin/users').set('Cookie', userCookie).expect(403);
});
```

Fastify has `app.inject({ method, url, headers, payload })` built in. FastAPI: `TestClient(app)`. Django: `self.client`. Rails: request specs. Laravel: `$this->actingAs($userB)->get(...)->assertForbidden()`.

### Forged, tampered and replayed webhook

```ts
import Stripe from 'stripe';
const stripe = new Stripe('sk_test_fake');
const secret = 'whsec_test_fake';          // set the handler's env to this in the test
const payload = JSON.stringify({ id: 'evt_test_1', type: 'checkout.session.completed',
  data: { object: { client_reference_id: 'user_1', payment_status: 'paid' } } });

test('PF-03 webhook without a valid signature is rejected and writes nothing', async () => {
  const res = await POST(new Request(url, { method: 'POST', body: payload,
    headers: { 'stripe-signature': 't=1,v1=deadbeef' } }));
  assert.equal(res.status, 400);
  assert.equal(db.writes.length, 0);
});

test('PF-04 the same event delivered twice is applied once', async () => {
  const header = stripe.webhooks.generateTestHeaderString({ payload, secret });
  const send = () => POST(new Request(url, { method: 'POST', body: payload,
    headers: { 'stripe-signature': header } }));
  await send(); await send();
  assert.equal(creditsOf('user_1'), 100);   // not 200
});
```

Other providers: compute the HMAC yourself in the test with the fake secret (`crypto.createHmac('sha256', secret).update(rawBody).digest('hex')`). Always add the three cases: no signature, wrong signature, valid signature sent twice. Add "old timestamp" where the provider signs one.

### Tampered price, quantity or amount

Call the checkout handler with `{ priceId: 'price_of_cheaper_plan' }`, `{ amount: 1 }`, `{ quantity: -5 }`, `{ quantity: 1e9 }`. Assert `400`, and assert the mocked payment SDK was **not called**, or was called only with a price from the server's own table.

### Mass assignment

Send the normal update plus forbidden fields: `{ name: 'x', role: 'admin', plan: 'pro', credits: 99999, user_id: 'someone-else' }`. Assert the write the mock received contains only allowed keys.

### Race and double spend (bounded)

```ts
test('PF-12 ten simultaneous spends of the last credit succeed once', async () => {
  setCredits('user_1', 1);
  const results = await Promise.all(Array.from({ length: 10 }, () => spend('user_1')));
  assert.equal(results.filter(r => r.status === 200).length, 1);
  assert.equal(creditsOf('user_1'), 0);     // never negative
});
```

At most 20 parallel calls. This needs a fake that behaves like the real store: an atomic conditional update must be atomic in the fake too. If the real guarantee lives in the database (a `where credits >= 1` update, a unique index), say so and add a level 3 test, or mark the proof `NOT RUN HERE`.

### Server-side request forgery

Unit-test the URL guard with a table of inputs. Nothing is fetched:

```ts
for (const bad of ['http://127.0.0.1/', 'http://localhost:3000/', 'http://169.254.169.254/latest/meta-data/',
  'http://[::1]/', 'http://2130706433/', 'http://0x7f.1/', 'http://10.0.0.5/', 'http://192.168.1.1/',
  'http://metadata.google.internal/', 'file:///etc/passwd', 'gopher://x/', 'http://user@127.0.0.1/'])
  await assert.rejects(() => assertPublicUrl(bad));
```

Add one case for redirects (a public URL that redirects to a private one, using a mocked fetch). For the local replay, start a listener on `127.0.0.1:<free port>`, ask the app to fetch it, and show the listener was hit before the fix and not after.

### Path traversal, command, template and deserialization injection

Test the function, not the shell. Extract the path or argument building into a small function if needed, then assert that `../../etc/passwd`, `..\\..\\x`, `/abs/path`, `a;b`, `$(x)`, `` `x` `` and `--flag` inputs are rejected or stay inside the base folder. Never execute an injected command.

### Cross-site scripting

Render the component or call the sanitizer with `<img src=x onerror=alert(1)>`, `<script>`, `<a href="javascript:alert(1)">` and an SVG with `onload`. Assert the output contains no `onerror`, no `<script`, no `javascript:`. For redirects, assert `?next=https://evil.example`, `//evil.example` and `/\evil.example` all resolve to a same-site path.

### Rate limits (bounded)

Call the handler `limit + 1` times with the same key and assert the last one is `429`. Then prove the key cannot be dodged: change the `X-Forwarded-For` header and assert it is still limited when the platform would not have set that header.

### LLM features

Mock the model. Three useful tests: (1) the endpoint refuses anonymous callers and over-quota users without calling the model; (2) client-supplied `model`, `system` role messages and `max_tokens` are ignored or rejected; (3) a tool call the fake model "decides" to make with another user's id is refused by the tool's own check. For indirect injection, feed a document containing an instruction and assert that no outbound or destructive tool runs without the confirmation step.

### Supabase and Postgres row-level security (level 3)

Run inside a transaction and roll back. `<A>` and `<B>` are test user ids.

```sql
begin;
set local role authenticated;
set local request.jwt.claims = '{"sub":"<B>","role":"authenticated"}';

-- B must not see A's rows
select count(*) = 0 as pass from documents where owner_id = '<A>';
-- B must not upgrade their own plan
update profiles set plan = 'pro' where id = '<B>';
select plan <> 'pro' as pass from profiles where id = '<B>';
-- B must not join A's team
insert into team_members (team_id, user_id, role) values ('<team of A>', '<B>', 'owner');  -- must error

rollback;
```

Repeat with `set local role anon;` and empty claims. With the Supabase CLI: put pgTAP tests in `supabase/tests/` and run `supabase test db` against the local stack (`supabase start`). No local database: deliver the SQL, mark it `NOT RUN HERE`, and give the user the steps to run it in a development project, never in production.

### Firebase rules (level 3)

`@firebase/rules-unit-testing` with the emulator: `assertFails(getDoc(otherUsersDoc))`, `assertFails(updateDoc(myDoc, { role: 'admin' }))`, `assertSucceeds(getDoc(myDoc))`.

## Local replay script

Keep the replay small and readable so the user can run it again before a deploy. Suggested file: `tests/security/replay.local.mjs`.

```js
// Usage: node tests/security/replay.local.mjs http://127.0.0.1:3000
const base = process.argv[2] ?? 'http://127.0.0.1:3000';
if (!/^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(base)) throw new Error('local only');

const cases = [
  { id: 'PF-01', name: 'admin user list without login',
    run: () => fetch(`${base}/api/admin/users`), safe: r => r.status === 401 || r.status === 403 },
  { id: 'PF-03', name: 'webhook without signature',
    run: () => fetch(`${base}/api/webhooks/stripe`, { method: 'POST', body: '{}' }), safe: r => r.status === 400 },
];
let open = 0;
for (const c of cases) {
  const r = await c.run();
  const ok = c.safe(r);
  if (!ok) open++;
  console.log(`${ok ? 'BLOCKED' : 'OPEN   '}  ${c.id}  ${c.name}  -> ${r.status}`);
}
process.exit(open ? 1 : 0);
```

The script refuses any base URL that is not local. Keep that line.

Before you start the app: read the names in the local env file and the hosts they point to. Production database, `sk_live` payment key, real mail or SMS provider: do not replay; use level 1 instead and say why.

## What to write in the report

For each finding: the attack attempted, the result before, the result after, and the test name. If you could not get a red, say so. If a proof is `NOT RUN HERE`, say what the user needs to run and what a pass looks like.
