capgo icon indicating copy to clipboard operation
capgo copied to clipboard

fix(webhooks): block private DNS targets

Open cleberrafael opened this issue 6 months ago β€’ 13 comments

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.ts
  • npx 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.

Review Change Stack

cleberrafael avatar May 11 '26 10:05 cleberrafael

πŸ“ Walkthrough

Walkthrough

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.

Changes

Async DNS-Based Webhook URL Validation

Layer / File(s) Summary
DNS Validation Infrastructure
supabase/functions/_backend/utils/ip.ts
Adds 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.ts
Removes 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.ts
Imports 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.ts
Each 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.ts
Replaces local IP/DNS logic with shared helpers and broadens candidate-name tokenization delimiters.
Async URL Validation Tests
tests/webhook-url-validation.test.ts
Vitest 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

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • Cap-go/capgo#2199: Similar changes to webhook URL validation using async DNS-aware public-host checks.
  • Cap-go/capgo#2090: Prior edits touching webhook URL validation comments and boundaries; related to the validation area.

Poem

🐰 I hop through DNS fields, sniffing each host,

I skip the private burrows I fear the most.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
πŸ§ͺ Generate unit tests (beta)
  • [ ] Create PR with unit tests
βš”οΈ Resolve merge conflicts
  • [ ] Resolve merge conflict in branch 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.

❀️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 11 '26 10:05 coderabbitai[bot]

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)

Open in CodSpeed

[^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.

codspeed[bot] avatar May 11 '26 10:05 codspeed[bot]

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 to fetch (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 Host header 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 <= 239
  • 240.0.0.0/4 (class E / reserved, includes 255.255.255.255 limited broadcast) β€” a >= 240
  • Or, more conservatively and future-proof: a single a >= 224 clause.

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::/8 multicast
  • 64:ff9b::/96 NAT64 β€” this is the lever that lets an attacker embed a private IPv4 inside an IPv6 address and slip past the IPv6 check
  • 2001:db8::/32 documentation
  • 100::/64 discard-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 Answer array
  • 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.

michael-schvarcz avatar May 11 '26 19:05 michael-schvarcz

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.

subhajitlucky avatar May 12 '26 10:05 subhajitlucky

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.ts and 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/24 overmatch and 224.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"

cleberrafael avatar May 12 '26 10:05 cleberrafael

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.

michael-schvarcz avatar May 12 '26 14:05 michael-schvarcz

Pushed another follow-up commit (e44cd81) for the remaining IPv6 representation issue.

Changes:

  • replaced raw string-prefix checks for 100::/64, 64:ff9b::/96, and 2001:db8::/32 with expanded-hextet prefix comparisons
  • added regression coverage for zero-padded/equivalent forms like 0100::, 0064:ff9b::..., and 2001:0db8::
  • converted the webhook validation tests to it.concurrent() with hostname-routed fetch mocks so parallel execution does not race on global fetch

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

cleberrafael avatar May 13 '26 11:05 cleberrafael

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.

digzrow-coder avatar May 13 '26 19:05 digzrow-coder

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 Host header
  • 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.ts
  • npx 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.ts
  • git diff --check

michael-schvarcz avatar May 13 '26 19:05 michael-schvarcz

Fix conflict

riderx avatar May 14 '26 08:05 riderx

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.

anansutiawan avatar May 14 '26 14:05 anansutiawan

ο»Ώ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.

albercr3 avatar May 14 '26 14:05 albercr3