Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions docs/securityscan.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,14 @@ fail-closed on any unexpected migration change (see CI).
includeSubDomains; preload` to the `/*` block in `public/_headers`, and
enable HSTS zone-wide in the Cloudflare dashboard (SSL/TLS → Edge
Certificates) so it also covers API responses from the Worker.
- **Disposition:** ✅ Resolved 2026-07-29 — added the recommended
`Strict-Transport-Security` header to the `/*` block in `public/_headers`,
with `src/security-headers.test.ts` asserting the whole static header set so
a regression fails CI. `includeSubDomains` is safe today: `www.pegma.dev`
already serves HTTPS and 301s to the apex. Two operator actions remain
outside this repository: enabling HSTS zone-wide so Worker `/api/*`
responses carry it, and submitting the apex to hstspreload.org (the
`preload` token alone does nothing until then).

### [LOW] `Access-Control-Allow-Origin: *` on static HTML responses

Expand All @@ -172,6 +180,16 @@ fail-closed on any unexpected migration change (see CI).
- **Fix:** optional; if desired, strip the header for HTML responses via a
Pages `_headers` override or serve static assets through the Worker and
control headers explicitly.
- **Disposition:** ⚠️ Disputed 2026-07-29 — not a valid finding: the header
grants cross-origin script read access to bytes that are already served to
anonymous clients and published from a public repository, so it discloses
nothing. Nothing on the Pages origin is credentialed, and without
`Access-Control-Allow-Credentials: true` a browser will not attach the
`__Host-` session cookie to a cross-origin read regardless of ACAO. The
credentialed surface is `/api/*` on the Worker, which returns no ACAO
(asserted in `releases-api.test.ts:177`). The finding's own exploitability
note and "optional" fix agree there is no impact; changing the header would
add a Pages override with no security effect.

### [LOW] Public health endpoint discloses versions and ops timing

Expand All @@ -191,6 +209,25 @@ fail-closed on any unexpected migration change (see CI).
behind the staff allowlist, or strip versions/timestamps from the public
body. If public detail is deliberate for the reference environment,
document that in the endpoint contract.
- **Disposition:** ⚠️ Disputed 2026-07-29 — not a valid finding: nothing in
the body is confidential in this repository. The version strings are
hardcoded literals in `worker/src/index.ts` in a **public** repo whose
`package.json` pins the same versions (`@pegma/identity` 0.1.0,
`@pegma/authorization-identity` 0.1.2, `@pegma/sessions` 0.1.0), so the
endpoint reveals nothing an attacker cannot read from the source — and,
being literals, it is not even evidence of what is deployed. The site
publishes those versions on purpose: `GET /api/releases` and the Stack page
are a deliberate public feed of every `@pegma/*` release. The ops timing is
likewise already public — `/api/releases` returns the same reconciliation
instant as `observedAt` (both `2026-07-30T00:00:05.178Z` when probed), and
the 1-minute/6-hour cron cadence is in the public `worker/wrangler.jsonc`.
`datadog` and `emailDelivery` are configuration booleans with no secret
values, and `@pegma/health` defines check detail as "booleans and names,
never secrets". The finding's own alternative remedy — document the public
contract — is already met in `worker/README.md`, which specifies the
`githubReleases` detail fields and the "no secrets, delivery IDs, or
payloads" rule. Gating this endpoint behind sessions would also add D1 reads
to a liveness probe, making it fail for exactly the monitors it exists for.

### [LOW] Webhook replay: delivery ID unsigned, no body-hash binding

Expand All @@ -209,6 +246,18 @@ fail-closed on any unexpected migration change (see CI).
reject bodies seen under a different delivery ID. (GitHub signs no
timestamp, so a true freshness window is unavailable; reconciliation
already bounds worst-case drift.)
- **Disposition:** ✅ Resolved 2026-07-29 — dedup now keys on data the
signature covers: `worker/src/github-webhook-body-binding.ts` binds the
SHA-256 of the signed body to the first delivery id that carried it via
`insertIfAbsent`, and `handleGitHubReleaseWebhook` refuses the same bytes
under a different delivery id with `409 duplicate_body` before the ledger or
any projection runs. The claim is race-free rather than a read-then-write
check, and it is permanent: GitHub keeps one delivery id per event across
redeliveries, so a retry re-binds and runs while a different id stays
refused. Covered by
`worker/src/github-webhook-body-binding.test.ts` plus replay and
failed-delivery cases in `worker/src/github-release-webhook.test.ts`;
documented in `worker/README.md`.

## Phase 3 — Summary

Expand All @@ -219,6 +268,15 @@ fail-closed on any unexpected migration change (see CI).
| Medium | 0 |
| Low | 4 |

Dispositions recorded 2026-07-29, one per finding above:

| Finding | Disposition |
| --- | --- |
| Missing HSTS | ✅ Resolved — header added to `public/_headers` |
| ACAO `*` on static HTML | ⚠️ Disputed — public bytes, no credentialed origin |
| Health endpoint detail | ⚠️ Disputed — same facts already public by design |
| Webhook replay binding | ✅ Resolved — signed body bound to its delivery id |

| Layer | Status |
| --- | --- |
| Frontend (`src/`, `public/*.js`) | Clean — no DOM-XSS sinks, memory-only CSRF token, passkey auth, no web storage |
Expand Down
1 change: 1 addition & 0 deletions public/_headers
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/*
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Content-Security-Policy: default-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
Expand Down
69 changes: 69 additions & 0 deletions src/security-headers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';

const here = dirname(fileURLToPath(import.meta.url));
const headersPath = join(here, '../public/_headers');

/**
* Parse the Cloudflare Pages `_headers` rule for one path pattern.
*
* The file is indented `Name: value` lines under a path line, so a rule ends
* at the next unindented line. Names are lowercased; an unknown pattern gives
* an empty map, which the assertions below report as a missing header.
*/
function headersFor(pattern: string): Map<string, string> {
const lines = readFileSync(headersPath, 'utf8').split('\n');
const headers = new Map<string, string>();
const start = lines.findIndex((line) => line.trim() === pattern);
if (start < 0) {
return headers;
}

for (const line of lines.slice(start + 1)) {
if (line.trim() === '') {
continue;
}
if (!line.startsWith(' ')) {
break;
}
const separator = line.indexOf(':');
if (separator <= 0) {
continue;
}
headers.set(
line.slice(0, separator).trim().toLowerCase(),
line.slice(separator + 1).trim(),
);
}
return headers;
}

describe('public/_headers', () => {
it('declares HSTS with at least a one-year max-age', () => {
const hsts = headersFor('/*').get('strict-transport-security');
expect(hsts).toBeDefined();

const maxAge = /(?:^|;)\s*max-age=(\d+)\s*(?:;|$)/.exec(hsts ?? '');
expect(maxAge, `no max-age in "${hsts}"`).not.toBeNull();
expect(Number(maxAge?.[1])).toBeGreaterThanOrEqual(31_536_000);
expect(hsts).toContain('includeSubDomains');
});

it('keeps the rest of the static security header set', () => {
const headers = headersFor('/*');
expect(headers.get('x-content-type-options')).toBe('nosniff');
expect(headers.get('referrer-policy')).toBe(
'strict-origin-when-cross-origin',
);
expect(headers.get('cross-origin-opener-policy')).toBe('same-origin');
expect(headers.get('content-security-policy')).toContain(
"script-src 'self'",
);
expect(headers.get('content-security-policy')).toContain(
"frame-ancestors 'none'",
);
expect(headers.get('permissions-policy')).toContain('geolocation=()');
});
});
8 changes: 8 additions & 0 deletions worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,14 @@ webhook delivery UI/API to redeliver; the ledger acknowledges duplicates
without re-applying a processed projection. Missed or deleted events converge
via six-hour reconciliation without operator D1 edits.

**Replay:** GitHub's HMAC covers the body only, so `x-github-delivery` — the
ledger's dedup key — is unauthenticated. Each signed body is therefore bound to
the first delivery id that carried it; the same bytes presented under a
different delivery id are refused with `409 duplicate_body` and have no storage
effect. The binding survives a failed attempt, because GitHub keeps one
delivery id per event across redeliveries: the retry re-binds and runs, while
expiring the claim would be permission to replay that body later.

**Rollback:** disable the organization webhook first. Keep `GET /api/releases`
serving last-known public records while investigating unless integrity is in
doubt — then disable release rendering (Stack still shows repository links).
Expand Down
95 changes: 95 additions & 0 deletions worker/src/github-release-webhook.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createMemoryStore } from '@pegma/storage-core';
import type { Logger } from '@pegma/spine';
import type { WebhookLedger } from '@pegma/webhooks';
import { describe, expect, it, vi } from 'vitest';
import {
componentReleaseCollection,
Expand All @@ -16,6 +17,7 @@ const SECRET = "It's a Secret to Everybody";
const ORG_ID = '309286193';
const REPO_ID = '1313911960';
const DELIVERY = '11111111-1111-4111-8111-111111111111';
const OTHER_DELIVERY = '33333333-3333-4333-8333-333333333333';
const NOW = '2026-07-28T18:00:00.000Z';

const logger: Logger = { log: vi.fn() };
Expand Down Expand Up @@ -261,6 +263,99 @@ describe('handleGitHubReleaseWebhook', () => {
});
});

it('rejects a signed body replayed under a fresh delivery id', async () => {
const store = createMemoryStore();
const releases = store.collection(componentReleaseCollection());
const payload = releasePayload();

const first = await handleGitHubReleaseWebhook({
request: await signedRequest(payload),
store,
logger,
config,
now: NOW,
});
expect(first.status).toBe(204);

const replay = await handleGitHubReleaseWebhook({
request: await signedRequest(payload, {
'X-GitHub-Delivery': OTHER_DELIVERY,
}),
store,
logger,
config,
now: NOW,
});
expect(replay.status).toBe(409);
expect(await replay.json()).toEqual({ error: 'duplicate_body' });

// The real delivery may still be redelivered under its own id.
const redelivery = await handleGitHubReleaseWebhook({
request: await signedRequest(payload),
store,
logger,
config,
now: NOW,
});
expect(redelivery.status).toBe(204);
expect(await releases.get(componentReleaseKey(REPO_ID))).toMatchObject({
tagName: 'v0.1.0',
releaseId: '100',
});
});

it('keeps the body claim through a failed attempt and still allows redelivery', async () => {
const store = createMemoryStore();
const releases = store.collection(componentReleaseCollection());
const payload = releasePayload();
const brokenLedger: WebhookLedger = {
begin: async () => {
throw new Error('ledger unavailable');
},
markProcessed: async () => {},
markFailed: async () => ({ attempts: 1, quarantined: false }),
purgeExpired: async () => 0,
};

const failed = await handleGitHubReleaseWebhook({
request: await signedRequest(payload),
store,
logger,
config,
now: NOW,
ledger: brokenLedger,
});
expect(failed.status).toBe(500);
expect(await releases.get(componentReleaseKey(REPO_ID))).toBeNull();

// A failed attempt is not a licence to replay: another delivery id still
// cannot claim those bytes.
const replay = await handleGitHubReleaseWebhook({
request: await signedRequest(payload, {
'X-GitHub-Delivery': OTHER_DELIVERY,
}),
store,
logger,
config,
now: NOW,
});
expect(replay.status).toBe(409);
expect(await releases.get(componentReleaseKey(REPO_ID))).toBeNull();

// GitHub keeps one delivery id per event, so the redelivery still runs.
const redelivery = await handleGitHubReleaseWebhook({
request: await signedRequest(payload),
store,
logger,
config,
now: NOW,
});
expect(redelivery.status).toBe(204);
expect(await releases.get(componentReleaseKey(REPO_ID))).toMatchObject({
tagName: 'v0.1.0',
});
});

it('records draft deliveries without projecting them', async () => {
const store = createMemoryStore();
const response = await handleGitHubReleaseWebhook({
Expand Down
28 changes: 27 additions & 1 deletion worker/src/github-release-webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import { createWebhookLedger, type WebhookLedger } from '@pegma/webhooks';
import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1';
import type { Store } from '@pegma/storage-core';
import type { Logger } from '@pegma/spine';
import {
bindSignedWebhookBody,
hashSignedWebhookBody,
} from './github-webhook-body-binding';
import { verifyGitHubWebhookSignature } from './github-webhook-signature';
import {
applyReleaseProjection,
Expand Down Expand Up @@ -322,6 +326,25 @@ export async function handleGitHubReleaseWebhook(
return jsonResponse(403, { error: 'repository_not_allowed' });
}

const observedAt = options.now ?? new Date().toISOString();

// The HMAC covers the body only, so `x-github-delivery` — the ledger's dedup
// key — is unauthenticated. Bind the signed bytes to the first delivery id
// that carried them so a captured body cannot be replayed under a fresh id.
const bodyHash = await hashSignedWebhookBody(bounded.body);
const binding = await bindSignedWebhookBody(store, {
bodyHash,
deliveryId,
firstSeenAt: observedAt,
});
if (binding.status === 'replayed') {
logger.log('warn', 'github_release_webhook.body_replayed', {
deliveryId,
boundDeliveryId: binding.boundDeliveryId,
});
return jsonResponse(409, { error: 'duplicate_body' });
}

const ledger =
options.ledger ??
createWebhookLedger({
Expand All @@ -340,7 +363,6 @@ export async function handleGitHubReleaseWebhook(
return emptyResponse(204);
}

const observedAt = options.now ?? new Date().toISOString();
const decision = decideReleaseProjection(facts, observedAt);
await applyReleaseProjection(store, decision);
// ETag invalidation is correctness-critical (not best-effort): a later
Expand Down Expand Up @@ -383,6 +405,10 @@ export async function handleGitHubReleaseWebhook(
markFailedError instanceof Error ? markFailedError.name : 'unknown',
});
}
// The body binding deliberately survives a failed attempt. GitHub keeps
// one delivery id per event across redeliveries, so the retry still binds;
// dropping the claim here would only let a different delivery id take it,
// which is the replay the binding exists to refuse.
return jsonResponse(500, { error: 'processing_failed' });
}
}
Loading
Loading