Harden website preview DNS IP validation
Summary
- moved website preview DNS IP classification into a dependency-free utility
- blocks additional non-public DNS answers before server-side preview fetches
- adds coverage for multicast, reserved, documentation, 6to4, ORCHID, IPv6 documentation/multicast/link-local, and IPv4-mapped loopback forms
- parses IPv6 special ranges by hextet/mask instead of relying on string prefixes
- adds focused unit tests for the SSRF guard helper
/claim #1667
Security impact
The private/website_preview endpoint validates a user-supplied website URL before fetching HTML and icons server-side. It already blocks localhost, direct IP literals, private IPv4 ranges, and some IPv6 ranges.
This patch closes gaps where a DNS response could resolve to non-public but previously unclassified ranges such as:
- IPv4 multicast/reserved:
224.0.0.0/4,240.0.0.0/4,255.255.255.255 - 6to4 relay anycast:
192.88.99.0/24 - IPv6 multicast, documentation, ORCHID, deprecated site-local, and link-local
fe80::/10ranges - IPv4-mapped IPv6 loopback forms such as
::ffff:7f00:1
That keeps website preview behavior aligned with its existing rule: preview targets must point to public hosts.
Residual risk
This is DNS preflight hardening. It does not fully bind the runtime fetch() connection to the validated DNS answer. A complete SSRF defense for DNS rebinding or split-horizon DNS would need connection-time egress enforcement, a trusted fetch proxy, or another runtime-supported way to reject private destinations at connect time.
Tests
npx --yes vitest run tests/website-preview-security.unit.test.ts --config /dev/nullnpx --yes -p typescript tsc --noEmit --ignoreConfig --allowImportingTsExtensions --moduleResolution bundler --module esnext --target es2022 --skipLibCheck supabase/functions/_backend/utils/ip.ts
Notes
- No production endpoints were tested.
- No private data, credentials, or accounts were accessed.
- This is a defensive code-review patch, not an exploit submission.
Summary by CodeRabbit
- New Features
- Enhanced IP address validation to more accurately classify private and public addresses, with comprehensive support for IPv4, IPv6, and IPv4-mapped IPv6 address formats, including improved detection of special-use and reserved address ranges.
- Tests
- Added comprehensive unit tests validating IP address classification across diverse address types and network ranges.
- Refactor
- Improved internal code organization by consolidating IP validation logic into dedicated utilities.
No actionable comments were generated in the recent review. π
βΉοΈ Recent review info
βοΈ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 9455b72a-bcae-4105-9bc5-657130bca49d
π₯ Commits
Reviewing files that changed from the base of the PR and between b520dae510408eebcc2a18c1f2df8d72b83f4615 and eebec6546bb632931ec67f2131d7ac201a879f1f.
π Files selected for processing (1)
supabase/functions/_backend/utils/publicUrl.ts
π Walkthrough
Walkthrough
Extracts private/reserved IP detection logic into a reusable ip.ts utility module with three exported functions (isPrivateIpv4, isPrivateIpv6, isPrivateIp) and internal helpers for IPv6 normalization. Integrates the new utility into publicUrl.ts by removing inline helpers. Adds comprehensive Vitest unit tests covering IPv4, IPv6, IPv4-mapped forms, and public addresses.
Changes
IP Privacy Detection Utility
| Layer / File(s) | Summary |
|---|---|
IP Detection Contracts and Helpers supabase/functions/_backend/utils/ip.ts |
Exports isPrivateIpv4, isPrivateIpv6, and isPrivateIp for classifying addresses as private/reserved. isPrivateIpv4 validates dotted-quad format and checks RFC1918, loopback, CGNAT, and test-net ranges. isPrivateIpv6 handles ::1/::, normalizes IPv4-mapped forms (::ffff:), and checks reserved prefixes (fe80::/10, fc00::/7, ff00::/8, etc.). isPrivateIp dispatches to IPv4 or IPv6 based on colon presence. Internal helpers normalizeMappedIpv4 and parseIpv6Hextets support IPv6 processing. |
Integration into Website Preview supabase/functions/_backend/utils/publicUrl.ts |
Imports isPrivateIp from the new ip.ts utility and removes the previous inline private-IP detection helpers, delegating classification to the shared module. |
Unit Test Coverage tests/website-preview-security.unit.test.ts |
Vitest suite asserting isPrivateIp returns true for non-public IPv4 ranges (loopback, RFC1918, CGNAT, test-net, documentation, link-local, multicast), IPv6 special-use ranges (unspecified, loopback, link-local, ULA, multicast, documentation), IPv4-mapped IPv6 variants, and malformed inputs; asserts false for globally-routable public addresses. |
Estimated code review effort
π― 3 (Moderate) | β±οΈ ~25 minutes
Possibly related PRs
- Cap-go/capgo#2199: Centralized and strengthened public outbound URL validation with private-IP detection, directly related to this PR's extraction of IP classification logic.
Poem
π° A utility hops into view,
Where IPv4 and IPv6 lines are true.
Private ranges? We catch them allβ
From loopback whispers to multicast call.
One module to test them, one place to belong! β¨
π₯ Pre-merge checks | β 4 | β 1
β Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | β οΈ Warning | Docstring coverage is 0.00% 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 'Harden website preview DNS IP validation' directly and specifically describes the main change: enhancing security validation for DNS IP addresses in the website preview feature. |
| Description check | β Passed | The PR description includes a comprehensive Summary section covering the changes and security impact, a detailed Security impact section explaining the gaps being closed, acknowledgment of residual risk, and explicit test commands. All key template sections are addressed. |
| 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
[!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 popka13221:capgo-website-preview-ip-hardening (eebec65) with main (94e06cc)
[^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.
Thanks for the review. I pushed an update that narrows the IPv4 192.0.0.0 check to 192.0.0.0/24, adds a regression case for 192.0.1.1, and parses the first IPv6 hextet to cover the full fe80::/10 link-local range including fe90::1 and febf::1.\n\nOn the DNS rebinding / TOCTOU point: agreed. This PR is DNS preflight hardening and does not fully bind fetch() to the validated answer. I added a Residual risk section to the PR description to make that clear. A complete fix likely needs connection-time egress enforcement or a trusted fetch proxy that rejects private/link-local/reserved destinations at connect time.
Thanks, good catch. I pushed a follow-up that rejects deprecated site-local fec0::/10 via the same hextet/mask parser and added regression cases for fec0::1 and feff::1.
Thanks, addressed. I replaced the loose IPv6 prefix parsing with a small fail-closed hextet parser, kept valid compressed public IPv6 accepted, and added regression cases for malformed IPv6 inputs plus a public compressed IPv6 address.
Fixed the lint failure from the latest CI run () and pushed the update. Local targeted checks still pass: website preview security unit test, TypeScript check for , and .
Fixed the lint failure from the latest CI run (e18e/prefer-array-fill) and pushed the update. Local targeted checks still pass: website preview security unit test, TypeScript check for utils/ip.ts, and git diff --check.
Review note: this improves the range classifier, but the fetch path still has a validation/use split. getPublicHostnameValidationError() resolves the host through Cloudflare DoH, then fetch(currentUrl) resolves the hostname again through the runtime resolver. A hostile hostname can answer with a public address during the validation lookup and a private/link-local address during the actual fetch, so the SSRF protection still depends on DNS stability across two independent resolutions.
A stronger follow-up would be to fetch the already-validated IP directly while preserving the original Host header/SNI where the runtime supports it, or proxy resolution/fetch through one controlled component that enforces the same resolved address. At minimum, I would document this residual risk so this PR is not treated as fully closing DNS rebinding for website previews.
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
Strong improvement over the original website_preview.ts private-IP checks β the move to utils/ip.ts with hextet-and-mask parsing is the right call, and the IPv6 coverage is now correct for the actual prefix lengths instead of leaning on startsWith strings (which silently miscount for the longer prefixes like fec0::/10). The PR body also honestly flags the residual rebinding risk, which I appreciate.
Few things worth tightening before this merges.
1. Webhook validation should now use the same library
utils/ip.ts is materially stricter than the isPrivateIp still living inside utils/webhook.ts β the webhook path is missing 6to4 anycast (192.88.99.0/24), multicast/class-E (224.0.0.0/3), TEST-NET-1, deprecated site-local IPv6, ORCHID, and the IPv4-mapped hex-pair form. After this PR, the website preview is well-defended and webhook delivery is not. Worse, website_preview.ts still imports getWebhookUrlValidationError from webhook.ts for the URL-shape check, so the two SSRF paths are now structurally entangled but inconsistent in what they block.
Suggested follow-up (could be in this PR or a quick next one): replace the inline isPrivateIpv4/isPrivateIpv6/isPrivateIp in webhook.ts with imports from utils/ip.ts, and have getWebhookUrlValidationErrorAsync use the same helper. Otherwise it's only a matter of time before a webhook target points at 192.88.99.x or a ::ffff:0a00:0001 and someone has to re-discover this.
2. NAT64 64:ff9b::/96 isn't blocked
isPrivateIpv6 correctly covers ULA, link-local, deprecated site-local, multicast, documentation, ORCHID, benchmarking, and 6to4. But the well-known NAT64 prefix 64:ff9b::/96 (RFC 6052) isn't in the list. An attacker who can get the resolver to return a NAT64 address can embed an arbitrary IPv4 β including any private one β and slip through, because the embedded 10.x.x.x is encoded in the low 32 bits of the IPv6 address and isPrivateIpv6 never looks at them.
Concrete test that currently passes ("public") but shouldn't:
expect(isPrivateIp('64:ff9b::a00:1')).toBe(true) // currently returns false
Suggested fix: add firstHextet === 0x0064 && secondHextet === 0xFF9B to the block list, OR (better) extract the low-32-bit IPv4 from any 64:ff9b::/96 address and recurse through isPrivateIpv4. The recurse form also defends against the local-network-translation prefix 64:ff9b:1::/48.
3. The 192.88.99.0/24 check uses octets[2] where the previous lines use c
Minor consistency β const [a, b, c] = octets is destructured at the top, but several lines mix c and octets[2]:
|| (a === 192 && b === 88 && octets[2] === 99) // uses octets[2]
β¦
|| (a === 192 && b === 0 && c === 0) // uses c
|| (a === 192 && b === 0 && octets[2] === 2) // uses octets[2]
|| (a === 198 && b === 51 && octets[2] === 100) // uses octets[2]
|| (a === 203 && b === 0 && octets[2] === 113) // uses octets[2]
Easy β β pick one. c reads slightly better in the boolean chain.
4. The comment on the TEST-NET block is slightly misleading
// Reserved TEST-NET ranges are also non-public for server-side fetch paths.
|| (a === 192 && b === 0 && c === 0) // 192.0.0.0/24 β IETF Protocol Assignments, NOT a TEST-NET
|| (a === 192 && b === 0 && octets[2] === 2) // 192.0.2.0/24 β TEST-NET-1
|| (a === 198 && b === 51 && octets[2] === 100) // TEST-NET-2
|| (a === 203 && b === 0 && octets[2] === 113) // TEST-NET-3
The first line under the comment is the IETF Protocol Assignments block (RFC 6890 Β§ 2.2.5), not a TEST-NET. Worth either splitting it under its own comment or relabeling the section "RFC 6890 special-use ranges."
5. Test gaps
The IPv6 test list is thorough. A few I'd add:
-
NAT64:
64:ff9b::a00:1(see #2) β single highest-value addition -
Legacy IPv4-compatible IPv6:
::1.2.3.4and::a00:1β current code returnstrue(rejected) because the mixed-mode address falls throughparseIpv6Hextets'svalue.includes('.') β nullearly-return. Pin the behavior with a test so a future cleanup of the parser doesn't accidentally unlock it. -
Loopback in hex-pair form via
::ffff::::ffff:127.0.0.1is covered;::ffff:7f00:1is covered. Worth also pinning::ffff:c0a8:101for 192.168.1.1 β different from anything currently exercised. -
Globally routable IPv6 negative: only Cloudflare and Google DNS are tested as public; worth one or two outside of the well-known DNS hosts to make sure no implementation detail accidentally classifies them as private.
6. Style nit: Number.isFinite vs Number.isNaN
const [high, low] = parts.map(part => Number.parseInt(part, 16))
if (!Number.isFinite(high) || !Number.isFinite(low) || high < 0 || high > 0xFFFF β¦)
parseInt('xyz', 16) returns NaN, and Number.isFinite(NaN) is false, so the check works. But Number.isNaN(x) reads more directly for the case you're actually trying to catch. The high < 0 guard is also unreachable since parseInt with a positive radix can only return NaN or a non-negative integer. Pure style, take it or leave it.
Excellent direction overall β turning this into a shared util is exactly what should have happened the first time, and now you've done it for two endpoints. Closing the webhook side too (#1) is the highest-leverage follow-up.
The IP range hardening is good, but fetchPublicUrl() still has the same DNS TOCTOU window as the webhook path. getPublicHostnameValidationError() resolves A/AAAA through Cloudflare DoH, then fetch(currentUrl, { redirect: 'manual' }) performs a separate runtime DNS resolution for the actual connection. A rebinding hostname can answer the validation lookup with a public IP and then answer the fetch resolver with 127.0.0.1, RFC1918, or metadata/link-local addresses.
Because redirects are already handled manually and each Location is revalidated, the missing piece is binding validation to the connection that gets opened. I would add a regression where the validation resolver sees a public address but the delivery/fetch resolver reaches a private address, and either route these requests through an egress proxy that enforces peer IPs or use a runtime mechanism that connects only to the validated address while preserving the original Host/SNI semantics.