Skip to content

Commit 218f3c0

Browse files
Update IPv6 parsing (#3334)
This updates our parsing / validating of IPv6 addresses, to make them more compliant with `std::net::Ipv6Addr` parsing. Instead of a regex, it uses the `new URL()` function as part of the evaluation. Closes #1939 --------- Co-authored-by: David Crespo <[email protected]>
1 parent ff240db commit 218f3c0

3 files changed

Lines changed: 102 additions & 8 deletions

File tree

‎app/util/ip.spec.ts‎

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { describe, expect, test } from 'vitest'
1010

1111
import type { ExternalIp, IpVersion, UnicastIpPool } from '~/api'
1212

13-
import { getEphemeralIpSlots, parseIp, parseIpNet } from './ip'
13+
import { getEphemeralIpSlots, toUrlCheckableIpv6, parseIp, parseIpNet } from './ip'
1414

1515
const makePool = (ipVersion: IpVersion, name = `pool-${ipVersion}`): UnicastIpPool => ({
1616
id: `id-${name}`,
@@ -183,6 +183,22 @@ describe('getEphemeralIpSlots', () => {
183183
// and oxnet's Ipv4Net and Ipv6Net have the same validation behavior as our code.
184184
// https://github.com/oxidecomputer/test-ip-validation
185185

186+
test.each([
187+
['2001:db8::1', '2001:db8::1'],
188+
['2001:db8:1:2::10.0.0.1', '2001:db8:1:2::0:0'],
189+
['1:2:3:4::10.0.0.1', '1:2:3:4::0:0'],
190+
['::ffff:255.255.255.255', '::ffff:0:0'],
191+
])('toUrlCheckableIpv6 converts %s to %s', (ip, expected) => {
192+
expect(toUrlCheckableIpv6(ip)).toBe(expected)
193+
})
194+
195+
test.each(['::ffff:1.2.3.04', '::251.240.044.17', '1::2:', '::1:', '1.2.3.4::', '1.2.3.4'])(
196+
'toUrlCheckableIpv6 rejects %s',
197+
(ip) => {
198+
expect(toUrlCheckableIpv6(ip)).toBeNull()
199+
}
200+
)
201+
186202
const v4 = ['123.4.56.7', '1.2.3.4']
187203

188204
test.each(v4)('parseIp catches valid IPV4 / invalid IPV6: %s', (s) => {
@@ -206,6 +222,18 @@ const v6 = [
206222
'::ffff:255.255.255.255',
207223
'fe08::7:8',
208224
'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
225+
// embedded IPv4 is allowed with :: in any position and in the full 6-group
226+
// form, not just after ::ffff: (console#1939)
227+
'2001:db8:3:4:5::192.0.2.33',
228+
'1:2:3:4:5:6:192.0.2.33',
229+
'::192.0.2.33',
230+
'2001:db8::192.0.2.33',
231+
'1:2:3:4::5:192.0.2.33',
232+
'db8:db8:db8:db8:db8::192.0.2.33',
233+
// WebKit's URL parser wrongly rejects embedded IPv4 where :: expands to
234+
// exactly two groups; isIpv6 validates the quad itself so these still pass
235+
'2001:db8:1:2::10.0.0.1',
236+
'1:2:3:4::10.0.0.1',
209237
]
210238

211239
test.each(v6)('parseIp catches invalid IPV4 / valid IPV6: %s', (s) => {
@@ -238,10 +266,33 @@ const invalid = [
238266
'::1:2:3:4:5:6:7:8',
239267
'1:2:3:4:5:6:7:8::',
240268
'1:2:3:4:5:6:7:88888',
241-
'2001:db8:3:4:5::192.0.2.33', // std::new::Ipv6Net allows this one
269+
'1:2:3:4:5:6:7:192.0.2.33', // one group too many before the dotted quad
270+
'::1.2.3.4.5',
271+
'1:2:3:4:5:6:7:8:1.2.3.4',
242272
'fe08::7:8%',
243273
'fe08::7:8i',
244274
'fe08::7:8interface',
275+
// zone IDs are valid in some contexts but std::net::Ipv6Addr rejects them
276+
'fe80::1%eth0',
277+
'fe80::1%0',
278+
'fe80::%eth0',
279+
'::1%lo0',
280+
// We validate v6 by handing the address to the URL parser as a bracketed
281+
// host, so a `]` plus a URL continuation could otherwise parse as port, path,
282+
// query, or fragment and come back valid. Zod's z.ipv6() has this bug.
283+
'::1]:80',
284+
'::1]:80/foo',
285+
'::1]#x',
286+
'::1]?q=1',
287+
'::1]:0/../x',
288+
'::1]@evil.com',
289+
'::1]',
290+
// engine quirks handled explicitly in isIpv6: Chrome's URL parser accepts
291+
// leading-zero octets in the embedded quad; WebKit's accepts a trailing colon
292+
'::ffff:1.2.3.04',
293+
'::251.240.044.17',
294+
'1::2:',
295+
'::1:',
245296
]
246297

247298
test.each(invalid)('parseIp catches invalid IP: %s', (s) => {

‎app/util/ip.ts‎

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,61 @@ export const orderIps = (ips: ExternalIp[]) => R.sortBy(ips, (a) => IP_ORDER[a.k
1818
// Borrowed from Valibot. I tried some from Zod and an O'Reilly regex cookbook
1919
// but they didn't match results with std::net on simple test cases
2020
// https://github.com/fabian-hiller/valibot/blob/2554aea5/library/src/regex.ts#L43-L54
21-
2221
const IPV4_REGEX =
2322
/^(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])(?:\.(?:(?:[1-9]|1\d|2[0-4])?\d|25[0-5])){3}$/u
2423

25-
const IPV6_REGEX =
26-
/^(?:(?:[\da-f]{1,4}:){7}[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,7}:|(?:[\da-f]{1,4}:){1,6}:[\da-f]{1,4}|(?:[\da-f]{1,4}:){1,5}(?::[\da-f]{1,4}){1,2}|(?:[\da-f]{1,4}:){1,4}(?::[\da-f]{1,4}){1,3}|(?:[\da-f]{1,4}:){1,3}(?::[\da-f]{1,4}){1,4}|(?:[\da-f]{1,4}:){1,2}(?::[\da-f]{1,4}){1,5}|[\da-f]{1,4}:(?::[\da-f]{1,4}){1,6}|:(?:(?::[\da-f]{1,4}){1,7}|:)|fe80:(?::[\da-f]{0,4}){0,4}%[\da-z]+|::(?:f{4}(?::0{1,4})?:)?(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d)|(?:[\da-f]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1?\d)?\d)\.){3}(?:25[0-5]|(?:2[0-4]|1?\d)?\d))$/iu
24+
// IPv6 is more complex; use the WHATWG URL parser rather than a regex to determine validity.
25+
// Restrict the charset first so the parser only ever sees a bare host: `]`, `/`,
26+
// `%`, and whitespace would otherwise let non-addresses through as port, path, or zone.
27+
28+
const IPV6_CHARS_REGEX = /^[0-9a-f:.]+$/i
29+
30+
/**
31+
* Convert an IPv6 candidate to a form all browsers' URL parsers judge
32+
* correctly, or return null if it's invalid in a way we can detect up front.
33+
* The result is only structurally equivalent to the input (an embedded IPv4
34+
* quad becomes placeholder groups) — use it for validity checking only, never
35+
* as an address.
36+
*/
37+
export function toUrlCheckableIpv6(ip: string): string | null {
38+
if (!ip.includes(':') || !IPV6_CHARS_REGEX.test(ip)) return null
39+
40+
// WebKit accepts a trailing single colon (`1::2:`), which std::net rejects.
41+
if (/[^:]:$/.test(ip)) return null
42+
43+
// URL parsers disagree on embedded IPv4, so validate the dotted quad and
44+
// replace it with two placeholder groups before handing the address to URL.
45+
const lastColon = ip.lastIndexOf(':')
46+
const quad = ip.slice(lastColon + 1)
47+
if (quad.includes('.')) {
48+
if (!IPV4_REGEX.test(quad)) return null
49+
return ip.slice(0, lastColon + 1) + '0:0'
50+
} else if (ip.includes('.')) {
51+
return null // dots are only valid in a trailing IPv4 quad
52+
}
53+
54+
return ip
55+
}
56+
57+
function isIpv6(ip: string): boolean {
58+
const normalizedIp = toUrlCheckableIpv6(ip)
59+
if (normalizedIp === null) return false
60+
61+
try {
62+
// the brackets force the parser to treat the host as an IPv6 literal —
63+
// without them, non-addresses like domain names would parse fine
64+
new URL(`http://[${normalizedIp}]`)
65+
return true
66+
} catch {
67+
return false
68+
}
69+
}
2770

2871
type ParsedIp = { type: IpVersion; address: string } | { type: 'error'; message: string }
2972

3073
export function parseIp(ip: string): ParsedIp {
3174
if (IPV4_REGEX.test(ip)) return { type: 'v4', address: ip }
32-
if (IPV6_REGEX.test(ip)) return { type: 'v6', address: ip }
75+
if (isIpv6(ip)) return { type: 'v6', address: ip }
3376
return { type: 'error', message: 'Not a valid IP address' }
3477
}
3578

‎vitest.browser.config.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ const pressComboboxKey: BrowserCommand<[label: string, key: string]> = async (
3030

3131
export default defineConfig({
3232
optimizeDeps: {
33-
entries: ['app/**/*.browser.spec.{ts,tsx}'],
33+
entries: ['app/**/*.browser.spec.{ts,tsx}', 'app/util/ip.spec.ts'],
3434
include: ['react-router'],
3535
},
3636
plugins: [tailwindcss(), react()],
@@ -39,7 +39,7 @@ export default defineConfig({
3939
attachmentsDir: 'test-results/vitest/attachments',
4040
// Concurrent Playwright contexts make focus-sensitive Firefox interactions flaky.
4141
fileParallelism: false,
42-
include: ['app/**/*.browser.spec.{ts,tsx}'],
42+
include: ['app/**/*.browser.spec.{ts,tsx}', 'app/util/ip.spec.ts'],
4343
name: 'browser',
4444
setupFiles: ['test/browser/setup.ts'],
4545
browser: {

0 commit comments

Comments
 (0)