Merge commit from fork
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(ip-restriction): match static IP rules numerically * fix: throw TypeError for invalid IP addresses in ipaddr utils * fix(ip-restriction): validate CIDR prefixes
authored by Taku Amano · committed by GitHub · parent 905aedb · Browse files · 4 files·+395 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+395 added−39 removed
- tests:+116 added−5 removed
- other:+279 added−34 removed
Provenance
- Commit
c831020- Tree
34383dd- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
905aedb
4 files changed+395 added−39 removed
modified:src/middleware/ip-restriction/index.test.ts+76 added-3 removed
58 unmodified lines596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912016 unmodified lines13713813914014114214314414514614714814915015115215315415534 unmodified lines1901911921931291301311941951961971981992002012022032042052062072082098 unmodified lines58 unmodified lines if (res) { expect(await res.text()).toBe('error') } })
test.each(['999.999.999.999', '2001:db8::1%eth0', '1234:::5678'])( 'Should reject invalid remote address: %s', async (ip) => { const app = new Hono<{ Bindings: { ip: string } }>() app.use( '/invalid', ipRestriction( (c) => ({ remote: { address: c.env.ip, }, }), { allowList: ['127.0.0.1'], } ) ) app.get('/invalid', (c) => c.text('Hello World!'))
expect((await app.request('/invalid', {}, { ip })).status).toBe(403) } )
it('Should not call onError for invalid remote addresses', async () => { const app = new Hono<{ Bindings: { ip: string } }>() app.use( '/invalid', ipRestriction( (c) => ({ remote: { address: c.env.ip, }, }), { allowList: ['127.0.0.1'], }, () => new Response('custom error', { status: 418 }) ) ) app.get('/invalid', (c) => c.text('Hello World!'))
const res = await app.request('/invalid', {}, { ip: '1234:::5678' }) expect(res.status).toBe(403) expect(await res.text()).toBe('Forbidden') })})
describe('isMatchForRule', () => { const isMatch = async (info: { addr: string; type: AddressType }, rule: IPRestrictionRule) => {16 unmodified lines } return true }
test.each(['192.168.0.0/33', '::/129', '127.0.0.1/', '::ffff:127.0.0.1/129'])( 'Should throw for invalid CIDR rule: %s', (rule) => { expect(() => ipRestriction(() => '127.0.0.1', { allowList: [rule], }) ).toThrow(`Invalid rule: ${rule}`) } )
it('star', async () => { expect(await isMatch({ addr: '192.168.2.0', type: 'IPv4' }, '*')).toBeTruthy() expect(await isMatch({ addr: '192.168.2.1', type: 'IPv4' }, '*')).toBeTruthy() expect(await isMatch({ addr: '::0', type: 'IPv6' }, '*')).toBeTruthy()34 unmodified lines expect(await isMatch({ addr: '127.0.0.1', type: 'IPv4' }, '::ffff:127.0.0.1')).toBeTruthy() // IPv4-mapped IPv6 addresses are canonicalized to IPv4 expect(await isMatch({ addr: '::ffff:127.0.0.1', type: 'IPv6' }, '127.0.0.1')).toBeTruthy() expect(await isMatch({ addr: '::ffff:127.0.0.1', type: 'IPv6' }, '127.0.0.2')).toBeFalsy() // non-dotted IPv4-mapped forms are not canonicalized (treated as IPv6) expect(await isMatch({ addr: '::ffff:7f00:1', type: 'IPv6' }, '127.0.0.1')).toBeFalsy() // regular IPv6 is not affected expect(await isMatch({ addr: '::ffff:7f00:1', type: 'IPv6' }, '127.0.0.1')).toBeTruthy() expect(await isMatch({ addr: '0:0:0:0:0:ffff:7f00:1', type: 'IPv6' }, '127.0.0.1')).toBeTruthy() // regular IPv6 is matched numerically without being treated as IPv4 expect(await isMatch({ addr: '::1', type: 'IPv6' }, '::1')).toBeTruthy() expect( await isMatch({ addr: '2001:db8:0:0:0:0:0:1', type: 'IPv6' }, '2001:db8::1') ).toBeTruthy() expect( await isMatch({ addr: '2001:db8::1', type: 'IPv6' }, '2001:db8:0:0:0:0:0:1') ).toBeTruthy() expect(await isMatch({ addr: '::ffff:127.0.0.2', type: 'IPv6' }, '127.0.0.1')).toBeFalsy() expect(await isMatch({ addr: '::7f00:1', type: 'IPv6' }, '127.0.0.1')).toBeFalsy() }) it('Function Rules', async () => { expect(await isMatch({ addr: '0.0.0.0', type: 'IPv4' }, () => true)).toBeTruthy() expect(await isMatch({ addr: '0.0.0.0', type: 'IPv4' }, () => false)).toBeFalsy()8 unmodified linesmodified:src/middleware/ip-restriction/index.ts+60 added-24 removed
4 unmodified lines5 6 import type { Context, MiddlewareHandler } from '../..'7 import type { AddressType, GetConnInfo } from '../../helper/conninfo'8 import { HTTPException } from '../../http-exception'9+import type { InvalidIPAddressError } from '../../utils/ipaddr'10 import {11 convertIPv4MappedIPv6ToIPv4,12 convertIPv4ToBinary,13 convertIPv6BinaryToString,14 convertIPv6ToBinary,15 distinctRemoteAddr,16 isIPv4MappedIPv6,17+ INVALID_IP_ADDRESS_ERROR_CODE,18 } from '../../utils/ipaddr'19 20 /**21 * Function to get IP Address14 unmodified lines36 */37 type IPRestrictionRuleFunction = (addr: { addr: string; type: AddressType }) => boolean38 export type IPRestrictionRule = string | ((addr: { addr: string; type: AddressType }) => boolean)39 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 parsedPrefix50+}51 const buildMatcher = (52 rules: IPRestrictionRule[]53 ): ((addr: { addr: string; type: AddressType; isIPv4: boolean }) => boolean) => {54 const functionRules: IPRestrictionRuleFunction[] = []55 const staticRules: Set<string> = new Set()56+ const staticIPv4Rules: Set<bigint> = new Set()57+ const staticIPv6Rules: Set<bigint> = new Set()58 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: prefix77+ staticIPv4Rules.add(convertIPv4MappedIPv6ToIPv4(ipv6binary))78+ }79+ }80+ }81 82 for (let rule of rules) {83 if (rule === '*') {84 return () => true9 unmodified lines94 throw new TypeError(`Invalid rule: ${rule}`)95 }96 97 let isIPv4 = type === 'IPv4'62- let prefix = parseInt(separatedRule[1])98+ let prefix = parseCidrPrefix(rule, separatedRule[1], isIPv4 ? 32 : 128)99 100 if (isIPv4 ? prefix === 32 : prefix === 128) {101 // this rule is a static rule102 rule = addrStr11 unmodified lines114 continue115 }116 }117 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: prefix95- }96- }118+ registerStaticRule(rule)119 }120 }121 122 return (remote: {13 unmodified lines136 ? remote.isIPv4137 ? remoteAddr138 : convertIPv4MappedIPv6ToIPv4(remoteAddr)139 : undefined140+ if ((remote.isIPv4 ? staticIPv4Rules : staticIPv6Rules).has(remoteAddr)) {141+ return true142+ }143 for (const [isIPv4, addr, mask] of cidrRules) {144 if (isIPv4) {145 if (remoteIPv4Addr === undefined) {146 continue98 unmodified lines245 (typeof connInfo !== 'string' && connInfo.remote.addressType) || distinctRemoteAddr(addr)246 247 const remoteData = { addr, type, isIPv4: type === 'IPv4' }248 249+ try {224- if (denyMatcher(remoteData)) {225- if (onError) {226- return onError({ addr, type }, c)250+ if (denyMatcher(remoteData)) {251+ if (onError) {252+ return onError({ addr, type }, c)253+ }254+ throw blockError(c)255 }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_CODE263+ ) {264+ // If an invalid IP address is specified, treat it as if no IP address was specified228- throw blockError(c)265+ throw blockError(c)266+ }267+ throw e268 }230- if (allowMatcher(remoteData)) {231- return await next()232- }269 270 if (allowLength === 0) {271 return await next()272 } else {7 unmodified linesmodified:src/utils/ipaddr.test.ts+40 added-2 removed
3 unmodified lines4 convertIPv6BinaryToString,5 convertIPv6ToBinary,6 distinctRemoteAddr,7 expandIPv6,8+ INVALID_IP_ADDRESS_ERROR_CODE,9 } from './ipaddr'10 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+ return18+ }19+ throw new Error('Expected invalid IP address error')20+}21+22 describe('expandIPv6', () => {23 it('Should result be valid', () => {24 expect(expandIPv6('1::1')).toBe('0001:0000:0000:0000:0000:0000:0000:0001')25 expect(expandIPv6('::1')).toBe('0000:0000:0000:0000:0000:0000:0000:0001')36 unmodified lines62 expect(convertIPv4ToBinary('0.0.0.1')).toBe(1n)63 64 expect(convertIPv4ToBinary('0.0.1.0')).toBe(1n << 8n)65 })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+ )73 })74 75 describe('convertIPv4ToString', () => {76 // add tons of test cases here12 unmodified lines89 expect(convertIPv6ToBinary('::0')).toBe(0n)90 expect(convertIPv6ToBinary('::1')).toBe(1n)91 92 expect(convertIPv6ToBinary('::f')).toBe(15n)74- expect(convertIPv6ToBinary('1234:::5678')).toBe(24196103360772296748952112894165669496n)93+ expect(convertIPv6ToBinary('1234::5678')).toBe(24196103360772296748952112894165669496n)94 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))113+ })114 })115 116 describe('convertIPv6ToString', () => {117 // add tons of test cases here118 test.each`119 input | expected120 ${'::1'} | ${'::1'}121 ${'1::'} | ${'1::'}85- ${'1234:::5678'} | ${'1234::5678'}122+ ${'1234::5678'} | ${'1234::5678'}123 ${'2001:2::'} | ${'2001:2::'}124 ${'2001::db8:0:0:0:0:1'} | ${'2001:0:db8::1'}125 ${'1234:5678:9abc:def0:1234:5678:9abc:def0'} | ${'1234:5678:9abc:def0:1234:5678:9abc:def0'}126 ${'::ffff:127.0.0.1'} | ${'::ffff:127.0.0.1'}127+ ${'fe80::1%eth0'} | ${'fe80::1'}128 `('convertIPv6ToString($input) === $expected', ({ input, expected }) => {129 expect(convertIPv6BinaryToString(convertIPv6ToBinary(input))).toBe(expected)130 })131 })modified:src/utils/ipaddr.ts+219 added-10 removed
33 unmodified lines34 }35 36 const IPV4_OCTET_PART = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])'37 const IPV4_REGEX = new RegExp(`^(?:${IPV4_OCTET_PART}\\.){3}${IPV4_OCTET_PART}$`)38+export const INVALID_IP_ADDRESS_ERROR_CODE = 'ERR_INVALID_IP_ADDRESS'39+export type InvalidIPAddressError = TypeError & {40+ code: typeof INVALID_IP_ADDRESS_ERROR_CODE41+}42+const CHAR_CODE_0 = 4843+const CHAR_CODE_9 = 5744+const CHAR_CODE_A = 6545+const CHAR_CODE_F = 7046+const CHAR_CODE_a = 9747+const CHAR_CODE_f = 10248+const CHAR_CODE_DOT = 4649+const CHAR_CODE_COLON = 5850+const CHAR_CODE_PERCENT = 3751 52 /**53 * Distinct Remote Addr54 * @param remoteAddr Remote Addr7 unmodified lines62 return 'IPv6'63 }64 }65 66+const createInvalidIPAddressError = (message: string): InvalidIPAddressError => {67+ const error = new TypeError(message) as InvalidIPAddressError68+ error.code = INVALID_IP_ADDRESS_ERROR_CODE69+ return error70+}71+72+const throwInvalidIPv4Address = (ipv4: string): never => {73+ throw createInvalidIPAddressError(`Invalid IPv4 address: ${ipv4}`)74+}75+76+const throwInvalidIPv6Address = (ipv6: string): never => {77+ throw createInvalidIPAddressError(`Invalid IPv6 address: ${ipv6}`)78+}79+80+const parseIPv4ToBinary = (81+ ipv4: string,82+ start: number,83+ end: number,84+ onInvalid: () => never85+): bigint => {86+ let result = 0n87+ let octets = 088+ let octet = 089+ let digits = 090+ let firstDigit = 091+92+ for (let i = start; i <= end; i++) {93+ const code = i < end ? ipv4.charCodeAt(i) : CHAR_CODE_DOT94+ if (code >= CHAR_CODE_0 && code <= CHAR_CODE_9) {95+ if (digits === 0) {96+ firstDigit = code97+ } else if (firstDigit === CHAR_CODE_0) {98+ onInvalid()99+ }100+ octet = octet * 10 + code - CHAR_CODE_0101+ if (octet > 255) {102+ onInvalid()103+ }104+ digits++105+ continue106+ }107+108+ if (code !== CHAR_CODE_DOT || digits === 0 || octets === 4) {109+ onInvalid()110+ }111+112+ result = (result << 8n) + BigInt(octet)113+ octets++114+ octet = 0115+ digits = 0116+ }117+118+ if (octets !== 4) {119+ onInvalid()120+ }121+122+ return result123+}124+125+const parseIPv6HexCode = (code: number): number => {126+ if (code >= CHAR_CODE_0 && code <= CHAR_CODE_9) {127+ return code - CHAR_CODE_0128+ }129+ if (code >= CHAR_CODE_A && code <= CHAR_CODE_F) {130+ return code - CHAR_CODE_A + 10131+ }132+ if (code >= CHAR_CODE_a && code <= CHAR_CODE_f) {133+ return code - CHAR_CODE_a + 10134+ }135+ return -1136+}137+138+const isIPv6LinkLocal = (ipv6binary: bigint): boolean => ipv6binary >> 118n === 0x3fan139+140 /**141 * Convert IPv4 to Uint8Array142 * @param ipv4 IPv4 Address143 * @returns BigInt144 */145 export const convertIPv4ToBinary = (ipv4: string): bigint => {59- const parts = ipv4.split('.')60- let result = 0n61- for (let i = 0; i < 4; i++) {62- result <<= 8n63- result += BigInt(parts[i])64- }65- return result146+ return parseIPv4ToBinary(ipv4, 0, ipv4.length, () => throwInvalidIPv4Address(ipv4))147 }148 149 /**150 * Convert IPv6 to Uint8Array151 * @param ipv6 IPv6 Address152 * @returns BigInt153 */154 export const convertIPv6ToBinary = (ipv6: string): bigint => {74- const sections = expandIPv6(ipv6).split(':')155+ const length = ipv6.length156+ const sections: number[] = []157+ let hasZoneId = false158+ let compressAt = -1159+ let index = 0160+161+ if (length === 0) {162+ throwInvalidIPv6Address(ipv6)163+ }164+165+ while (index < length) {166+ if (sections.length > 8) {167+ throwInvalidIPv6Address(ipv6)168+ }169+170+ let code = ipv6.charCodeAt(index)171+172+ if (code === CHAR_CODE_PERCENT) {173+ if (index + 1 === length) {174+ throwInvalidIPv6Address(ipv6)175+ }176+ hasZoneId = true177+ break178+ }179+180+ if (code === CHAR_CODE_COLON) {181+ if (index + 1 < length && ipv6.charCodeAt(index + 1) === CHAR_CODE_COLON) {182+ if (compressAt !== -1) {183+ throwInvalidIPv6Address(ipv6)184+ }185+ compressAt = sections.length186+ index += 2187+ continue188+ }189+ throwInvalidIPv6Address(ipv6)190+ }191+192+ let value = 0193+ let digits = 0194+ const sectionStart = index195+196+ while (index < length) {197+ code = ipv6.charCodeAt(index)198+ const hex = parseIPv6HexCode(code)199+ if (hex === -1) {200+ break201+ }202+ if (digits === 4) {203+ throwInvalidIPv6Address(ipv6)204+ }205+ value = (value << 4) | hex206+ digits++207+ index++208+ }209+210+ if (index < length && ipv6.charCodeAt(index) === CHAR_CODE_DOT) {211+ let ipv4End = length212+ for (let i = index; i < length; i++) {213+ if (ipv6.charCodeAt(i) === CHAR_CODE_PERCENT) {214+ if (i + 1 === length) {215+ throwInvalidIPv6Address(ipv6)216+ }217+ hasZoneId = true218+ ipv4End = i219+ break220+ }221+ }222+ const ipv4 = parseIPv4ToBinary(ipv6, sectionStart, ipv4End, () =>223+ throwInvalidIPv6Address(ipv6)224+ )225+ sections.push(Number((ipv4 >> 16n) & 0xffffn), Number(ipv4 & 0xffffn))226+ index = length227+ break228+ }229+230+ if (digits === 0) {231+ throwInvalidIPv6Address(ipv6)232+ }233+234+ sections.push(value)235+236+ if (index === length) {237+ break238+ }239+240+ code = ipv6.charCodeAt(index)241+ if (code === CHAR_CODE_PERCENT) {242+ if (index + 1 === length) {243+ throwInvalidIPv6Address(ipv6)244+ }245+ hasZoneId = true246+ break247+ }248+249+ if (code !== CHAR_CODE_COLON) {250+ throwInvalidIPv6Address(ipv6)251+ }252+253+ if (index + 1 < length && ipv6.charCodeAt(index + 1) === CHAR_CODE_COLON) {254+ if (compressAt !== -1) {255+ throwInvalidIPv6Address(ipv6)256+ }257+ compressAt = sections.length258+ index += 2259+ continue260+ }261+262+ index++263+ if (index === length) {264+ throwInvalidIPv6Address(ipv6)265+ }266+ }267+268+ if (compressAt === -1 ? sections.length !== 8 : sections.length >= 8) {269+ throwInvalidIPv6Address(ipv6)270+ }271+272 let result = 0n273+ const zeros = compressAt === -1 ? 0 : 8 - sections.length274+ const firstSectionEnd = compressAt === -1 ? sections.length : compressAt76- for (let i = 0; i < 8; i++) {275+ for (let i = 0; i < firstSectionEnd; i++) {276 result <<= 16n78- result += BigInt(parseInt(sections[i], 16))277+ result += BigInt(sections[i])278 }279+ for (let i = 0; i < zeros; i++) {280+ result <<= 16n281+ }282+ for (let i = firstSectionEnd; i < sections.length; i++) {283+ result <<= 16n284+ result += BigInt(sections[i])285+ }286+ if (hasZoneId && !isIPv6LinkLocal(result)) {287+ throwInvalidIPv6Address(ipv6)288+ }289 return result290 }291 292 /**71 unmodified lines