cookie.test.ts
This file
Path
src/utils/cookie.test.ts
460 lines 路 19.6 KiB 路 TypeScript
Last changed by
fix(cookie): allow parsing signed cookies with empty string values (#5246)Nanasibefore adoption241ae4c
History of this fileTake it
1import type { Cookie, SignedCookie } from './cookie'2import { parse, parseSigned, serialize, serializeSigned } from './cookie'34describe('Parse cookie', () => {5 it('Should parse cookies', () => {6 const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry '7 const cookie: Cookie = parse(cookieString)8 expect(cookie['yummy_cookie']).toBe('choco')9 expect(cookie['tasty_cookie']).toBe('strawberry')10 })1112 it('Should trim only SP and HTAB around cookie pairs', () => {13 const cookieString = '\tyummy_cookie=choco;\t tasty_cookie = strawberry \t'14 const cookie: Cookie = parse(cookieString)15 expect(cookie['yummy_cookie']).toBe('choco')16 expect(cookie['tasty_cookie']).toBe('strawberry')17 })1819 it('Should parse quoted cookie values', () => {20 const cookieString =21 'yummy_cookie="choco"; tasty_cookie = " strawberry " ; best_cookie="%20sugar%20";'22 const cookie: Cookie = parse(cookieString)23 expect(cookie['yummy_cookie']).toBe('choco')24 expect(cookie['tasty_cookie']).toBe(' strawberry ')25 expect(cookie['best_cookie']).toBe(' sugar ')26 })2728 it('Should not throw a URIError when parsing an invalid string', () => {29 const cookieString = 'yummy_cookie="choco%2";'30 const cookie: Cookie = parse(cookieString)31 expect(cookie['yummy_cookie']).toBe('choco%2')32 })3334 it('Should parse empty cookies', () => {35 const cookie: Cookie = parse('')36 expect(Object.keys(cookie).length).toBe(0)37 })3839 it('Should parse one cookie specified by name', () => {40 const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry '41 const cookie: Cookie = parse(cookieString, 'yummy_cookie')42 expect(cookie['yummy_cookie']).toBe('choco')43 expect(cookie['tasty_cookie']).toBeUndefined()44 })4546 it('Should parse one cookie specified by name even if it is not found', () => {47 const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry '48 const cookie: Cookie = parse(cookieString, 'no_such_cookie')49 expect(cookie['yummy_cookie']).toBeUndefined()50 expect(cookie['tasty_cookie']).toBeUndefined()51 expect(cookie['no_such_cookie']).toBeUndefined()52 })5354 it('Should parse cookies with no value', () => {55 const cookieString = 'yummy_cookie=; tasty_cookie = ; best_cookie= ; last_cookie=""'56 const cookie: Cookie = parse(cookieString)57 expect(cookie['yummy_cookie']).toBe('')58 expect(cookie['tasty_cookie']).toBe('')59 expect(cookie['best_cookie']).toBe('')60 expect(cookie['last_cookie']).toBe('')61 })6263 it('Should parse cookies but not process signed cookies', () => {64 // also contains another cookie with a '.' in its value to test it is not misinterpreted as signed cookie65 const cookieString =66 'yummy_cookie=choco; tasty_cookie = strawberry.I9qAeGQOvWjCEJgRPmrw90JjYpnnX2C9zoOiGSxh1Ig%3D; great_cookie=rating3.5; best_cookie=sugar.valueShapedLikeASignatureButIsNotASignature%3D'67 const cookie: Cookie = parse(cookieString)68 expect(cookie['yummy_cookie']).toBe('choco')69 expect(cookie['tasty_cookie']).toBe('strawberry.I9qAeGQOvWjCEJgRPmrw90JjYpnnX2C9zoOiGSxh1Ig=')70 expect(cookie['great_cookie']).toBe('rating3.5')71 expect(cookie['best_cookie']).toBe('sugar.valueShapedLikeASignatureButIsNotASignature=')72 })7374 it('Should ignore invalid cookie names', () => {75 const cookieString = 'yummy_cookie=choco; tasty cookie=strawberry; best_cookie\\=sugar; =ng'76 const cookie: Cookie = parse(cookieString)77 expect(cookie['yummy_cookie']).toBe('choco')78 expect(cookie['tasty cookie']).toBeUndefined()79 expect(cookie['best_cookie\\']).toBeUndefined()80 expect(cookie['']).toBeUndefined()81 })8283 it('Should parse cookies whose names are not RFC 6265 tokens', () => {84 const cookieString =85 'paraglide:lang=en; CognitoIdentityServiceProvider.abc.user@example.com.idToken=token; round(brackets)=ok; square[brackets]=ok; curly{brackets}=ok'86 const cookie: Cookie = parse(cookieString)87 expect(cookie['paraglide:lang']).toBe('en')88 expect(cookie['CognitoIdentityServiceProvider.abc.user@example.com.idToken']).toBe('token')89 expect(cookie['round(brackets)']).toBe('ok')90 expect(cookie['square[brackets]']).toBe('ok')91 expect(cookie['curly{brackets}']).toBe('ok')92 })9394 it('Should parse one cookie specified by a name that is not an RFC 6265 token', () => {95 const cookieString = 'paraglide:lang=en; test=ok'96 const cookie: Cookie = parse(cookieString, 'paraglide:lang')97 expect(cookie['paraglide:lang']).toBe('en')98 expect(cookie['test']).toBeUndefined()99 })100101 it('Should ignore cookie names containing non-ASCII or control characters', () => {102 const cookieString = 'yummy_cookie=choco; 銈儍銈兗=strawberry; bad\x01name=sugar'103 const cookie: Cookie = parse(cookieString)104 expect(cookie['yummy_cookie']).toBe('choco')105 expect(cookie['銈儍銈兗']).toBeUndefined()106 expect(cookie['bad\x01name']).toBeUndefined()107 })108109 it('Should ignore invalid cookie values', () => {110 const cookieString = 'yummy_cookie=choco\\nchip; tasty_cookie=strawberry; best_cookie="sugar'111 const cookie: Cookie = parse(cookieString)112 expect(cookie['yummy_cookie']).toBeUndefined()113 expect(cookie['tasty_cookie']).toBe('strawberry')114 expect(cookie['best_cookie\\']).toBeUndefined()115 })116117 it('Should ignore NBSP-prefixed cookie names when parsing one cookie by name', () => {118 const cookieString = '\u00a0dummy-cookie=evil; dummy-cookie=victim'119 const cookie: Cookie = parse(cookieString, 'dummy-cookie')120 expect(cookie['dummy-cookie']).toBe('victim')121 })122123 it('Should not collapse NBSP-prefixed cookie names when parsing all cookies', () => {124 const cookieString = 'dummy-cookie=victim; \u00a0dummy-cookie=evil'125 const cookie: Cookie = parse(cookieString)126 expect(cookie['dummy-cookie']).toBe('victim')127 expect(cookie['\u00a0dummy-cookie']).toBeUndefined()128 })129130 it('Should return the first value for duplicate cookie names', () => {131 const cookieString = 'a=first; a=last'132 const cookie: Cookie = parse(cookieString)133 expect(cookie['a']).toBe('first')134 })135136 it('Should return the first value for duplicate cookie names when parsed by name', () => {137 const cookieString = 'a=first; a=last'138 const cookie: Cookie = parse(cookieString, 'a')139 expect(cookie['a']).toBe('first')140 })141142 it('Should return consistent values between parse() and parse(name) for duplicates', () => {143 const cookieString = 'session=legit; other=x; session=evil'144 expect(parse(cookieString)['session']).toBe(parse(cookieString, 'session')['session'])145 })146147 it('Should parse cookies whose names collide with Object.prototype properties', () => {148 const cookieString = 'toString=foo; hasOwnProperty=bar; constructor=baz'149 const cookie: Cookie = parse(cookieString)150 expect(cookie['toString']).toBe('foo')151 expect(cookie['hasOwnProperty']).toBe('bar')152 expect(cookie['constructor']).toBe('baz')153 })154155 it('Should parse a cookie whose name collides with Object.prototype when parsed by name', () => {156 const cookieString = 'toString=foo'157 const cookie: Cookie = parse(cookieString, 'toString')158 expect(cookie['toString']).toBe('foo')159 })160161 it('Should keep first-wins behavior for cookies whose names collide with Object.prototype', () => {162 const cookieString = 'toString=first; toString=last'163 const cookie: Cookie = parse(cookieString)164 expect(cookie['toString']).toBe('first')165 })166167 it('Should parse signed cookies', async () => {168 const secret = 'secret ingredient'169 const cookieString =170 'yummy_cookie=choco.UdFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D; tasty_cookie = strawberry.I9qAeGQOvWjCEJgRPmrw90JjYpnnX2C9zoOiGSxh1Ig%3D'171 const cookie: SignedCookie = await parseSigned(cookieString, secret)172 expect(cookie['yummy_cookie']).toBe('choco')173 expect(cookie['tasty_cookie']).toBe('strawberry')174 })175176 it('Should parse signed cookies with binary secret', async () => {177 const secret = new Uint8Array([178 172, 142, 204, 63, 210, 136, 58, 143, 25, 18, 159, 16, 161, 34, 94,179 ])180 const cookieString =181 'yummy_cookie=choco.8Km4IwZETZdwiOfrT7KgYjKXwiO98XIkms0tOtRa2TA%3D; tasty_cookie = strawberry.TbV33P%2Bi1K0JTxMzNYq7FV9fB4s2VlQcBCBFDxTrUSg%3D'182 const cookie: SignedCookie = await parseSigned(cookieString, secret)183 expect(cookie['yummy_cookie']).toBe('choco')184 expect(cookie['tasty_cookie']).toBe('strawberry')185 })186187 it('Should parse signed cookies containing the signature separator', async () => {188 const secret = 'secret ingredient'189 const cookieString = 'yummy_cookie=choco.chip.2%2FJA0c68Y3zm0DvSvHyR6IRysDWmHW0LfoaC0AkyOpw%3D'190 const cookie: SignedCookie = await parseSigned(cookieString, secret)191 expect(cookie['yummy_cookie']).toBe('choco.chip')192 })193194 it('Should parse signed cookies and return "false" for wrong signature', async () => {195 const secret = 'secret ingredient'196 // tasty_cookie has invalid signature197 const cookieString =198 'yummy_cookie=choco.UdFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D; tasty_cookie = strawberry.LAa7RX43t2vCrLNcKmNG65H41OkyV02sraRPuY5RuVg%3D'199 const cookie: SignedCookie = await parseSigned(cookieString, secret)200 expect(cookie['yummy_cookie']).toBe('choco')201 expect(cookie['tasty_cookie']).toBe(false)202 })203204 it('Should parse signed cookie with empty string value', async () => {205 const secret = 'secret ingredient'206 const cookieString = await serializeSigned('empty_cookie', '', secret)207 const cookie: SignedCookie = await parseSigned(cookieString, secret)208 expect(cookie['empty_cookie']).toBe('')209 })210211 it('Should parse signed cookies and return "false" for corrupt signature', async () => {212 const secret = 'secret ingredient'213 // yummy_cookie has corrupt signature (i.e. invalid base64 encoding)214 // best_cookie has a shape that matches the signature format but isn't actually a signature215 const cookieString =216 'yummy_cookie=choco.?dFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D; tasty_cookie = strawberry.I9qAeGQOvWjCEJgRPmrw90JjYpnnX2C9zoOiGSxh1Ig%3D; best_cookie=sugar.valueShapedLikeASignatureButIsNotASignature%3D'217 const cookie: SignedCookie = await parseSigned(cookieString, secret)218 expect(cookie['yummy_cookie']).toBe(false)219 expect(cookie['tasty_cookie']).toBe('strawberry')220 expect(cookie['best_cookie']).toBe(false)221 })222223 it('Should parse one signed cookie specified by name', async () => {224 const secret = 'secret ingredient'225 const cookieString =226 'yummy_cookie=choco.UdFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D; tasty_cookie = strawberry.I9qAeGQOvWjCEJgRPmrw90JjYpnnX2C9zoOiGSxh1Ig%3D'227 const cookie: SignedCookie = await parseSigned(cookieString, secret, 'tasty_cookie')228 expect(cookie['yummy_cookie']).toBeUndefined()229 expect(cookie['tasty_cookie']).toBe('strawberry')230 })231232 it('Should parse one signed cookie specified by name and return "false" for wrong signature', async () => {233 const secret = 'secret ingredient'234 // tasty_cookie has invalid signature235 const cookieString =236 'yummy_cookie=choco.UdFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D; tasty_cookie = strawberry.LAa7RX43t2vCrLNcKmNG65H41OkyV02sraRPuY5RuVg%3D'237 const cookie: SignedCookie = await parseSigned(cookieString, secret, 'tasty_cookie')238 expect(cookie['yummy_cookie']).toBeUndefined()239 expect(cookie['tasty_cookie']).toBe(false)240 })241242 it('Should parse signed cookies and ignore regular cookies', async () => {243 const secret = 'secret ingredient'244 // also contains another cookie with a '.' in its value to test it is not misinterpreted as signed cookie245 const cookieString =246 'yummy_cookie=choco; tasty_cookie = strawberry.I9qAeGQOvWjCEJgRPmrw90JjYpnnX2C9zoOiGSxh1Ig%3D; great_cookie=rating3.5'247 const cookie: SignedCookie = await parseSigned(cookieString, secret)248 expect(cookie['yummy_cookie']).toBeUndefined()249 expect(cookie['tasty_cookie']).toBe('strawberry')250 expect(cookie['great_cookie']).toBeUndefined()251 })252253 it('Should ignore NBSP-prefixed signed cookie names when parsing one cookie by name', async () => {254 const secret = 'secret ingredient'255 const cookieString =256 '\u00a0dummy-cookie=evil.UdFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D; dummy-cookie=choco.UdFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D'257 const cookie: SignedCookie = await parseSigned(cookieString, secret, 'dummy-cookie')258 expect(cookie['dummy-cookie']).toBe('choco')259 })260261 it('Should return the first signed cookie when there are duplicate names', async () => {262 const secret = 'secret ingredient'263 const cookieString =264 'yummy_cookie=choco.UdFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D; yummy_cookie=strawberry.I9qAeGQOvWjCEJgRPmrw90JjYpnnX2C9zoOiGSxh1Ig%3D'265 const cookie: SignedCookie = await parseSigned(cookieString, secret)266 expect(cookie['yummy_cookie']).toBe('choco')267 })268269 it('Should parse signed cookies whose names collide with Object.prototype properties', async () => {270 const secret = 'secret ingredient'271 const cookieString = 'toString=choco.UdFR2rBpS1GsHfGlUiYyMIdqxqwuEgplyQIgTJgpGWY%3D'272 const cookie: SignedCookie = await parseSigned(cookieString, secret)273 expect(cookie['toString']).toBe('choco')274 })275})276277describe('Set cookie', () => {278 it('Should serialize cookie', () => {279 const serialized = serialize('delicious_cookie', 'macha')280 expect(serialized).toBe('delicious_cookie=macha')281 })282283 it('Should serialize cookie with all options', () => {284 const serialized = serialize('__Secure-great_cookie', 'banana', {285 path: '/',286 secure: true,287 domain: 'example.com',288 httpOnly: true,289 maxAge: 1000,290 expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),291 sameSite: 'Strict',292 priority: 'High',293 partitioned: true,294 })295 expect(serialized).toBe(296 '__Secure-great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Priority=High; Partitioned'297 )298 })299300 it('Should serialize __Host- cookie with all valid options', () => {301 const serialized = serialize('__Host-great_cookie', 'banana', {302 path: '/',303 secure: true,304 httpOnly: true,305 maxAge: 1000,306 expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),307 sameSite: 'Strict',308 priority: 'High',309 partitioned: true,310 })311 expect(serialized).toBe(312 '__Host-great_cookie=banana; Max-Age=1000; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Priority=High; Partitioned'313 )314 })315316 it('Should serialize a signed cookie', async () => {317 const secret = 'secret chocolate chips'318 const serialized = await serializeSigned('delicious_cookie', 'macha', secret)319 expect(serialized).toBe(320 'delicious_cookie=macha.diubJPY8O7hI1pLa42QSfkPiyDWQ0I4DnlACH%2FN2HaA%3D'321 )322 })323324 it('Should serialize signed cookie with all options', async () => {325 const secret = 'secret chocolate chips'326 const serialized = await serializeSigned('great_cookie', 'banana', secret, {327 path: '/',328 secure: true,329 domain: 'example.com',330 httpOnly: true,331 maxAge: 1000,332 expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),333 sameSite: 'Strict',334 priority: 'High',335 partitioned: true,336 })337 expect(serialized).toBe(338 'great_cookie=banana.hSo6gB7YT2db0WBiEAakEmh7dtwEL0DSp76G23WvHuQ%3D; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict; Priority=High; Partitioned'339 )340 })341342 it('Should serialize cookie with maxAge is 0', () => {343 const serialized = serialize('great_cookie', 'banana', {344 maxAge: 0,345 })346 expect(serialized).toBe('great_cookie=banana; Max-Age=0')347 })348349 it('Should serialize cookie with maxAge is -1', () => {350 const serialized = serialize('great_cookie', 'banana', {351 maxAge: -1,352 })353 expect(serialized).toBe('great_cookie=banana')354 })355356 it('Should throw Error cookie with maxAge grater than 400days', () => {357 expect(() => {358 serialize('great_cookie', 'banana', {359 maxAge: 3600 * 24 * 401,360 })361 }).toThrowError(362 'Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.'363 )364 })365366 it('Should throw Error cookie with expires grater than 400days', () => {367 const now = Date.now()368 const day401 = new Date(now + 1000 * 3600 * 24 * 401)369 expect(() => {370 serialize('great_cookie', 'banana', {371 expires: day401,372 })373 }).toThrowError(374 'Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.'375 )376 })377378 it('Should throw Error Partitioned cookie without Secure attributes', () => {379 expect(() => {380 serialize('great_cookie', 'banana', {381 partitioned: true,382 })383 }).toThrowError('Partitioned Cookie must have Secure attributes')384 })385386 it('Should throw Error cookie with domain, path, sameSite, or priority containing ";", "\\r", or "\\n"', () => {387 // domain388 expect(() => {389 serialize('great_cookie', 'banana', { domain: 'example.com;evil' })390 }).toThrowError('domain must not contain ";", "\\r", or "\\n"')391 expect(() => {392 serialize('great_cookie', 'banana', { domain: 'example.com\revil' })393 }).toThrowError('domain must not contain ";", "\\r", or "\\n"')394 expect(() => {395 serialize('great_cookie', 'banana', { domain: 'example.com\nevil' })396 }).toThrowError('domain must not contain ";", "\\r", or "\\n"')397398 // path399 expect(() => {400 serialize('great_cookie', 'banana', { path: '/;evil' })401 }).toThrowError('path must not contain ";", "\\r", or "\\n"')402 expect(() => {403 serialize('great_cookie', 'banana', { path: '/\revil' })404 }).toThrowError('path must not contain ";", "\\r", or "\\n"')405 expect(() => {406 serialize('great_cookie', 'banana', { path: '/\nevil' })407 }).toThrowError('path must not contain ";", "\\r", or "\\n"')408409 // sameSite410 expect(() => {411 serialize('great_cookie', 'banana', { sameSite: 'Strict;evil' as 'Strict' })412 }).toThrowError('sameSite must not contain ";", "\\r", or "\\n"')413 expect(() => {414 serialize('great_cookie', 'banana', { sameSite: 'Strict\revil' as 'Strict' })415 }).toThrowError('sameSite must not contain ";", "\\r", or "\\n"')416 expect(() => {417 serialize('great_cookie', 'banana', { sameSite: 'Strict\nevil' as 'Strict' })418 }).toThrowError('sameSite must not contain ";", "\\r", or "\\n"')419420 // priority421 expect(() => {422 serialize('great_cookie', 'banana', { priority: 'High;evil' as 'High' })423 }).toThrowError('priority must not contain ";", "\\r", or "\\n"')424 expect(() => {425 serialize('great_cookie', 'banana', { priority: 'High\revil' as 'High' })426 }).toThrowError('priority must not contain ";", "\\r", or "\\n"')427 expect(() => {428 serialize('great_cookie', 'banana', { priority: 'High\nevil' as 'High' })429 }).toThrowError('priority must not contain ";", "\\r", or "\\n"')430 })431432 it('Should throw Error for invalid cookie name', () => {433 expect(() => {434 serialize('legit\r\nX-Injected: evil', 'value')435 }).toThrowError('Invalid cookie name')436 expect(() => {437 serialize('bad;name', 'value')438 }).toThrowError('Invalid cookie name')439 expect(() => {440 serialize('bad=name', 'value')441 }).toThrowError('Invalid cookie name')442 })443444 it('Should serialize cookie with lowercase priority values', () => {445 const lowSerialized = serialize('test_cookie', 'value', {446 priority: 'low',447 })448 expect(lowSerialized).toBe('test_cookie=value; Priority=Low')449450 const mediumSerialized = serialize('test_cookie', 'value', {451 priority: 'medium',452 })453 expect(mediumSerialized).toBe('test_cookie=value; Priority=Medium')454455 const highSerialized = serialize('test_cookie', 'value', {456 priority: 'high',457 })458 expect(highSerialized).toBe('test_cookie=value; Priority=High')459 })460})