Skip to content

Commit c831020

Browse files
authored
Merge commit from fork
* fix(ip-restriction): match static IP rules numerically * fix: throw TypeError for invalid IP addresses in ipaddr utils * fix(ip-restriction): validate CIDR prefixes
1 parent 905aedb commit c831020

4 files changed

Lines changed: 395 additions & 39 deletions

File tree

‎src/middleware/ip-restriction/index.test.ts‎

Lines changed: 76 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,60 @@ describe('ipRestriction middleware', () => {
6060
expect(await res.text()).toBe('error')
6161
}
6262
})
63+
64+
test.each(['999.999.999.999', '2001:db8::1%eth0', '1234:::5678'])(
65+
'Should reject invalid remote address: %s',
66+
async (ip) => {
67+
const app = new Hono<{
68+
Bindings: {
69+
ip: string
70+
}
71+
}>()
72+
app.use(
73+
'/invalid',
74+
ipRestriction(
75+
(c) => ({
76+
remote: {
77+
address: c.env.ip,
78+
},
79+
}),
80+
{
81+
allowList: ['127.0.0.1'],
82+
}
83+
)
84+
)
85+
app.get('/invalid', (c) => c.text('Hello World!'))
86+
87+
expect((await app.request('/invalid', {}, { ip })).status).toBe(403)
88+
}
89+
)
90+
91+
it('Should not call onError for invalid remote addresses', async () => {
92+
const app = new Hono<{
93+
Bindings: {
94+
ip: string
95+
}
96+
}>()
97+
app.use(
98+
'/invalid',
99+
ipRestriction(
100+
(c) => ({
101+
remote: {
102+
address: c.env.ip,
103+
},
104+
}),
105+
{
106+
allowList: ['127.0.0.1'],
107+
},
108+
() => new Response('custom error', { status: 418 })
109+
)
110+
)
111+
app.get('/invalid', (c) => c.text('Hello World!'))
112+
113+
const res = await app.request('/invalid', {}, { ip: '1234:::5678' })
114+
expect(res.status).toBe(403)
115+
expect(await res.text()).toBe('Forbidden')
116+
})
63117
})
64118

65119
describe('isMatchForRule', () => {
@@ -84,6 +138,17 @@ describe('isMatchForRule', () => {
84138
return true
85139
}
86140

141+
test.each(['192.168.0.0/33', '::/129', '127.0.0.1/', '::ffff:127.0.0.1/129'])(
142+
'Should throw for invalid CIDR rule: %s',
143+
(rule) => {
144+
expect(() =>
145+
ipRestriction(() => '127.0.0.1', {
146+
allowList: [rule],
147+
})
148+
).toThrow(`Invalid rule: ${rule}`)
149+
}
150+
)
151+
87152
it('star', async () => {
88153
expect(await isMatch({ addr: '192.168.2.0', type: 'IPv4' }, '*')).toBeTruthy()
89154
expect(await isMatch({ addr: '192.168.2.1', type: 'IPv4' }, '*')).toBeTruthy()
@@ -126,10 +191,18 @@ describe('isMatchForRule', () => {
126191
// IPv4-mapped IPv6 addresses are canonicalized to IPv4
127192
expect(await isMatch({ addr: '::ffff:127.0.0.1', type: 'IPv6' }, '127.0.0.1')).toBeTruthy()
128193
expect(await isMatch({ addr: '::ffff:127.0.0.1', type: 'IPv6' }, '127.0.0.2')).toBeFalsy()
129-
// non-dotted IPv4-mapped forms are not canonicalized (treated as IPv6)
130-
expect(await isMatch({ addr: '::ffff:7f00:1', type: 'IPv6' }, '127.0.0.1')).toBeFalsy()
131-
// regular IPv6 is not affected
194+
expect(await isMatch({ addr: '::ffff:7f00:1', type: 'IPv6' }, '127.0.0.1')).toBeTruthy()
195+
expect(await isMatch({ addr: '0:0:0:0:0:ffff:7f00:1', type: 'IPv6' }, '127.0.0.1')).toBeTruthy()
196+
// regular IPv6 is matched numerically without being treated as IPv4
132197
expect(await isMatch({ addr: '::1', type: 'IPv6' }, '::1')).toBeTruthy()
198+
expect(
199+
await isMatch({ addr: '2001:db8:0:0:0:0:0:1', type: 'IPv6' }, '2001:db8::1')
200+
).toBeTruthy()
201+
expect(
202+
await isMatch({ addr: '2001:db8::1', type: 'IPv6' }, '2001:db8:0:0:0:0:0:1')
203+
).toBeTruthy()
204+
expect(await isMatch({ addr: '::ffff:127.0.0.2', type: 'IPv6' }, '127.0.0.1')).toBeFalsy()
205+
expect(await isMatch({ addr: '::7f00:1', type: 'IPv6' }, '127.0.0.1')).toBeFalsy()
133206
})
134207
it('Function Rules', async () => {
135208
expect(await isMatch({ addr: '0.0.0.0', type: 'IPv4' }, () => true)).toBeTruthy()

‎src/middleware/ip-restriction/index.ts‎

Lines changed: 60 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,15 @@
66
import type { Context, MiddlewareHandler } from '../..'
77
import type { AddressType, GetConnInfo } from '../../helper/conninfo'
88
import { HTTPException } from '../../http-exception'
9+
import type { InvalidIPAddressError } from '../../utils/ipaddr'
910
import {
1011
convertIPv4MappedIPv6ToIPv4,
1112
convertIPv4ToBinary,
1213
convertIPv6BinaryToString,
1314
convertIPv6ToBinary,
1415
distinctRemoteAddr,
1516
isIPv4MappedIPv6,
17+
INVALID_IP_ADDRESS_ERROR_CODE,
1618
} from '../../utils/ipaddr'
1719

1820
/**
@@ -35,13 +37,47 @@ type GetIPAddr = GetConnInfo | ((c: Context) => string)
3537
type IPRestrictionRuleFunction = (addr: { addr: string; type: AddressType }) => boolean
3638
export type IPRestrictionRule = string | ((addr: { addr: string; type: AddressType }) => boolean)
3739

38-
const IS_CIDR_NOTATION_REGEX = /\/[0-9]{0,3}$/
40+
const IS_CIDR_NOTATION_REGEX = /\/[^/]*$/
41+
const parseCidrPrefix = (rule: string, prefix: string, max: number): number => {
42+
if (!/^[0-9]{1,3}$/.test(prefix)) {
43+
throw new TypeError(`Invalid rule: ${rule}`)
44+
}
45+
const parsedPrefix = parseInt(prefix)
46+
if (parsedPrefix > max) {
47+
throw new TypeError(`Invalid rule: ${rule}`)
48+
}
49+
return parsedPrefix
50+
}
3951
const buildMatcher = (
4052
rules: IPRestrictionRule[]
4153
): ((addr: { addr: string; type: AddressType; isIPv4: boolean }) => boolean) => {
4254
const functionRules: IPRestrictionRuleFunction[] = []
4355
const staticRules: Set<string> = new Set()
56+
const staticIPv4Rules: Set<bigint> = new Set()
57+
const staticIPv6Rules: Set<bigint> = new Set()
4458
const cidrRules: [boolean, bigint, bigint][] = []
59+
const registerStaticRule = (rule: string): void => {
60+
const type = distinctRemoteAddr(rule)
61+
if (type === undefined) {
62+
throw new TypeError(`Invalid rule: ${rule}`)
63+
}
64+
if (type === 'IPv4') {
65+
const ipv4binary = convertIPv4ToBinary(rule)
66+
staticRules.add(rule)
67+
staticRules.add(`::ffff:${rule}`)
68+
staticIPv4Rules.add(ipv4binary)
69+
staticIPv6Rules.add((0xffffn << 32n) | ipv4binary)
70+
} else {
71+
const ipv6binary = convertIPv6ToBinary(rule)
72+
const ipv6Addr = convertIPv6BinaryToString(ipv6binary)
73+
staticRules.add(ipv6Addr)
74+
staticIPv6Rules.add(ipv6binary)
75+
if (isIPv4MappedIPv6(ipv6binary)) {
76+
staticRules.add(ipv6Addr.substring(7)) // remove ::ffff: prefix
77+
staticIPv4Rules.add(convertIPv4MappedIPv6ToIPv4(ipv6binary))
78+
}
79+
}
80+
}
4581

4682
for (let rule of rules) {
4783
if (rule === '*') {
@@ -59,7 +95,7 @@ const buildMatcher = (
5995
}
6096

6197
let isIPv4 = type === 'IPv4'
62-
let prefix = parseInt(separatedRule[1])
98+
let prefix = parseCidrPrefix(rule, separatedRule[1], isIPv4 ? 32 : 128)
6399

64100
if (isIPv4 ? prefix === 32 : prefix === 128) {
65101
// this rule is a static rule
@@ -79,21 +115,7 @@ const buildMatcher = (
79115
}
80116
}
81117

82-
const type = distinctRemoteAddr(rule)
83-
if (type === undefined) {
84-
throw new TypeError(`Invalid rule: ${rule}`)
85-
}
86-
if (type === 'IPv4') {
87-
staticRules.add(rule)
88-
staticRules.add(`::ffff:${rule}`)
89-
} else {
90-
const ipv6binary = convertIPv6ToBinary(rule)
91-
const ipv6Addr = convertIPv6BinaryToString(ipv6binary)
92-
staticRules.add(ipv6Addr)
93-
if (isIPv4MappedIPv6(ipv6binary)) {
94-
staticRules.add(ipv6Addr.substring(7)) // remove ::ffff: prefix
95-
}
96-
}
118+
registerStaticRule(rule)
97119
}
98120
}
99121

@@ -115,6 +137,9 @@ const buildMatcher = (
115137
? remoteAddr
116138
: convertIPv4MappedIPv6ToIPv4(remoteAddr)
117139
: undefined
140+
if ((remote.isIPv4 ? staticIPv4Rules : staticIPv6Rules).has(remoteAddr)) {
141+
return true
142+
}
118143
for (const [isIPv4, addr, mask] of cidrRules) {
119144
if (isIPv4) {
120145
if (remoteIPv4Addr === undefined) {
@@ -221,14 +246,25 @@ export const ipRestriction = (
221246

222247
const remoteData = { addr, type, isIPv4: type === 'IPv4' }
223248

224-
if (denyMatcher(remoteData)) {
225-
if (onError) {
226-
return onError({ addr, type }, c)
249+
try {
250+
if (denyMatcher(remoteData)) {
251+
if (onError) {
252+
return onError({ addr, type }, c)
253+
}
254+
throw blockError(c)
227255
}
228-
throw blockError(c)
229-
}
230-
if (allowMatcher(remoteData)) {
231-
return await next()
256+
if (allowMatcher(remoteData)) {
257+
return await next()
258+
}
259+
} catch (e) {
260+
if (
261+
e instanceof TypeError &&
262+
(e as InvalidIPAddressError).code === INVALID_IP_ADDRESS_ERROR_CODE
263+
) {
264+
// If an invalid IP address is specified, treat it as if no IP address was specified
265+
throw blockError(c)
266+
}
267+
throw e
232268
}
233269

234270
if (allowLength === 0) {

‎src/utils/ipaddr.test.ts‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,20 @@ import {
55
convertIPv6ToBinary,
66
distinctRemoteAddr,
77
expandIPv6,
8+
INVALID_IP_ADDRESS_ERROR_CODE,
89
} from './ipaddr'
910

11+
const expectInvalidIPAddressError = (fn: () => unknown) => {
12+
try {
13+
fn()
14+
} catch (error) {
15+
expect(error).toBeInstanceOf(TypeError)
16+
expect(error).toHaveProperty('code', INVALID_IP_ADDRESS_ERROR_CODE)
17+
return
18+
}
19+
throw new Error('Expected invalid IP address error')
20+
}
21+
1022
describe('expandIPv6', () => {
1123
it('Should result be valid', () => {
1224
expect(expandIPv6('1::1')).toBe('0001:0000:0000:0000:0000:0000:0000:0001')
@@ -51,6 +63,13 @@ describe('convertIPv4ToBinary', () => {
5163

5264
expect(convertIPv4ToBinary('0.0.1.0')).toBe(1n << 8n)
5365
})
66+
67+
test.each(['1.2.3.256', '1.2.3', '1.2.3.4.5', '1..3.4', '01.2.3.4', 'a.b.c.d'])(
68+
'Should throw for invalid IPv4: %s',
69+
(input) => {
70+
expectInvalidIPAddressError(() => convertIPv4ToBinary(input))
71+
}
72+
)
5473
})
5574

5675
describe('convertIPv4ToString', () => {
@@ -71,8 +90,26 @@ describe('convertIPv6ToBinary', () => {
7190
expect(convertIPv6ToBinary('::1')).toBe(1n)
7291

7392
expect(convertIPv6ToBinary('::f')).toBe(15n)
74-
expect(convertIPv6ToBinary('1234:::5678')).toBe(24196103360772296748952112894165669496n)
93+
expect(convertIPv6ToBinary('1234::5678')).toBe(24196103360772296748952112894165669496n)
7594
expect(convertIPv6ToBinary('::ffff:127.0.0.1')).toBe(281472812449793n)
95+
expect(convertIPv6ToBinary('fe80::1%eth0')).toBe(convertIPv6ToBinary('fe80::1'))
96+
})
97+
98+
test.each([
99+
'1::2::3',
100+
'1:2:3:4:5:6:7:8:9',
101+
'1:2:3:4:5:6:7',
102+
'12345::',
103+
'gggg::',
104+
'::ffff:127.0.0.256',
105+
'1234:::5678',
106+
'2001:db8::1%eth0',
107+
'::ffff:127.0.0.1%eth0',
108+
'1:2:3%eth0',
109+
'gggg%eth0',
110+
'fe80::1%',
111+
])('Should throw for invalid IPv6: %s', (input) => {
112+
expectInvalidIPAddressError(() => convertIPv6ToBinary(input))
76113
})
77114
})
78115

@@ -82,11 +119,12 @@ describe('convertIPv6ToString', () => {
82119
input | expected
83120
${'::1'} | ${'::1'}
84121
${'1::'} | ${'1::'}
85-
${'1234:::5678'} | ${'1234::5678'}
122+
${'1234::5678'} | ${'1234::5678'}
86123
${'2001:2::'} | ${'2001:2::'}
87124
${'2001::db8:0:0:0:0:1'} | ${'2001:0:db8::1'}
88125
${'1234:5678:9abc:def0:1234:5678:9abc:def0'} | ${'1234:5678:9abc:def0:1234:5678:9abc:def0'}
89126
${'::ffff:127.0.0.1'} | ${'::ffff:127.0.0.1'}
127+
${'fe80::1%eth0'} | ${'fe80::1'}
90128
`('convertIPv6ToString($input) === $expected', ({ input, expected }) => {
91129
expect(convertIPv6BinaryToString(convertIPv6ToBinary(input))).toBe(expected)
92130
})

0 commit comments

Comments
 (0)