fix(webhooks): block private DNS targets
Summary
- add DNS-over-HTTPS resolution to webhook URL validation
- reject webhook hosts that resolve to private or special-use addresses
- apply the stricter validation when creating, updating, testing, retrying, dispatching, and delivering webhooks
Security context
The existing webhook guard blocked direct IP literals and localhost hostnames, but hostnames resolving to private network addresses were not checked. This hardens webhook delivery against SSRF-style private DNS targets while preserving the existing CAPGO_ALLOW_LOCAL_WEBHOOK_URLS local-development override.
Tests
npx vitest run tests/webhook-url-validation.test.tsnpx eslint "supabase/functions/_backend/utils/webhook.ts" "supabase/functions/_backend/public/webhooks/post.ts" "supabase/functions/_backend/public/webhooks/put.ts" "supabase/functions/_backend/public/webhooks/test.ts" "supabase/functions/_backend/public/webhooks/deliveries.ts" "supabase/functions/_backend/triggers/webhook_dispatcher.ts" "tests/webhook-url-validation.test.ts"
Summary by CodeRabbit
-
Bug Fixes
- URL validation for webhooks and previews now includes DNS-based checks, blocking targets that resolve to private/unroutable IPs; webhook deliveries also avoid following redirects.
- Website preview URL parsing and private-IP protections improved.
-
Tests
- Added extensive tests covering sync/async URL validation, DNS failure modes, private-IP cases, and redirect behavior.
Webhook URL validation now performs async DNS A/AAAA resolution and private-IP checks. A new async validator is added and awaited across webhook create/update/test/retry handlers, the dispatcher, delivery path, and website preview; tests exercise DNS outcomes and redirect behavior. Async DNS-Based Webhook URL Validation π― 4 (Complex) | β±οΈ ~45 minutes π° I hop through DNS fields, sniffing each host, I skip the private burrows I fear the most. βοΈ Tip: You can configure your own custom pre-merge checks in the settings.π Walkthrough
Walkthrough
Changes
Layer / File(s)
Summary
DNS Validation Infrastructure
supabase/functions/_backend/utils/ip.tsAdds DNS-over-HTTPS resolver,
isIpLiteral, isPrivateIp, and resolveHostnameIps helpers for A/AAAA lookups and IP classification.
Async URL Validator Function and webhook utils
supabase/functions/_backend/utils/webhook.tsRemoves in-file IP detection, imports IP/DNS helpers, adds
getWebhookUrlValidationErrorAsync which runs sync checks then resolves A/AAAA and blocks private/unresolvable hosts; delivery now calls this async validator.
Webhook Dispatcher
supabase/functions/_backend/triggers/webhook_dispatcher.tsImports and awaits async validator; validation error controls whether delivery is marked failed or queued.
Webhook Handlers (Create/Update/Test/Retry)
supabase/functions/_backend/public/webhooks/post.ts, put.ts, test.ts, deliveries.tsEach handler imports and awaits async URL validator instead of synchronous validation before proceeding with webhook operations.
Website Preview reuse
supabase/functions/_backend/private/website_preview.tsReplaces local IP/DNS logic with shared helpers and broadens candidate-name tokenization delimiters.
Async URL Validation Tests
tests/webhook-url-validation.test.tsVitest suite stubbing DNS responses validates direct IP rejection, private-IP resolution rejection, mixed answers behavior, fails-closed DNS, public-IP acceptance, and delivery redirect handling.
Sequence Diagram
sequenceDiagram
participant Handler as webhook handler
participant Validator as getWebhookUrlValidationErrorAsync
participant DNS as resolveHostnameIps (DoH)
participant Classifier as isPrivateIp
participant Queue as queueWebhookDelivery
Handler->>Validator: validate URL (await)
Validator->>DNS: request A and AAAA records
DNS-->>Validator: list of IPs
Validator->>Classifier: check each IP
Classifier-->>Validator: private/public verdict
Validator-->>Handler: validation result (null or error)
Handler->>Queue: queue delivery (when valid)
Estimated code review effort
Possibly related PRs
Poem
I await the answers, check addresses twice,
Only public hooks get a carrot of spice.
Safe deliveries! π₯π₯ Pre-merge checks | β
4 | β 1
β Failed checks (1 warning)
Check name
Status
Explanation
Resolution
Docstring Coverage
β οΈ Warning
Docstring coverage is 4.17% which is insufficient. The required threshold is 80.00%.
Write docstrings for the functions missing them to satisfy the coverage threshold.
β
Passed checks (4 passed)
Check name
Status
Explanation
Title check
β
Passed
The title 'fix(webhooks): block private DNS targets' directly and concisely describes the main security hardening: rejecting webhook hosts that resolve to private IP addresses.
Description check
β
Passed
The PR description includes a clear summary of changes, security context, and test instructions, though it does not fully follow the repository's template structure (missing Screenshots and incomplete Checklist sections).
Linked Issues check
β
Passed
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
β
Passed
Check skipped because no linked issues were found for this pull request.
β¨ Finishing Touches
π§ͺ Generate unit tests (beta)
βοΈ Resolve merge conflicts
codex/harden-webhook-url-validation
[!TIP]
π¬ Introducing Slack Agent: The best way for teams to turn conversations into code.
Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
- Generate code and open pull requests
- Plan features and break down work
- Investigate incidents and troubleshoot customer tickets together
- Automate recurring tasks and respond to alerts with triggers
- Summarize progress and report instantly
Built for teams:
- Shared memory across your entire orgβno repeating context
- Per-thread sandboxes to safely plan and execute work
- Governance built-inβscoped access, auditability, and budget controls
One agent for your entire SDLC. Right inside Slack.
π Get started
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
Merging this PR will not alter performance
β
43 untouched benchmarks
β© 2 skipped benchmarks[^skipped]
Comparing cleberrafael:codex/harden-webhook-url-validation (b767ba9) with main (1d10e6f)
[^skipped]: 2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
Nice direction β closing the DNS-resolution gap in webhook validation is real protection. Few things I'd push back on before this merges, in roughly decreasing severity.
1. TOCTOU / DNS-rebinding bypass (highest impact)
getWebhookUrlValidationErrorAsync resolves the hostname and rejects if any IP is private, but deliverWebhook then does a separate fetch(url, ...) that resolves the same hostname again in the runtime's HTTP client. An attacker who controls the authoritative DNS for the webhook hostname can return a public IP on the first lookup (passes validation) and a private IP on the second (the actual delivery). This is the classic DNS rebinding pattern and survives this PR.
Two ways to close it:
- After resolving in
resolveHostnameIps, pick one of the returned public IPs and pass{ resolved: { ... } }-style options tofetch(Cloudflare Workers and Deno both expose this), so the connection goes to the IP you actually validated. - Or, since the resolver returns the IPs anyway, build the request against the IP directly and set the
Hostheader to the original hostname. Slightly fiddlier with TLS SNI but works.
PR #2106 (Harden website preview DNS IP validation) explicitly acknowledges the same residual risk in its body, so it's worth coordinating with that PR on a shared fix rather than punting it twice.
2. (a === 192 && b === 0) over-matches the IETF protocol block
This line is meant to block 192.0.0.0/24 (RFC 6890 Β§ 2.2.5, IETF Protocol Assignments), but as written it matches a === 192 && b === 0 with no constraint on the third or fourth octet, i.e. all of 192.0.0.0/16. That accidentally covers TEST-NET-1 (192.0.2.0/24 β also listed below it as a separate clause, so this is double-covered) but also blocks 192.0.1.x, 192.0.3.x, 192.0.4.x etc., which are not reserved and could be legitimate webhook targets. Tighten to (a === 192 && b === 0 && octets[2] === 0) to match what the comment suggests.
3. Missing IPv4 special-use ranges
Beyond the /16 over-match, these RFC 6890 ranges are not covered:
224.0.0.0/4(multicast) βa >= 224 && a <= 239240.0.0.0/4(class E / reserved, includes255.255.255.255limited broadcast) βa >= 240- Or, more conservatively and future-proof: a single
a >= 224clause.
PR #2106 takes the a >= 224 approach and consolidates into a shared utils/ip.ts β the natural follow-up is to have this PR import from there too, see #6.
4. IPv6 link-local: startsWith('fe80:') is too narrow
Link-local is fe80::/10, not fe80::/16. The top ten bits 1111111010 cover hextet values 0xfe80 through 0xfebf, so fe90::1, feab::1, etc. are also link-local and currently pass through. Two ways to fix:
// option a: prefix-only check for the four hextet values
;['fe80:', 'fe90:', 'fea0:', 'feb0:'].some(p => normalized.startsWith(p))
// option b (cleaner): parse the first hextet and mask
const firstHextet = parseInt(normalized.split(':')[0] || '0', 16)
if ((firstHextet & 0xFFC0) === 0xFE80) return true
Same issue, separately, for the deprecated site-local range fec0::/10 β currently uncovered and worth adding as defense-in-depth.
5. IPv4-mapped IPv6 in hex-pair form is rejected outright (usability)
This one's a usability gotcha, not a security bug, but it'll surprise someone.
if (normalized.startsWith('::ffff:'))
return isPrivateIpv4(normalized.slice(7))
If the resolver returns the hex-pair encoding ::ffff:0808:0808 (= 8.8.8.8), slice(7) is 0808:0808. That string has no ., so isPrivateIpv4's octets.length !== 4 check trips and returns true (private). Result: a legitimate public IPv4-mapped IPv6 host is rejected as "must point to a public host." Fail-closed is the right side to err on, but if Cloudflare DoH ever returns this form for an AAAA query, it'll look like a confusing customer-facing bug. Either normalize the hex-pair form into dotted form before passing to isPrivateIpv4, or fall back to a structured IPv6 parse on the second branch.
6. Missing IPv6 ranges
ff00::/8multicast64:ff9b::/96NAT64 β this is the lever that lets an attacker embed a private IPv4 inside an IPv6 address and slip past the IPv6 check2001:db8::/32documentation100::/64discard-only
Again, PR #2106's utils/ip.ts already handles most of these. Strong case for sharing the implementation rather than keeping two divergent copies.
7. No timeout on the DNS-over-HTTPS lookup
const response = await fetch(dnsUrl.toString(), {
headers: { Accept: 'application/dns-json' },
})
If cloudflare-dns.com is slow or hangs, every webhook validation hangs with it (you do two of these per validation β A and AAAA). Worth an AbortSignal.timeout(2_000) and a deliberate decision on failure mode β current behavior is fail-closed (returns [] β "host could not be resolved"), which is the safer side but does mean a Cloudflare DNS outage takes out webhook delivery entirely. At minimum, log it loudly when this happens so you don't get a silent outage.
8. Hardcoded resolver, no fallback
DNS_LOOKUP_URL = 'https://cloudflare-dns.com/dns-query' makes Capgo's webhook subsystem reliant on a single third party. Consider making it env-configurable so self-hosters can use Quad9 / Google / their own resolver, and consider falling through to a second resolver on the first one's failure. Operational rather than security, but it's a one-line change that buys real resilience.
9. Test coverage gaps
Current tests cover three happy paths. Worth adding:
- DNS returns both a public and a private IP for the same host (CDN-style multi-record) β current code rejects, good, but no test pins it
- AAAA returns an IPv4-mapped IPv6 in hex-pair form (see #5)
- Link-local outside
fe80::prefix, e.g.fea0::1(see #4) - Non-200 response from the resolver
- Empty
Answerarray - Multicast / class-E hits (whichever ranges land in #3)
Happy to spin any of these into a follow-up PR if useful. Thanks for the work on this.
Review note: this still allows an SSRF bypass through redirects.
getWebhookUrlValidationErrorAsync() validates the original webhook URL, but deliverWebhook() then calls fetch(url, ...) with the default redirect behavior. A webhook endpoint on a public host can return a 30x redirect to http://127.0.0.1/..., http://169.254.169.254/..., or another private-network host. The original URL passes DNS validation, then the runtime follows the redirect without validating the redirect target.
A safer shape is to set redirect: "manual" on webhook delivery fetches and either reject redirects entirely or resolve/validate each Location target before following it, with a strict redirect count. The retry/test delivery paths should use the same behavior so validation and delivery cannot diverge.
Thanks for the detailed reviews. I pushed a follow-up commit (b1de6c3) addressing the actionable items:
- moved the DNS/IP checks into shared
utils/ip.tsand reused it from webhook validation and website preview validation, which should reduce the Sonar duplication - tightened IPv4 special-use handling, including the
192.0.0.0/24overmatch and224.0.0.0/4+ reserved/broadcast space - expanded IPv6 blocking for
fe80::/10,fec0::/10,fc00::/7, multicast, documentation/discard/NAT64 ranges, and IPv4-mapped hex-pair form - added timeout/error handling for DoH lookups, with fail-closed behavior
- kept webhook delivery
redirect: 'manual'and added a regression test for redirect-to-private SSRF - documented the remaining DNS-rebinding window inline since fully closing it needs connect-time IP pinning or egress enforcement
Verification run locally:
npx vitest run tests/webhook-url-validation.test.ts
npx eslint "supabase/functions/_backend/utils/ip.ts" "supabase/functions/_backend/utils/webhook.ts" "supabase/functions/_backend/private/website_preview.ts" "supabase/functions/_backend/public/webhooks/post.ts" "supabase/functions/_backend/public/webhooks/put.ts" "supabase/functions/_backend/public/webhooks/test.ts" "supabase/functions/_backend/public/webhooks/deliveries.ts" "supabase/functions/_backend/triggers/webhook_dispatcher.ts" "tests/webhook-url-validation.test.ts"
Thanks for the follow-up, this addresses most of the concerns I raised, especially the shared IP utilities, DoH timeout/error handling, redirect: 'manual', and broader IPv4/IPv6 special-use coverage.
The remaining CodeRabbit finding looks valid to me: the 100::/64, 64:ff9b::/96, and 2001:db8::/32 checks should avoid raw string-prefix matching because IPv6 allows equivalent zero-padded/abbreviated forms like 0100::, 0064:ff9b::..., and 2001:0db8::.
A small helper that expands IPv6 into 8 hextets and compares prefix bits would close that cleanly. After that and the merge conflict resolution, this looks much closer.
Pushed another follow-up commit (e44cd81) for the remaining IPv6 representation issue.
Changes:
- replaced raw string-prefix checks for
100::/64,64:ff9b::/96, and2001:db8::/32with expanded-hextet prefix comparisons - added regression coverage for zero-padded/equivalent forms like
0100::,0064:ff9b::..., and2001:0db8:: - converted the webhook validation tests to
it.concurrent()with hostname-routed fetch mocks so parallel execution does not race on globalfetch
Verification run locally:
npx vitest run tests/webhook-url-validation.test.ts
npx eslint "supabase/functions/_backend/utils/ip.ts" "tests/webhook-url-validation.test.ts" "supabase/functions/_backend/utils/webhook.ts" "supabase/functions/_backend/private/website_preview.ts"
git diff --check
Quality Gate passed
Issues
0 New issues
0 Accepted issues
Measures
0 Security Hotspots
0.0% Coverage on New Code
0.0% Duplication on New Code
This still has a DNS TOCTOU gap. getWebhookUrlValidationErrorAsync() asks Cloudflare DoH for A/AAAA records and approves the hostname when those answers are public, but the actual fetch(url, ...) performs a separate resolution afterwards. A rebinding webhook host can return a public address to the validation lookup and then return 127.0.0.1 / RFC1918 / metadata IPs to the worker fetch, so the private-host block is not tied to the connection that is actually opened.
Since redirects are already manual, the remaining hard part is binding validation to delivery. I would either resolve and connect to the validated address while preserving the original Host/SNI semantics where the runtime supports it, or add an egress proxy/allowlist layer that enforces the resolved peer address at connect time. A regression can mock validation DNS as public while the delivery resolver points the same hostname at a private IP, and assert the delivery is blocked rather than posted.
I pushed a follow-up branch with the remaining DNS TOCTOU fix and opened a PR into this PR's source branch:
- Follow-up PR: https://github.com/cleberrafael/capgo/pull/1
- Branch: https://github.com/michael-schvarcz/capgo/tree/codex/harden-webhook-url-validation-toctou
- Commit: michael-schvarcz/capgo@9519933eec86325dd697c0270485532b995d14bb
Summary of the fix:
- webhook delivery now validates DNS and then pins the outbound TLS connection to one of the validated public IPs
- preserves the original hostname for SNI and the HTTP
Hostheader - avoids the second runtime hostname resolution that allowed DNS rebinding between validation and delivery
- keeps redirects manual/non-followed
Coverage added/updated:
- DNS rebinding regression: validation DNS is public, delivery uses the validated IP, and runtime
fetch()is not used for the POST - loopback, RFC1918, IPv4 link-local/metadata, reserved/multicast IPv4
- IPv6 link-local, discard-only, NAT64, documentation, and multicast ranges
- redirect responses remain unsuccessful and are not followed
Ran locally:
npx vitest run tests/webhook-url-validation.test.ts tests/webhook-delivery-security.unit.test.ts tests/webhook-delivery-redirect.unit.test.tsnpx eslint supabase/functions/_backend/utils/ip.ts supabase/functions/_backend/utils/webhook.ts tests/webhook-url-validation.test.ts tests/webhook-delivery-security.unit.test.ts tests/webhook-delivery-redirect.unit.test.tsgit diff --check
Fix conflict
P2: IPv4-mapped IPv6 is only detected when the address string starts with ::ffff:. The new numeric IPv6 checks still miss equivalent expanded forms inside ::ffff:0:0/96, for example 0:0:0:0:0:ffff:7f00:1 for 127.0.0.1 and 0000:0000:0000:0000:0000:ffff:0a00:0001 for 10.0.0.1. In a local reproduction of the PR-head classifier, both returned false from isPrivateIp, so a hostname resolving only to such an AAAA answer can be classified as public by this guard. Please parse IPv6 hextets first and check hextets[0..5] == [0,0,0,0,0,0xffff], then pass the last 32 bits through the IPv4 classifier. I have local regression coverage for expanded mapped loopback/RFC1918 and a public mapped address like 0:0:0:0:0:ffff:0808:0808.
ο»ΏP2: Partial DNS lookup failures can still pass validation when the other family returns a public address. resolveHostnameIps() collapses a non-OK response, timeout, or thrown lookup into [], and getWebhookUrlValidationErrorAsync() only fails closed when the combined ips array is empty. That means this sequence currently returns null: A lookup succeeds with 93.184.216.34, AAAA lookup times out or returns 503. For an SSRF guard, that leaves a validation gap because the failed family was never classified; a private AAAA answer hidden behind that transient failure would be ignored, and the later runtime fetch may still resolve/use it.
I would make lookup failure explicit instead of encoding it as an empty answer set, then reject if either A or AAAA lookup errors. Empty Answer with an OK DNS response can remain valid as "no records for this family", but resolver/network failure should probably produce Webhook URL host could not be resolved even when the other family returned public records. A regression test can mock A -> 93.184.216.34 and AAAA -> 503 and assert validation fails closed.