diff --git a/docs/securityscan.md b/docs/securityscan.md index 3b7c865..9953bff 100644 --- a/docs/securityscan.md +++ b/docs/securityscan.md @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 | diff --git a/public/_headers b/public/_headers index 3450d74..fa77e4c 100644 --- a/public/_headers +++ b/public/_headers @@ -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' diff --git a/src/security-headers.test.ts b/src/security-headers.test.ts new file mode 100644 index 0000000..ebfa0fc --- /dev/null +++ b/src/security-headers.test.ts @@ -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 { + const lines = readFileSync(headersPath, 'utf8').split('\n'); + const headers = new Map(); + 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=()'); + }); +}); diff --git a/worker/README.md b/worker/README.md index c847e1f..2588693 100644 --- a/worker/README.md +++ b/worker/README.md @@ -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). diff --git a/worker/src/github-release-webhook.test.ts b/worker/src/github-release-webhook.test.ts index 83685ba..de62a5f 100644 --- a/worker/src/github-release-webhook.test.ts +++ b/worker/src/github-release-webhook.test.ts @@ -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, @@ -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() }; @@ -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({ diff --git a/worker/src/github-release-webhook.ts b/worker/src/github-release-webhook.ts index 4d929d8..91762ec 100644 --- a/worker/src/github-release-webhook.ts +++ b/worker/src/github-release-webhook.ts @@ -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, @@ -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({ @@ -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 @@ -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' }); } } diff --git a/worker/src/github-webhook-body-binding.test.ts b/worker/src/github-webhook-body-binding.test.ts new file mode 100644 index 0000000..b501f27 --- /dev/null +++ b/worker/src/github-webhook-body-binding.test.ts @@ -0,0 +1,111 @@ +import { createMemoryStore } from '@pegma/storage-core'; +import { describe, expect, it } from 'vitest'; +import { + bindSignedWebhookBody, + hashSignedWebhookBody, +} from './github-webhook-body-binding'; + +const FIRST_DELIVERY = '11111111-1111-4111-8111-111111111111'; +const SECOND_DELIVERY = '22222222-2222-4222-8222-222222222222'; +const AT = '2026-07-28T18:00:00.000Z'; + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text); +} + +describe('hashSignedWebhookBody', () => { + it('is the SHA-256 hex of the exact bytes', async () => { + // Published SHA-256 of the empty input and of "abc". + expect(await hashSignedWebhookBody(new Uint8Array())).toBe( + 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', + ); + expect(await hashSignedWebhookBody(bytes('abc'))).toBe( + 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad', + ); + }); + + it('separates bodies that differ by one byte', async () => { + expect(await hashSignedWebhookBody(bytes('{"a":1}'))).not.toBe( + await hashSignedWebhookBody(bytes('{"a":2}')), + ); + }); +}); + +describe('bindSignedWebhookBody', () => { + it('binds a body once and reports a replay under another delivery id', async () => { + const store = createMemoryStore(); + const bodyHash = await hashSignedWebhookBody(bytes('{"action":"published"}')); + + expect( + await bindSignedWebhookBody(store, { + bodyHash, + deliveryId: FIRST_DELIVERY, + firstSeenAt: AT, + }), + ).toEqual({ status: 'bound' }); + + // Same delivery id: a retry of the same event, not a replay. + expect( + await bindSignedWebhookBody(store, { + bodyHash, + deliveryId: FIRST_DELIVERY, + firstSeenAt: '2026-07-28T19:00:00.000Z', + }), + ).toEqual({ status: 'bound' }); + + expect( + await bindSignedWebhookBody(store, { + bodyHash, + deliveryId: SECOND_DELIVERY, + firstSeenAt: AT, + }), + ).toEqual({ status: 'replayed', boundDeliveryId: FIRST_DELIVERY }); + }); + + it('binds different bodies independently', async () => { + const store = createMemoryStore(); + await bindSignedWebhookBody(store, { + bodyHash: await hashSignedWebhookBody(bytes('first')), + deliveryId: FIRST_DELIVERY, + firstSeenAt: AT, + }); + + expect( + await bindSignedWebhookBody(store, { + bodyHash: await hashSignedWebhookBody(bytes('second')), + deliveryId: SECOND_DELIVERY, + firstSeenAt: AT, + }), + ).toEqual({ status: 'bound' }); + }); + + it('keeps the first delivery id, so a claim never transfers', async () => { + const store = createMemoryStore(); + const bodyHash = await hashSignedWebhookBody(bytes('{"action":"edited"}')); + await bindSignedWebhookBody(store, { + bodyHash, + deliveryId: FIRST_DELIVERY, + firstSeenAt: AT, + }); + + // Repeated replay attempts keep naming the original owner rather than + // rewriting the record to the most recent caller. + for (const attempt of [1, 2, 3]) { + expect( + await bindSignedWebhookBody(store, { + bodyHash, + deliveryId: SECOND_DELIVERY, + firstSeenAt: `2026-07-28T2${attempt}:00:00.000Z`, + }), + ).toEqual({ status: 'replayed', boundDeliveryId: FIRST_DELIVERY }); + } + + expect( + await bindSignedWebhookBody(store, { + bodyHash, + deliveryId: FIRST_DELIVERY, + firstSeenAt: AT, + }), + ).toEqual({ status: 'bound' }); + }); +}); diff --git a/worker/src/github-webhook-body-binding.ts b/worker/src/github-webhook-body-binding.ts new file mode 100644 index 0000000..bcde1e7 --- /dev/null +++ b/worker/src/github-webhook-body-binding.ts @@ -0,0 +1,97 @@ +import { + defineCollection, + type EntityKey, + type Store, + type StoredRecord, +} from '@pegma/storage-core'; + +const BODY_BINDING_PARTITION = 'github-webhook-body'; + +/** One signed webhook body bound to the delivery id that first carried it. */ +export interface WebhookBodyBinding { + /** SHA-256 hex of the exact bytes `X-Hub-Signature-256` covered. */ + readonly bodyHash: string; + readonly deliveryId: string; + readonly firstSeenAt: string; +} + +/** + * Outcome of claiming a signed body. + * + * `bound` means this delivery owns the body — either it is new or the same + * delivery is being retried. `replayed` means the identical signed bytes were + * already claimed by a different delivery id. + */ +export type WebhookBodyBindingResult = + | { readonly status: 'bound' } + | { readonly status: 'replayed'; readonly boundDeliveryId: string }; + +export function webhookBodyBindingKey(bodyHash: string): EntityKey { + return { partition: BODY_BINDING_PARTITION, id: bodyHash }; +} + +function encode(value: WebhookBodyBinding): StoredRecord { + return { + bodyHash: value.bodyHash, + deliveryId: value.deliveryId, + firstSeenAt: value.firstSeenAt, + }; +} + +function decode(record: StoredRecord): WebhookBodyBinding { + return { + bodyHash: typeof record['bodyHash'] === 'string' ? record['bodyHash'] : '', + deliveryId: + typeof record['deliveryId'] === 'string' ? record['deliveryId'] : '', + firstSeenAt: + typeof record['firstSeenAt'] === 'string' ? record['firstSeenAt'] : '', + }; +} + +export function webhookBodyBindingCollection() { + return defineCollection({ + name: 'githubWebhookBodyBinding', + key: (value) => webhookBodyBindingKey(value.bodyHash), + codec: { encode, decode }, + }); +} + +/** SHA-256 hex of the exact bytes the signature covered. */ +export async function hashSignedWebhookBody( + body: Uint8Array, +): Promise { + const digest = new Uint8Array( + await crypto.subtle.digest('SHA-256', body as BufferSource), + ); + return [...digest].map((byte) => byte.toString(16).padStart(2, '0')).join(''); +} + +/** + * Claim one signed body for `deliveryId`, reporting a replay under another id. + * + * GitHub's HMAC covers the body only, so `X-GitHub-Delivery` — the + * `@pegma/webhooks` ledger dedup key — is unauthenticated input: anyone holding + * a previously valid signed body could re-present it under a fresh delivery id + * and slip past dedup. Binding the signed bytes to the first delivery id that + * carried them moves dedup onto data the signature actually covers. The claim + * is an `insertIfAbsent`, so concurrent deliveries cannot both win it. + * + * A claim is permanent, including after a failed attempt: GitHub keeps one + * delivery id per event across redeliveries, so a retry re-binds and proceeds, + * while expiring a claim would be granting permission to replay that body + * later. Growth is one small row per distinct signed body — bounded by the + * release cadence of the allowlisted repositories, the same rate at which the + * `@pegma/webhooks` receipt beside it accrues. + */ +export async function bindSignedWebhookBody( + store: Store, + binding: WebhookBodyBinding, +): Promise { + const result = await store + .collection(webhookBodyBindingCollection()) + .insertIfAbsent(binding); + if (result.inserted || result.value.deliveryId === binding.deliveryId) { + return { status: 'bound' }; + } + return { status: 'replayed', boundDeliveryId: result.value.deliveryId }; +}