fix(accept): replace regex split to mitigate ReDoS (#4758)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(accept): replace regex split to mitigate ReDoS * test(accept): cover escaped quote and backslash parsing paths * fix(accept): handle quoted params and comma safely * refactor: improve accept header parsing ---------
authored by EdamAmex · committed by GitHub · parent 18cc595 · Browse files · 2 files·+328 added−45 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Taku Amano <taku@taaas.jp>
Diff stats
2 files+328 added−45 removed
- tests:+107 added−4 removed
- other:+221 added−41 removed
Provenance
- Commit
5086956- Tree
6139c7f- Author
EdamAmex <121654029+EdamAme-x@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
18cc595
2 files changed+328 added−45 removed
modified:src/utils/accept.test.ts+107 added-4 removed
15 unmodified lines16 expect(parseAccept(undefined as any)).toEqual([])17 // eslint-disable-next-line @typescript-eslint/no-explicit-any18 expect(parseAccept(null as any)).toEqual([])19 })20+21+ test('handles whitespace-only header', () => {22+ expect(parseAccept(' ')).toEqual([])23+ expect(parseAccept(' \t\n ')).toEqual([])24+ })25 })26 27 describe('Quality Values', () => {28 test('handles extreme q values', () => {21 unmodified lines50 const header = 'type;a=1;b="2";c=\'3\';d="semi;colon";e="nested"quoted""'51 const result = parseAccept(header)52 expect(result[0].params).toEqual({53 a: '1',49- b: '"2"',50-54+ b: '2',55 c: "'3'",52- d: '"semi;colon"',53- e: '"nested"quoted""',56+ d: 'semi;colon',57 })58 })59 60 test('handles malformed parameters', () => {46 unmodified lines107 const header = '\n\t a \t\n ; \n\t q=0.9 \t\n , \n\t b \t\n'108 const result = parseAccept(header)109 expect(result.map((x) => x.type)).toEqual(['b', 'a'])110 })111+112+ test('handles comma inside quoted parameter value', () => {113+ const header = 'text/plain;meta="a,b";q=0.8,application/json;q=0.7'114+ const result = parseAccept(header)115+ expect(result).toEqual([116+ {117+ type: 'text/plain',118+ params: {119+ meta: 'a,b',120+ q: '0.8',121+ },122+ q: 0.8,123+ },124+ {125+ type: 'application/json',126+ params: {127+ q: '0.7',128+ },129+ q: 0.7,130+ },131+ ])132+ })133+134+ test('handles escaped quote and semicolon inside quoted parameter', () => {135+ const header = 'text/plain;meta="a\\\";b";q=0.5'136+ const result = parseAccept(header)137+ expect(result).toEqual([138+ {139+ type: 'text/plain',140+ params: {141+ meta: 'a";b',142+ q: '0.5',143+ },144+ q: 0.5,145+ },146+ ])147+ })148+149+ test('handles escaped character inside quoted parameter', () => {150+ const header = 'text/plain;meta="a\\\\z;c";q=0.3'151+ const result = parseAccept(header)152+ expect(result).toEqual([153+ {154+ type: 'text/plain',155+ params: {156+ meta: 'a\\z;c',157+ q: '0.3',158+ },159+ q: 0.3,160+ },161+ ])162+ })163+164+ test('skips invalid param without swallowing next media type', () => {165+ const header = 'a;foo, b;q=0.5'166+ const result = parseAccept(header)167+ expect(result).toEqual([168+ { type: 'a', params: {}, q: 1 },169+ { type: 'b', params: { q: '0.5' }, q: 0.5 },170+ ])171+ })172+173+ test('skips malformed quoted param tail without creating bogus media type', () => {174+ const header = 'a;foo="x"bar,b'175+ const result = parseAccept(header)176+ expect(result).toEqual([177+ { type: 'a', params: {}, q: 1 },178+ { type: 'b', params: {}, q: 1 },179+ ])180+ })181+182+ test('parses params after quoted value with trailing whitespace', () => {183+ const header = 'a;foo="x" ;q=0.5,b;q=0.4'184+ const result = parseAccept(header)185+ expect(result).toEqual([186+ { type: 'a', params: { foo: 'x', q: '0.5' }, q: 0.5 },187+ { type: 'b', params: { q: '0.4' }, q: 0.4 },188+ ])189+ })190+191+ test('handles quoted param followed immediately by comma', () => {192+ const header = 'a;foo="x",b'193+ const result = parseAccept(header)194+ expect(result).toEqual([195+ { type: 'a', params: { foo: 'x' }, q: 1 },196+ { type: 'b', params: {}, q: 1 },197+ ])198+ })199+200+ test('skips empty media type that starts with semicolon', () => {201+ const header = ';q=0.5,b;q=0.4'202+ const result = parseAccept(header)203+ expect(result).toEqual([{ type: 'b', params: { q: '0.4' }, q: 0.4 }])204+ })205 })206 207 describe('Security Cases', () => {208 test('handles potential injection patterns', () => {8 unmodified lines217 expect(() => parseAccept(header)).not.toThrow()218 })219 })220 221+ test('handles many semicolons with an unbalanced quote', () => {222+ const header = `text/plain;${'a;'.repeat(8000)}"`223+ const result = parseAccept(header)224+ expect(result[0].type).toBe('text/plain')225+ })226+227 test('handles extremely large input', () => {228 const header = 'a;q=0.9,'.repeat(100000)229 expect(() => parseAccept(header)).not.toThrow()230 })31 unmodified linesmodified:src/utils/accept.ts+221 added-41 removed
2 unmodified lines345678910111213147891011121314151617181917202122232425262728291920212223303132333435363738394041424344252627282930313233454647484950515253545556575859606162636465363766676869707172737475767778798081828384858687888990919293949596399798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571584243444546159160161162163164165166167168169170171172173174175176177178179180181182183184484918518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224319 unmodified lines26326426526679808182838485862 unmodified lines params: Record<string, string> q: number}
/** * Parse an Accept header into an array of objects with type, parameters, and quality score. * @param acceptHeader The Accept header string * @returns An array of parsed Accept values */export const parseAccept = (acceptHeader: string): Accept[] => { if (!acceptHeader) { return []const isWhitespace = (char: number): boolean => char === 32 || char === 9 || char === 10 || char === 13
const consumeWhitespace = (acceptHeader: string, startIndex: number): number => { while (startIndex < acceptHeader.length) { if (!isWhitespace(acceptHeader.charCodeAt(startIndex))) { break } startIndex++ } return startIndex}
const acceptValues = acceptHeader.split(',').map((value, index) => ({ value, index }))const ignoreTrailingWhitespace = (acceptHeader: string, startIndex: number): number => { while (startIndex > 0) { if (!isWhitespace(acceptHeader.charCodeAt(startIndex - 1))) { break } startIndex-- } return startIndex}
return acceptValues .map(parseAcceptValue) .filter((item): item is Accept & { index: number } => Boolean(item)) .sort(sortByQualityAndIndex) .map(({ type, params, q }) => ({ type, params, q }))const skipInvalidParam = (acceptHeader: string, startIndex: number): [number, boolean] => { while (startIndex < acceptHeader.length) { const char = acceptHeader.charCodeAt(startIndex) if (char === 59) { // ';' => next param return [startIndex + 1, true] } if (char === 44) { // ',' => next accept value return [startIndex + 1, false] } startIndex++ } return [startIndex, false]}const parseAcceptValueRegex = /;(?=(?:(?:[^"]*"){2})*[^"]*$)/const parseAcceptValue = ({ value, index }: { value: string; index: number }) => { const parts = value .trim() .split(parseAcceptValueRegex) .map((s) => s.trim()) const type = parts[0] if (!type) { return null
const skipInvalidAcceptValue = (acceptHeader: string, startIndex: number): number => { let i = startIndex let inQuotes = false while (i < acceptHeader.length) { const char = acceptHeader.charCodeAt(i) if (inQuotes && char === 92) { // '\' => escape i++ } else if (char === 34) { // '"' => toggle quotes inQuotes = !inQuotes } else if (!inQuotes && char === 44) { // ',' => next accept value return i + 1 } i++ } return i}
const params = parseParams(parts.slice(1)) const q = parseQuality(params.q)const getNextParam = ( acceptHeader: string, startIndex: number): [number, string | undefined, string | undefined, boolean] => { startIndex = consumeWhitespace(acceptHeader, startIndex) let i = startIndex let key: string | undefined let value: string | undefined let hasNext = false while (i < acceptHeader.length) { const char = acceptHeader.charCodeAt(i) if (char === 61) { // '=' => end of key key = acceptHeader.slice(startIndex, ignoreTrailingWhitespace(acceptHeader, i)) i++ break } if (char === 59) { // ';' => invalid empty param, continue parsing params return [i + 1, undefined, undefined, true] } if (char === 44) { // ',' => invalid empty param, move to next accept value return [i + 1, undefined, undefined, false] } i++ } if (key === undefined) { return [i, undefined, undefined, false] }
return { type, params, q, index } i = consumeWhitespace(acceptHeader, i) if (acceptHeader.charCodeAt(i) === 61) { // '=' is invalid as a value, so return undefined const skipResult = skipInvalidParam(acceptHeader, i + 1) return [skipResult[0], key, undefined, skipResult[1]] }
let inQuotes = false const paramStartIndex = i while (i < acceptHeader.length) { const char = acceptHeader.charCodeAt(i)
if (inQuotes && char === 92) { // '\' => escape i++ } else if (char === 34) { // '"' => start of quotes if (inQuotes) { let nextIndex = consumeWhitespace(acceptHeader, i + 1) const nextChar = acceptHeader.charCodeAt(nextIndex) if (nextIndex < acceptHeader.length && !(nextChar === 59 || nextChar === 44)) { // not ';' or ',' => invalid trailing chars const skipResult = skipInvalidParam(acceptHeader, nextIndex) return [skipResult[0], key, undefined, skipResult[1]] } value = acceptHeader.slice(paramStartIndex + 1, i) if (value.includes('\\')) { value = value.replace(/\\(.)/g, '$1') } if (nextChar === 44) { // ',' => end of accept value return [nextIndex + 1, key, value, false] } if (nextChar === 59) { // ';' => has next param hasNext = true nextIndex++ } i = nextIndex break } inQuotes = true } else if (!inQuotes && (char === 59 || char === 44)) { // ';' or ',' => end of value value = acceptHeader.slice(paramStartIndex, ignoreTrailingWhitespace(acceptHeader, i)) if (char === 59) { // ';' => has next param hasNext = true } i++ break } i++ } return [ i, key, value ?? acceptHeader.slice(paramStartIndex, ignoreTrailingWhitespace(acceptHeader, i)), hasNext, ]}
const parseParams = (paramParts: string[]): Record<string, string> => { return paramParts.reduce<Record<string, string>>((acc, param) => { const [key, val] = param.split('=').map((s) => s.trim()) if (key && val) { acc[key] = valconst getNextAcceptValue = ( acceptHeader: string, startIndex: number): [number, Accept | undefined] => { const accept: Accept = { type: '', params: {}, q: 1, } startIndex = consumeWhitespace(acceptHeader, startIndex) let i = startIndex while (i < acceptHeader.length) { const char = acceptHeader.charCodeAt(i) if (char === 59 || char === 44) { // ';' or ',' => end of type accept.type = acceptHeader.slice(startIndex, ignoreTrailingWhitespace(acceptHeader, i)) i++ if (char === 44) { // ',' => end of value return [i, accept.type ? accept : undefined] } if (!accept.type) { return [skipInvalidAcceptValue(acceptHeader, i), undefined] } break // parse params } return acc }, {}) i++ } if (!accept.type) { accept.type = acceptHeader.slice( startIndex, ignoreTrailingWhitespace(acceptHeader, acceptHeader.length) ) return [acceptHeader.length, accept.type ? accept : undefined] }
let param: string | undefined let value: string | undefined let hasNext: boolean while (i < acceptHeader.length) { ;[i, param, value, hasNext] = getNextParam(acceptHeader, i) if (param && value) { accept.params[param] = value } if (!hasNext) { break } }
return [i, accept] as [number, Accept]}
export const parseAccept = (acceptHeader: string): Accept[] => { if (!acceptHeader) { return [] }
const values: Accept[] = [] let i = 0 let accept: Accept | undefined let requiresSort = false // in many cases, accept values are already sorted by quality (e.g. "text/html, application/json;q=0.9, */*;q=0.8") let lastAccept: Accept | undefined while (i < acceptHeader.length) { ;[i, accept] = getNextAcceptValue(acceptHeader, i) if (accept) { accept.q = parseQuality(accept.params.q) values.push(accept) if (lastAccept && lastAccept.q < accept.q) { // find higher quality accept value, so we need to sort requiresSort = true } lastAccept = accept } } if (requiresSort) { values.sort((a, b) => b.q - a.q) }
return values}
const parseQuality = (qVal?: string): number => { if (qVal === undefined) { return 1 }19 unmodified lines }
return num}
const sortByQualityAndIndex = (a: Accept & { index: number }, b: Accept & { index: number }) => { const qDiff = b.q - a.q if (qDiff !== 0) { return qDiff } return a.index - b.index}