Skip to content

feat(data-sharing): webhook-endpoints Edge Function with SSRF guard and signing (2/4) - #547

Merged
9thLevelSoftware merged 10 commits into
mainfrom
feat/webhook-endpoints-function
Nov 6, 2026
Merged

9thLevelSoftware merged 10 commits into
mainfrom
feat/webhook-endpoints-function

Conversation

@9thLevelSoftware

Copy link
Copy Markdown
Owner

What

PR 2 of 4 for user-configurable data sharing (outbound webhooks, FLAME+). Stacked on #546; review only the top commit.

webhook-endpoints is the one write path for a user's endpoints: create, update, rotate_secret, test, resend_all, delete. This PR also adds the three shared modules every outbound delivery goes through.

Changes

  • _shared/webhookTarget.ts — the only code that may fetch a user-chosen URL. The repo had no SSRF protection before this because every other outbound fetch goes to a fixed provider host.
    • https only, no credentials in the URL, port 443 or 1024–65535.
    • Loopback, private, link-local (cloud metadata), CGNAT, ULA, multicast, reserved and every IPv4-embedding IPv6 form are refused, as literals and as resolved addresses. Single-label and internal names and this project's own hosts are refused too.
    • Every resolved address must be public, checked when the endpoint is saved and before every send. A resolver error fails closed.
    • Redirects are never followed, the request times out at 10 s, and the response body is never read.
  • _shared/webhookSigning.ts — Standard Webhooks headers. The HMAC key is the base64-decoded bytes after whsec_; the specification's reference vector is pinned in a test.
  • _shared/webhookSend.ts — one signed POST and a fixed outcome code. Shared by test here and by the worker in PR 3, so a test delivery is exactly a real one.
  • _shared/webhookCredentials.ts — the only reader of webhook_endpoint_secrets, scoped by endpoint id and owner.
  • webhook-endpoints — verify_jwt = true. Responses go through an explicit column allowlist.

Residual risk, stated rather than hidden

The runtime cannot pin a connection to the address it validated, so DNS rebinding can still aim a request at an internal address. It is bounded, not closed: the request is https with certificate validation, carries no Supabase credential, follows no redirect, keeps nothing of the response but its status code, and reports every failure before an HTTP status as one code (connection_failed).

Axioms (docs/axioms.md)

How it holds Test that fails if it breaks
FP-1 The user id comes only from the verified JWT. Every read and write carries it, so another user's endpoint is a 404 for every action. "another user's endpoint is a 404 for every action and is left untouched". Confirmed to fail with the owner filter removed.
FP-2 requireSubscription(…, 'FLAME') on every action except delete and a pause-only update, which a lapsed user must always be able to do. A pause sent together with an edit is treated as an edit. EMBER create is 402 with nothing resolved or stored; lapsed user can pause and delete but not edit or resume. Confirmed to fail with the gate removed.
FP-5 The secret is generated server-side, stored as ciphertext, returned once by create and rotate_secret, and never logged. The outbound request carries no Supabase credential. assertNoSecretsLogged over create, rotate, test, pause, resume and delete; exact outbound header set asserted.
FP-8 Refusals carry a fixed code and a user-facing message. Switching an endpoint back on requires a passing test delivery. Resume with a failing receiver is 409 and the endpoint stays off.

Verification

  • 55 new Deno tests pass: signing 6, target 17, send 11, handler 21.
  • npm run check:edge-functions passes. npm run test:edge: 1152 passed, 2 failed, both in _shared/paddleFetch.test.ts on a Windows path; that file is not touched here and passes in CI on feat(data-sharing): schema, capture triggers and delivery queue for outbound webhooks (1/4) #546.
  • Smoke test against the local Edge runtime and real database, 25 of 25: tier gate, cross-user 404s, RLS on the secrets table, and URL refusals using the runtime's own resolver (including a public name that resolves to 127.0.0.1). No webhook was sent.
  • Deno.resolveDns was confirmed available in the local Edge runtime (edge-runtime 1.77.8). Not confirmed on the hosted runtime; if it is unavailable there, create fails closed with dns_failed.

CI

ci.yml only runs for PRs whose base is main, so this stacked PR does not get lint, typecheck, Vitest, Deno or E2E checks until its base changes. If #546 is squash-merged, rebase with git rebase --onto origin/main feat/webhook-data-sharing-schema feat/webhook-endpoints-function and retarget to main.

Operator

Nothing new. The Edge deploy gate already refuses to deploy until 20261106120000 (PR 1) is applied in prod. No new secret: OAUTH_TOKEN_ENCRYPTION_KEY also encrypts webhook secrets.

🤖 Generated with Claude Code

9thLevelSoftware and others added 3 commits November 6, 2026 12:07
…utbound webhooks

Database half of user-configurable data sharing (FLAME+): a user registers
HTTPS endpoints and the portal pushes their own data there as signed events.
Inert on its own: with no endpoint row every capture trigger returns at once
and the delivery cron job is created inactive.

- webhook_endpoints (owner SELECT, server-written), webhook_endpoint_secrets
  (service-only ciphertext) and webhook_deliveries (outbox + log). A composite
  FK ties every delivery to its endpoint's owner (FP-1).
- Statement-level capture triggers on every shared table, driven by
  private.webhook_entity_sources, so both LWW paths, the push transaction,
  portal writes and RPCs are covered by one mechanism. A capture error is a
  WARNING, never an aborted sync write (FP-3).
- Service-role RPCs: create/rotate/set-header, a FOR UPDATE SKIP LOCKED claim
  that pauses endpoints whose owner dropped below FLAME (FP-2), completion with
  backoff and auto-disable (FP-8), and a backfill.
- Not shared: raw telemetry, INFERNO-gated biomechanics, Strava-sourced
  activities, community rows, billing and sync bookkeeping. Every manifest
  table is classified in _shared/dataSharingScopes.ts and a test fails when a
  new one is not.
- Registered in the user-data manifest (secrets EXCLUDED), the RLS isolation
  suite and generated types; pgTAP floor raised.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…on race

- pgTAP: with the outbox made to reject the row, the user's write must still
  succeed (FP-3). Verified to fail when the trigger's exception handler is
  removed.
- complete_webhook_delivery: a pending row committed between the superseded
  check and the reschedule no longer surfaces as a unique violation; the
  attempt is closed as superseded.
- Raise PGTAP_TEST_FLOOR to the suite's actual count.
- Operator note on trigger lock contention.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…nd signing

The one write path for a user's outbound webhook endpoints (FLAME+):
create, update, rotate_secret, test, resend_all, delete.

- _shared/webhookTarget.ts: the only code that may fetch a user-chosen URL.
  https only, public addresses only (literal and every resolved address,
  checked on save and before each send, failing closed), own hosts refused,
  redirects never followed, response body never read. DNS rebinding is
  documented there as a residual risk and bounded, not claimed solved.
- _shared/webhookSigning.ts: Standard Webhooks headers; the HMAC key is the
  base64-decoded secret, pinned by the specification's reference vector.
- _shared/webhookSend.ts: one signed POST and a fixed outcome code. The request
  carries no Supabase credential (asserted) and nothing of the response but
  its status is kept.
- webhook-endpoints: user id from the verified JWT only; every query scoped by
  it, so another user's endpoint is a 404 for every action (FP-1). delete and a
  pause run before the FLAME gate so a lapsed user can always stop sharing
  (FP-2). The signing secret is returned once and never logged (FP-5).
  Requests to a user-chosen host have their own tight rate-limit key.
  Responses go through an explicit column allowlist.

Verified by mutation: removing the owner filter or the tier gate turns the
isolation tests red.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings November 6, 2026 17:51
@gitguardian

gitguardian Bot commented Nov 6, 2026

Copy link
Copy Markdown

⚠️ GitGuardian has uncovered 5 secrets following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

🔎 Detected hardcoded secrets in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
39754956 Triggered Stripe Webhook Secret 32ad07e supabase/functions/webhook-endpoints/index.test.ts View secret
39754956 Triggered Stripe Webhook Secret 32ad07e supabase/functions/_shared/webhookSigning.test.ts View secret
39754956 Triggered Stripe Webhook Secret 32ad07e supabase/functions/_shared/webhookSend.test.ts View secret
39754955 Triggered Generic High Entropy Secret 32ad07e supabase/functions/webhook-endpoints/index.test.ts View secret
39754955 Triggered Generic High Entropy Secret 32ad07e supabase/functions/_shared/webhookSend.test.ts View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secrets safely. Learn here the best practices.
  3. Revoke and rotate these secrets.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

GitGuardian flagged the whsec_ literals in the new test files as webhook
secrets. They were not credentials: one is the Standard Webhooks
specification's published example key, the other a second documentation
example used as a fixture. A scanner cannot tell that, and a scanner that
cries wolf gets ignored, so no secret-shaped literal is committed any more.

- Fixtures come from _shared/testing/webhookSecrets.ts (whsec_ + base64 of 32
  identical bytes, built at runtime).
- The reference vector is kept, because it is what proves interoperability;
  its public key is assembled from parts with a comment saying why.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
phoenix-portal 2d7e672 Commit Preview URL

Branch Preview URL
Nov 06 2026, 06:53 PM

9thLevelSoftware and others added 2 commits November 6, 2026 13:03
- The registry and the capture triggers could drift: a trigger's arguments
  are frozen when it is created. Trigger creation is now
  private.sync_webhook_capture_triggers(), which a later migration calls
  after editing private.webhook_entity_sources and which also removes capture
  triggers from tables that are no longer a source. pgTAP fails when a
  trigger's arguments differ from its row (verified by editing a row without
  rebuilding). The header no longer claims they cannot drift.
- The "does any active endpoint share this scope" probe ran on every write to
  a shared table with no index to use. Added a partial GIN index on scopes and
  switched the probe to @> so it can use it.
- sets and rep_summaries are payload children with no capture trigger. That is
  sound today (no browser role can write them, and every server writer
  rewrites exercises in the same call) but was neither stated nor tested. It
  is now documented, marked capturedThrough in dataSharingScopes.ts, checked
  in both directions by the parity test, and guarded by a pgTAP assertion on
  the grants.
- The profile omit list (stripe_customer_id and two internal columns) is now
  asserted, not only checked for existence.
- set_webhook_endpoint_header's two header arguments DEFAULT NULL, matching
  how they are used and the generated types.

Not changed: the pgTAP floor finding (the suite count is what the CI job
measured), and the endpoint-limit finding (endpoints are deleted through the
webhook-endpoints function in the next PR).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
header = { name: checked.name, value: checked.value };
}

if (body.url !== undefined) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: A new URL goes live on an active endpoint with no test delivery

patch.url is written straight to the row (L436), so from the next delivery every workout, personal record and profile event for this user goes to the new host - even though the resume path below (L454-463) deliberately refuses to switch an endpoint back on until a signed ping to that host succeeds. The one check that proves a receiver answers is skipped for the change that redirects the most data. Require the same signed ping before an active endpoint starts using a new URL, or state the policy explicitly in the header comment (L55-58).

if (header !== undefined) {
const valueEnc = header ? await deps.encrypt(header.value) : null;
if (header && !valueEnc) return unavailable(cors);
const { data: updated, error } = await admin.rpc('set_webhook_endpoint_header', {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: The custom header is committed before the rest of the update, so a failed patch leaves the request half applied

set_webhook_endpoint_header writes the header name and its encrypted value here, then the label/scopes/url/status patch runs at L436. If that second write fails the endpoint keeps the new header (and the new secret value) while the caller gets a 503 and reasonably believes nothing changed. Move the header RPC after the row update, or fold both writes into one RPC, so the update is all-or-nothing.

message: 'Switch the endpoint on before resending.',
}, 409, cors);
}
const { data: enqueued, error } = await admin.rpc('enqueue_webhook_backfill', {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: resend_all is limited by request count only, but each call enqueues one row per entity row with no cap

enqueue_webhook_backfill (migration 20261106120000_webhook_data_sharing.sql, L828-883) inserts one webhook_deliveries row for every matching source row with no LIMIT, and those rows are not charged against WEBHOOK_OUTBOUND_RATE_LIMIT. Two calls an hour per user can therefore flood the shared outbox - and the worker claim (100 rows per claim, 30 per endpoint) - with a backfill the user never sized. Cap the rows inserted per call and report the remainder, or charge resend_all against the outbound key as well.

return unavailable(cors);
}

const loaded = await loadEndpoint(admin, userId, endpointId as string);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: A failed read after create loses the signing secret for good

The secret is returned only here, so when this follow-up loadEndpoint fails the caller gets a 503 and never sees it: the endpoint stays, the user cannot sign for it, and a retry creates a second endpoint against the 3-endpoint cap. Build the response from the RPC result instead of a second read, or delete the just-created endpoint when the read fails.

Date.parse(row.previous_expires_at) > params.now.getTime();
if (previousLive) {
const previous = await decrypt(row.previous_signing_secret_enc!);
if (previous) secrets.push(previous);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: A malformed previous secret breaks every delivery, even though the current secret is fine

if (previous) secrets.push(previous) accepts any non-empty decrypted string. webhookSignatureHeaders then signs with each secret and secretKeyBytes throws webhook_secret_malformed - the throw escapes sendWebhook, because the signing call (webhookSend.ts:98) sits outside its try/catch - so one corrupt rotation-overlap secret takes down every delivery instead of falling back to the current secret. Validate each secret shape here (prefix + strict base64 + length) and drop the invalid one.

return this;
}
/** `delete().eq(...)`: removes the matching rows; `.select()` returns them. */
delete() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: The fake delete() ignores select(), so a real bug in handleDelete would pass the suite

select() only sets returning when insertRows is set (L185), and the delete branch at L315-317 returns the deleted rows unconditionally. If .select('id') is ever dropped from handleDelete (webhook-endpoints/index.ts:517), PostgREST answers 204 with data: null - the endpoint is deleted but the handler replies 404 - while this fake still returns the row and the test stays green. Set returning in select() when this.deleting, return null from the delete branch when it is false, and cover both shapes in a fake-level test.

}
});

Deno.test("webhook-endpoints: a lapsed user can still pause and delete, but not edit or resume", async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: The tier gate is only covered for create and update

FP-2 says every action except delete and a pause-only update needs FLAME, but the only 402 assertions here are for create (L261) and update (L414). Narrowing the gate to those two actions would leave rotate_secret, test and resend_all open to a lapsed user - test fires a request at a user-chosen host, resend_all enqueues a full backfill - with every test still green. Add a FREE-tier case asserting 402, no outbound request and no enqueue_webhook_backfill for those three actions.

assertEquals(db.rows("webhook_endpoints")[0].disabled_reason, "too_many_failures");
});

Deno.test("webhook-endpoints: resume needs a passing test delivery and clears the reason in the same write", async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: The fake models none of the table CHECK constraints, so clears the reason in the same write is not pinned

webhook_endpoints enforces (status = 'active') = (disabled_reason IS NULL) (migration L112-113), but the fake applies any patch, so a handler that wrote status: 'active' and disabled_reason: null as two statements - or that dropped disabled_reason - would pass this test and then fail in Postgres with a 23514, leaving the endpoint off. Assert the pairing in the fake update(), or add a pgTAP assertion for the CHECK.

const blocked = [
"127.0.0.1", "127.255.255.254", "10.0.0.1", "172.16.0.1", "172.31.255.255", "192.168.1.1",
"169.254.169.254", // cloud metadata
"100.64.0.1", "0.0.0.0", "192.0.2.1", "198.18.0.1", "198.51.100.1", "203.0.113.1",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Four reserved-range rules have no test case, so they can be deleted unnoticed

192.0.0.0/24 (webhookTarget.ts:108), 192.88.99.0/24 (L110), ORCHID 2001:10::/28 (L167) and 3fff::/20 (L169) are implemented but never exercised: neither the IPv4 blocked list (L64-67) nor the IPv6 one (L80-85) contains an address in them, and the CGNAT upper bound is only checked against 100.64.0.1. Add one address per range to the blocked lists plus the accepted neighbours, so every branch of isPublicIpv4/isPublicIpv6 is pinned.

assertEquals(db.rows("webhook_deliveries")[0].status, "dead");
});

Deno.test("webhook-endpoints: requests to a user-chosen host are rate limited on their own tight key", async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: The general and resend rate limits have no test

Only the tight outbound key is exercised (L560-575). WEBHOOK_ENDPOINTS_RATE_LIMIT (60 / 300 s) and WEBHOOK_RESEND_RATE_LIMIT (2 / 3600 s) have no assertion at all, so raising or removing either stays green - and the resend limit is the only thing between a user and repeated full backfills. Add a case that drives the general key past its budget and asserts a 429, and one that calls resend_all three times and asserts the third is 429 with no second enqueue_webhook_backfill.

@kilo-code-bot

kilo-code-bot Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Summary

Status: 11 Issues Found | Recommendation: Address before merge

Fix these issues in Kilo Cloud

Overview

Severity Count
CRITICAL 0
WARNING 4
SUGGESTION 7
Issue Details (click to expand)

WARNING

File Line Issue
supabase/functions/_shared/webhookCredentials.ts 58 A malformed secret still throws inside signWebhook and breaks every delivery - the new try/catch only covers a decrypt that throws
supabase/functions/webhook-endpoints/index.ts 411 A new URL goes live on an active endpoint with no test delivery, while the resume path demands one
supabase/functions/webhook-endpoints/index.ts 420 The custom header is committed before the row patch, so a failed patch leaves the update half applied
supabase/functions/webhook-endpoints/index.ts 646 resend_all is capped by request count only; one call enqueues one row per entity row with no limit

SUGGESTION

File Line Issue
supabase/functions/_shared/webhookTarget.ts 282 The resolveWebhookTarget doc comment now documents withDeadline instead
supabase/functions/webhook-endpoints/index.ts 339 A failed read after create loses the signing secret and orphans the endpoint
supabase/functions/_shared/webhookTarget.ts 77 .home is a delegated public gTLD and is wrongly refused
supabase/functions/_shared/webhookSigning.ts 50 atob is forgiving, so a corrupted secret silently becomes a different HMAC key
supabase/functions/webhook-endpoints/index.test.ts 457 The fake models no CHECK constraints, so the single-write resume claim is not pinned
supabase/functions/_shared/webhookTarget.test.ts 66 Four reserved-range rules (192.0.0/24, 192.88.99/24, ORCHID, 3fff::/20) have no test case
supabase/functions/webhook-endpoints/index.test.ts 582 The general and resend rate limits have no 429 test
Files Reviewed (8 files)
  • supabase/functions/_shared/testing/fakeSupabase.ts - 0 issues
  • supabase/functions/_shared/webhookCredentials.test.ts - 0 issues
  • supabase/functions/_shared/webhookCredentials.ts - 1 issue
  • supabase/functions/_shared/webhookSigning.ts - 1 issue
  • supabase/functions/_shared/webhookTarget.test.ts - 1 issue
  • supabase/functions/_shared/webhookTarget.ts - 2 issues
  • supabase/functions/webhook-endpoints/index.test.ts - 2 issues
  • supabase/functions/webhook-endpoints/index.ts - 4 issues

Verdict

Request changes - this pass closes the DNS-deadline, delete()/select(), missing-test-file and FLAME-gate gaps from the previous review, but the URL-change, half-applied-update and uncapped-resend_all behaviours are still undecided and a malformed stored secret still takes down every delivery.

Correctness / Safety Findings

important: supabase/functions/_shared/webhookCredentials.ts:58: a malformed secret still breaks every delivery. The new try/catch only covers a decrypt that throws, but decryptOAuthSecret returns the stored column verbatim when it does not start with enc:v1: (_shared/oauthTokenCrypto.ts:123), so a truncated, foreign-written or dev-plaintext row decrypts to any non-empty string. if (previous) secrets.push(previous) accepts it, secretKeyBytes (_shared/webhookSigning.ts:44) throws webhook_secret_malformed, and the throw is at _shared/webhookSend.ts:98 - outside sendWebhook's try/catch. Validate the shape of each secret (prefix + strict base64 + >= 24 bytes) and drop the invalid one, or catch the signing throw in sendWebhook so it becomes a connection_failed outcome. The current secret has the same exposure and needs the same check.

important: supabase/functions/webhook-endpoints/index.ts:411: patch.url is written straight to the row, so from the next delivery every event for this user goes to the new host, even though the resume path at L454-463 refuses to switch an endpoint on until a signed ping to that host succeeds. Require the same signed ping before an active endpoint starts using a new URL, or state the policy explicitly.

important: supabase/functions/webhook-endpoints/index.ts:420: set_webhook_endpoint_header writes the header name and its encrypted value, then the label/scopes/url/status patch runs at L436. If the second write fails the endpoint keeps the new header while the caller gets a 503 and reasonably believes nothing changed. Move the header RPC after the row update, or fold both writes into one RPC.

important: supabase/functions/webhook-endpoints/index.ts:646: enqueue_webhook_backfill inserts one webhook_deliveries row per matching source row with no LIMIT, and those rows are not charged against WEBHOOK_OUTBOUND_RATE_LIMIT. Two calls an hour can flood the shared outbox with a backfill the user never sized. Cap the rows inserted per call and report the remainder, or charge resend_all against the outbound key too.

minor: supabase/functions/_shared/webhookTarget.ts:282: inserting withDeadline between the doc block (L277-281) and resolveWebhookTarget (L290) leaves resolveWebhookTarget's contract attached to the helper and leaves the function itself undocumented.

minor: supabase/functions/webhook-endpoints/index.ts:339: when the follow-up loadEndpoint fails after create, the caller gets a 503 and never sees the signing secret - the endpoint stays, the user cannot sign for it, and a retry creates a second endpoint against the 3-endpoint cap. Build the response from the RPC result instead of a second read.

minor: supabase/functions/_shared/webhookTarget.ts:77: home is a live generic top-level domain, so https://mybox.home/hook is a public host that this list refuses. The internal-use name is home.arpa, blocked separately at L79. Drop home from the list.

minor: supabase/functions/_shared/webhookSigning.ts:50: atob strips ASCII whitespace and accepts unpadded input, so a secret with a stray space or one truncated by two characters decodes to a different key that still passes the >= 24 byte check at L54, and every signature then fails at the receiver with no local error. Validate the base64 part strictly before decoding.

minor: supabase/functions/webhook-endpoints/index.test.ts:457: webhook_endpoints enforces (status = 'active') = (disabled_reason IS NULL) (migration L112-113), but the fake applies any patch, so a handler that wrote status and disabled_reason as two statements would pass this test and then fail in Postgres with a 23514. Assert the pairing in the fake update().

minor: supabase/functions/_shared/webhookTarget.test.ts:66: 192.0.0.0/24 (webhookTarget.ts:110), 192.88.99.0/24 (L112), ORCHID 2001:10::/28 (L169) and 3fff::/20 (L171) are implemented but never exercised - neither the IPv4 nor the IPv6 blocked list contains an address in them. Add one address per range plus the accepted neighbours.

minor: supabase/functions/webhook-endpoints/index.test.ts:582: only the tight outbound key is exercised. WEBHOOK_ENDPOINTS_RATE_LIMIT (60 / 300 s) and WEBHOOK_RESEND_RATE_LIMIT (2 / 3600 s) have no assertion, so raising or removing either stays green - and the resend limit is the only thing between a user and repeated full backfills.

Ponytail Review

  • supabase/functions/_shared/webhookCredentials.test.ts:14: reuse: a second copy of the enc:test: encrypt/decrypt pair (webhook-endpoints/index.test.ts:22 writes the same one). Put the pair in _shared/testing/webhookSecrets.ts next to testWebhookSecret and import it in both files.
  • supabase/functions/_shared/webhookSigning.ts:20: reuse: a second private copy of bytesToBase64/base64ToBytes. _shared/oauthTokenCrypto.ts:37-51 already has both; export one pair from a shared module instead of copying it.
  • supabase/functions/_shared/webhookTarget.ts:282: shrink: withDeadline is a generic helper with one caller. Inline the race into resolveWebhookTarget and keep the deadline constant private to the module.
  • supabase/functions/_shared/webhookTarget.ts:34: delete: WEBHOOK_DNS_TIMEOUT_MS is exported but imported nowhere. Drop the export.
  • supabase/functions/_shared/webhookTarget.ts:273: shrink: ResolvedWebhookTarget duplicates ParsedWebhookTarget field for field. Return ParsedWebhookTarget from resolveWebhookTarget and delete the second union.
  • supabase/functions/_shared/webhookTarget.ts:100: delete: isPublicIpv4 and isPublicIpv6 are exported but have no caller in the repo. Drop the export on both.
  • supabase/functions/webhook-endpoints/index.ts:351: shrink: handlePause re-implements the pause handleUpdate already does at L431-434, and the two copies already disagree about where the "only from active" guard lives. Route the pause-only action through handleUpdate and move the .eq('status', 'active') guard into that update.
  • supabase/functions/webhook-endpoints/index.ts:66: reuse: another hand-rolled UUID regex (_shared/paddleWebhookUserId.ts:2, localProfileId.ts:17, pushPayloadSchema.ts:40, personalRecordRow.ts:395 already have four). Export one isUuid helper and use it.
  • supabase/functions/webhook-endpoints/index.ts:302: reuse: the custom-header parsing and its two error strings are written twice, in handleCreate and handleUpdate. Extract one parseCustomHeader(value).
  • supabase/functions/_shared/webhookSend.test.ts:81: test-shrink: the Deno.env.set/Deno.env.delete block proves nothing (sendWebhook never reads the environment) and delete does not restore a pre-existing value, unlike the repo's save-set-restore pattern. Delete the block, keep the exact header-key assertions.
  • supabase/functions/_shared/webhookTarget.test.ts:209: delete: assert(WEBHOOK_REQUEST_TIMEOUT_MS <= 10_000) compares a constant with itself and passes for any value.
  • supabase/functions/_shared/webhookSigning.test.ts:37: test-shrink: "a changed body, id or timestamp changes the signature" asserts a property of HMAC-SHA256, not of this code; the reference vector above already pins the signed content.

Ponytail net: -60 lines.

Suggested Minimal Patch

Three files, no new dependency. In _shared/webhookCredentials.ts, validate the shape of both secrets before pushing them and drop an invalid one (or catch the signing throw in _shared/webhookSend.ts so it becomes connection_failed). In webhook-endpoints/index.ts, move the set_webhook_endpoint_header RPC after the row update and cap or account for the rows resend_all enqueues. In _shared/webhookTarget.ts, move the resolveWebhookTarget doc comment back onto the function. The Ponytail items are optional cleanup and can follow in a separate commit.

Final Merge Guidance

The PR is already merged, so these are follow-up items rather than blockers. Fix the malformed-secret path before the delivery worker (PR 3) starts signing with rotated secrets, and decide the URL-change, half-applied-update and uncapped-resend_all policies; the remaining suggestions are optional cleanup.

Previous Review Summary (commit 69d403f)

Current summary above is authoritative. Previous snapshots are kept for context only.

Previous review (commit 69d403f)

Status: 14 Issues Found | Recommendation: Address before merge

Fix these issues in Kilo Cloud

Overview

Severity Count
CRITICAL 0
WARNING 6
SUGGESTION 8
Issue Details (click to expand)

WARNING

File Line Issue
supabase/functions/webhook-endpoints/index.ts 411 A new URL goes live on an active endpoint with no test delivery, while the resume path demands one
supabase/functions/webhook-endpoints/index.ts 420 The custom header is committed before the row patch, so a failed patch leaves the update half applied
supabase/functions/webhook-endpoints/index.ts 646 resend_all is capped by request count only; one call enqueues one row per entity row with no limit
supabase/functions/_shared/webhookCredentials.ts 54 An unvalidated previous secret throws inside signWebhook and breaks every delivery
supabase/functions/_shared/testing/fakeSupabase.ts 189 The fake delete() ignores select(), hiding a 404-after-delete bug in handleDelete
supabase/functions/webhook-endpoints/index.test.ts 379 The FLAME gate is untested for rotate_secret, test and resend_all

SUGGESTION

File Line Issue
supabase/functions/webhook-endpoints/index.ts 339 A failed read after create loses the signing secret and orphans the endpoint
supabase/functions/_shared/webhookCredentials.ts 23 No test file for this module: the rotation overlap is unverified
supabase/functions/_shared/webhookSigning.ts 50 atob is forgiving, so a corrupted secret silently becomes a different HMAC key
supabase/functions/_shared/webhookTarget.ts 75 .home is a delegated public gTLD and is wrongly refused
supabase/functions/_shared/webhookTarget.ts 291 DNS resolution has no deadline, so the 10 s budget does not cover the send
supabase/functions/webhook-endpoints/index.test.ts 435 The fake models no CHECK constraints, so the single-write resume claim is not pinned
supabase/functions/_shared/webhookTarget.test.ts 66 Four reserved-range rules (192.0.0/24, 192.88.99/24, ORCHID, 3fff::/20) have no test case
supabase/functions/webhook-endpoints/index.test.ts 560 The general and resend rate limits have no 429 test
Files Reviewed (14 files)
  • CLAUDE.md - 0 issues
  • supabase/config.toml - 0 issues
  • supabase/functions/_shared/requestBody.ts - 0 issues
  • supabase/functions/_shared/testing/fakeSupabase.ts - 1 issue
  • supabase/functions/_shared/testing/webhookSecrets.ts - 0 issues
  • supabase/functions/_shared/webhookCredentials.ts - 2 issues
  • supabase/functions/_shared/webhookSend.test.ts - 0 issues
  • supabase/functions/_shared/webhookSend.ts - 0 issues
  • supabase/functions/_shared/webhookSigning.test.ts - 0 issues
  • supabase/functions/_shared/webhookSigning.ts - 1 issue
  • supabase/functions/_shared/webhookTarget.test.ts - 1 issue
  • supabase/functions/_shared/webhookTarget.ts - 2 issues
  • supabase/functions/webhook-endpoints/index.test.ts - 3 issues
  • supabase/functions/webhook-endpoints/index.ts - 4 issues

Verdict

Request changes — the security design holds up (JWT-only ownership, a fail-closed SSRF guard, no secret in any log or response), but three behaviours need a decision before merge and one paid-capability test gap is open.

Ponytail Review

  • supabase/functions/_shared/webhookSigning.ts:20: reuse: a second private copy of bytesToBase64/base64ToBytes. _shared/oauthTokenCrypto.ts:37-51 already has both; export one pair from a shared module instead of copying it.
  • supabase/functions/_shared/webhookTarget.ts:271: shrink: ResolvedWebhookTarget duplicates ParsedWebhookTarget field for field. Return ParsedWebhookTarget from resolveWebhookTarget and delete the second union.
  • supabase/functions/_shared/webhookTarget.ts:98: delete: isPublicIpv4 and isPublicIpv6 are exported but have no caller in the repo. Drop the export on both.
  • supabase/functions/webhook-endpoints/index.ts:351: shrink: handlePause re-implements the pause handleUpdate already does at L431-434, and the two copies already disagree about where the "only from active" guard lives. Route the pause-only action through handleUpdate and move the .eq('status', 'active') guard into that update.
  • supabase/functions/webhook-endpoints/index.ts:66: reuse: a fifth hand-rolled UUID regex (paddleWebhookUserId.ts:1, localProfileId.ts:17, pushPayloadSchema.ts:40, personalRecordRow.ts:395 already have four). Export one isUuid helper and use it.
  • supabase/functions/webhook-endpoints/index.ts:302: reuse: the custom-header parsing and its two error strings are written twice, in handleCreate and handleUpdate. Extract one parseCustomHeader(value).
  • supabase/functions/_shared/webhookSend.test.ts:79: test-shrink: the Deno.env.set/Deno.env.delete block proves nothing (sendWebhook never reads the environment) and delete does not restore a pre-existing value, unlike the repo's save-set-restore pattern. Delete the block, keep the exact header-key assertions.
  • supabase/functions/_shared/webhookTarget.test.ts:199: delete: assert(WEBHOOK_REQUEST_TIMEOUT_MS <= 10_000) compares a constant with itself and passes for any value.
  • supabase/functions/_shared/webhookSigning.test.ts:37: test-shrink: "a changed body, id or timestamp changes the signature" asserts a property of HMAC-SHA256, not of this code; the reference vector above already pins the signed content.

Ponytail net: -55 lines.

Suggested Minimal Patch

Four files, no new dependency: validate the previous secret's shape in webhookCredentials.ts and drop it when invalid; move the set_webhook_endpoint_header RPC after the row update in index.ts; cap or account for the rows resend_all enqueues; make fakeSupabase.select() set returning for a delete and return null without it. The Ponytail items are optional cleanup and can follow in a separate commit.

Final Merge Guidance

Do not merge until the URL-change, half-applied-update and uncapped-resend_all behaviours are decided and the FLAME-gate test gap is closed; the remaining suggestions are optional cleanup.


Reviewed by minimax-m3 · Input: 128.6K · Output: 36.4K · Cached: 2.1M

9thLevelSoftware and others added 4 commits November 6, 2026 13:39
- A previous signing secret that cannot be decrypted no longer stops every
  delivery: it only smooths a rotation, so deliveries go out signed with the
  current secret alone.
- DNS resolution has its own 5 s deadline. The request timeout only starts
  with the fetch, so a resolver that hung could hold a delivery and the
  worker pass it belongs to.
- The Supabase test double returned deleted rows whether or not the caller
  asked for them. It now matches PostgREST, so dropping `.select()` from a
  delete (a 404 on success in production) would fail the suite.
- Tests: webhookCredentials gets its own file (rotation overlap, unreadable
  secrets, owner scoping); the tier gate is covered for rotate, test and
  resend as well as create and update.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Base automatically changed from feat/webhook-data-sharing-schema to main November 6, 2026 18:50
@9thLevelSoftware
9thLevelSoftware merged commit fc0a7fb into main Nov 6, 2026
12 of 23 checks passed
@9thLevelSoftware
9thLevelSoftware deleted the feat/webhook-endpoints-function branch November 6, 2026 19:00
// would stop every delivery over a secret that is being retired.
try {
const previous = await decrypt(row.previous_signing_secret_enc!);
if (previous) secrets.push(previous);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: A malformed secret still breaks every delivery - the new try/catch only covers a decrypt that throws

decryptOAuthSecret returns the stored column verbatim when it does not start with enc:v1: (_shared/oauthTokenCrypto.ts:123), so a row whose value was truncated, written by another producer, or stored in plaintext by a dev run can decrypt to any non-empty string. if (previous) secrets.push(previous) accepts it as-is, secretKeyBytes (_shared/webhookSigning.ts:44) throws webhook_secret_malformed, and that throw happens at _shared/webhookSend.ts:98 - outside sendWebhook's try/catch - so one bad rotation-overlap secret still takes down every delivery instead of falling back to the current one. Validate the shape of each secret before pushing it (prefix + strict base64 + at least 24 bytes) and drop the invalid one, or wrap the signing call in sendWebhook so a malformed secret becomes a connection_failed outcome.

* One private answer among public ones is a refusal, since the connection
* may use any of them. A resolver error, or no address at all, fails closed.
*/
function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR: The resolveWebhookTarget doc comment now documents withDeadline

Inserting the helper between the comment block (L277-281) and resolveWebhookTarget (L290) leaves the contract of resolveWebhookTarget attached to withDeadline instead, and leaves resolveWebhookTarget itself undocumented. Move the helper above the comment block, or move the comment back down to resolveWebhookTarget.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants