-
-
Notifications
You must be signed in to change notification settings - Fork 668
/
Copy pathindex.test.ts
642 lines (590 loc) · 24.7 KB
/
index.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
import { HttpResponse, http } from 'msw'
import { setupServer } from 'msw/node'
import { setSignedCookie } from '../../helper/cookie'
import { Hono } from '../../hono'
import { HTTPException } from '../../http-exception'
import { encodeBase64Url } from '../../utils/encode'
import { Jwt } from '../../utils/jwt'
import type { HonoJsonWebKey } from '../../utils/jwt/jws'
import { signing } from '../../utils/jwt/jws'
import { verifyFromJwks } from '../../utils/jwt/jwt'
import type { JWTPayload } from '../../utils/jwt/types'
import { utf8Encoder } from '../../utils/jwt/utf8'
import * as test_keys from './keys.test.json'
import { jwk } from '.'
const verify_keys = test_keys.public_keys
describe('JWK', () => {
const server = setupServer(
http.get('http://localhost/.well-known/jwks.json', () => {
return HttpResponse.json({ keys: verify_keys })
}),
http.get('http://localhost/.well-known/missing-jwks.json', () => {
return HttpResponse.json({})
}),
http.get('http://localhost/.well-known/bad-jwks.json', () => {
return HttpResponse.json({ keys: 'bad-keys' })
}),
http.get('http://localhost/.well-known/404-jwks.json', () => {
return HttpResponse.text('Not Found', { status: 404 })
})
)
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
describe('verifyFromJwks', () => {
it('Should throw error on missing options', async () => {
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
await expect(verifyFromJwks(credential, {})).rejects.toThrow(
'verifyFromJwks requires options for either "keys" or "jwks_uri" or both'
)
})
})
describe('Credentials in header', () => {
let handlerExecuted: boolean
beforeEach(() => {
handlerExecuted = false
})
const app = new Hono()
app.use('/auth-with-keys/*', jwk({ keys: verify_keys }))
app.use('/auth-with-keys-unicode/*', jwk({ keys: verify_keys }))
app.use('/auth-with-keys-nested/*', async (c, next) => {
const auth = jwk({ keys: verify_keys })
return auth(c, next)
})
app.use(
'/auth-with-keys-fn/*',
jwk({
keys: async () => {
const response = await fetch('http://localhost/.well-known/jwks.json')
const data = await response.json()
return data.keys
},
})
)
app.use(
'/auth-with-jwks_uri/*',
jwk({
jwks_uri: 'http://localhost/.well-known/jwks.json',
})
)
app.use(
'/auth-with-keys-and-jwks_uri/*',
jwk({
keys: verify_keys,
jwks_uri: 'http://localhost/.well-known/jwks.json',
})
)
app.use(
'/auth-with-missing-jwks_uri/*',
jwk({
jwks_uri: 'http://localhost/.well-known/missing-jwks.json',
})
)
app.use(
'/auth-with-404-jwks_uri/*',
jwk({
jwks_uri: 'http://localhost/.well-known/404-jwks.json',
})
)
app.use(
'/auth-with-bad-jwks_uri/*',
jwk({
jwks_uri: 'http://localhost/.well-known/bad-jwks.json',
})
)
app.get('/auth-with-keys/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
app.get('/auth-with-keys-unicode/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
app.get('/auth-with-keys-nested/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
app.get('/auth-with-keys-fn/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
app.get('/auth-with-jwks_uri/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
app.get('/auth-with-keys-and-jwks_uri/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
app.get('/auth-with-missing-jwks_uri/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
app.get('/auth-with-404-jwks_uri/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
app.get('/auth-with-bad-jwks_uri/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
it('Should throw an error if the middleware is missing both keys and jwks_uri (empty)', async () => {
expect(() => app.use('/auth-with-empty-middleware/*', jwk({}))).toThrow(
'JWK auth middleware requires options for either "keys" or "jwks_uri"'
)
})
it('Should throw an error when crypto.subtle is missing', async () => {
const subtleSpy = vi.spyOn(global.crypto, 'subtle', 'get').mockReturnValue({
importKey: undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
expect(() => app.use('/auth-with-bad-env/*', jwk({ keys: verify_keys }))).toThrow()
subtleSpy.mockRestore()
})
it('Should return a server error if options.jwks_uri returns a 404', async () => {
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request('http://localhost/auth-with-404-jwks_uri/a')
req.headers.set('Authorization', `Basic ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(500)
})
it('Should return a server error if the remotely fetched keys from options.jwks_uri are missing', async () => {
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request('http://localhost/auth-with-missing-jwks_uri/a')
req.headers.set('Authorization', `Basic ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(500)
})
it('Should return a server error if the remotely fetched keys from options.jwks_uri are malformed', async () => {
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request('http://localhost/auth-with-bad-jwks_uri/a')
req.headers.set('Authorization', `Basic ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(500)
})
it('Should not authorize requests with missing access token', async () => {
const req = new Request('http://localhost/auth-with-keys/a')
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
expect(await res.text()).toBe('Unauthorized')
expect(handlerExecuted).toBeFalsy()
})
it('Should authorize from a static array passed to options.keys (key 1)', async () => {
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request('http://localhost/auth-with-keys/a')
req.headers.set('Authorization', `Bearer ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ message: 'hello world' })
expect(handlerExecuted).toBeTruthy()
})
it('Should authorize from a static array passed to options.keys (key 2)', async () => {
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[1])
const req = new Request('http://localhost/auth-with-keys/a')
req.headers.set('Authorization', `Bearer ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ message: 'hello world' })
expect(handlerExecuted).toBeTruthy()
expect(res.status).toBe(200)
})
it('Should not authorize a token without header', async () => {
const encodeJwtPart = (part: unknown): string =>
encodeBase64Url(utf8Encoder.encode(JSON.stringify(part))).replace(/=/g, '')
const encodeSignaturePart = (buf: ArrayBufferLike): string =>
encodeBase64Url(buf).replace(/=/g, '')
const jwtSignWithoutHeader = async (payload: JWTPayload, privateKey: HonoJsonWebKey) => {
const encodedPayload = encodeJwtPart(payload)
const signaturePart = await signing(
privateKey,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
privateKey.alg as any,
utf8Encoder.encode(encodedPayload)
)
const signature = encodeSignaturePart(signaturePart)
return `${encodedPayload}.${signature}`
}
const credential = await jwtSignWithoutHeader(
{ message: 'hello world' },
test_keys.private_keys[1]
)
const req = new Request('http://localhost/auth-with-keys/a')
req.headers.set('Authorization', `Bearer ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
})
it('Should not authorize a token with missing "kid" in header', async () => {
const encodeJwtPart = (part: unknown): string =>
encodeBase64Url(utf8Encoder.encode(JSON.stringify(part))).replace(/=/g, '')
const encodeSignaturePart = (buf: ArrayBufferLike): string =>
encodeBase64Url(buf).replace(/=/g, '')
const jwtSignWithoutKid = async (payload: JWTPayload, privateKey: HonoJsonWebKey) => {
const encodedPayload = encodeJwtPart(payload)
const encodedHeader = encodeJwtPart({ alg: privateKey.alg, typ: 'JWT' })
const partialToken = `${encodedHeader}.${encodedPayload}`
const signaturePart = await signing(
privateKey,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
privateKey.alg as any,
utf8Encoder.encode(partialToken)
)
const signature = encodeSignaturePart(signaturePart)
return `${partialToken}.${signature}`
}
const credential = await jwtSignWithoutKid(
{ message: 'hello world' },
test_keys.private_keys[1]
)
const req = new Request('http://localhost/auth-with-keys/a')
req.headers.set('Authorization', `Bearer ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
})
it('Should not authorize a token with invalid "kid" in header', async () => {
const copy = structuredClone(test_keys.private_keys[1])
copy.kid = 'invalid-kid'
const credential = await Jwt.sign({ message: 'hello world' }, copy)
const req = new Request('http://localhost/auth-with-keys/a')
req.headers.set('Authorization', `Bearer ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
})
it('Should authorize with Unicode payload from a static array passed to options.keys', async () => {
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request('http://localhost/auth-with-keys-unicode/a')
req.headers.set('Authorization', `Basic ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ message: 'hello world' })
expect(handlerExecuted).toBeTruthy()
})
it('Should authorize from a function passed to options.keys', async () => {
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request('http://localhost/auth-with-keys-fn/a')
req.headers.set('Authorization', `Basic ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ message: 'hello world' })
expect(handlerExecuted).toBeTruthy()
})
it('Should authorize from keys remotely fetched from options.jwks_uri', async () => {
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request('http://localhost/auth-with-jwks_uri/a')
req.headers.set('Authorization', `Basic ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ message: 'hello world' })
expect(handlerExecuted).toBeTruthy()
})
it('Should authorize from keys and hard-coded and remotely fetched from options.jwks_uri', async () => {
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request('http://localhost/auth-with-keys-and-jwks_uri/a')
req.headers.set('Authorization', `Basic ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ message: 'hello world' })
expect(handlerExecuted).toBeTruthy()
})
it('Should not authorize requests with invalid Unicode payload in header', async () => {
const invalidToken =
'ssyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'
const url = 'http://localhost/auth-with-keys-unicode/a'
const req = new Request(url)
req.headers.set('Authorization', `Basic ${invalidToken}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
expect(res.headers.get('www-authenticate')).toEqual(
`Bearer realm="${url}",error="invalid_token",error_description="token verification failure"`
)
expect(handlerExecuted).toBeFalsy()
})
it('Should not authorize requests with malformed token structure in header', async () => {
const invalid_token = 'invalid token'
const url = 'http://localhost/auth-with-keys/a'
const req = new Request(url)
req.headers.set('Authorization', `Bearer ${invalid_token}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
expect(res.headers.get('www-authenticate')).toEqual(
`Bearer realm="${url}",error="invalid_request",error_description="invalid credentials structure"`
)
expect(handlerExecuted).toBeFalsy()
})
it('Should not authorize requests without authorization in nested JWK middleware', async () => {
const req = new Request('http://localhost/auth-with-keys-nested/a')
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
expect(await res.text()).toBe('Unauthorized')
expect(handlerExecuted).toBeFalsy()
})
it('Should authorize requests with authorization in nested JWK middleware', async () => {
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request('http://localhost/auth-with-keys-nested/a')
req.headers.set('Authorization', `Bearer ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ message: 'hello world' })
expect(handlerExecuted).toBeTruthy()
})
})
describe('Credentials in cookie', () => {
let handlerExecuted: boolean
beforeEach(() => {
handlerExecuted = false
})
const app = new Hono()
app.use('/auth-with-keys/*', jwk({ keys: verify_keys, cookie: 'access_token' }))
app.use('/auth-with-keys-unicode/*', jwk({ keys: verify_keys, cookie: 'access_token' }))
app.use(
'/auth-with-keys-prefixed/*',
jwk({ keys: verify_keys, cookie: { key: 'access_token', prefixOptions: 'host' } })
)
app.use(
'/auth-with-keys-unprefixed/*',
jwk({ keys: verify_keys, cookie: { key: 'access_token' } })
)
app.get('/auth-with-keys/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
app.get('/auth-with-keys-prefixed/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
app.get('/auth-with-keys-unprefixed/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
app.get('/auth-with-keys-unicode/*', (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
it('Should not authorize requests with missing access token', async () => {
const req = new Request('http://localhost/auth-with-keys/a')
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
expect(await res.text()).toBe('Unauthorized')
expect(handlerExecuted).toBeFalsy()
})
it('Should authorize cookie from a static array passed to options.keys', async () => {
const url = 'http://localhost/auth-with-keys/a'
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request(url, {
headers: new Headers({
Cookie: `access_token=${credential}`,
}),
})
const res = await app.request(req)
expect(res).not.toBeNull()
expect(await res.json()).toEqual({ message: 'hello world' })
expect(res.status).toBe(200)
expect(handlerExecuted).toBeTruthy()
})
it('Should authorize prefixed cookie from a static array passed to options.keys', async () => {
const url = 'http://localhost/auth-with-keys-prefixed/a'
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request(url, {
headers: new Headers({
Cookie: `__Host-access_token=${credential}`,
}),
})
const res = await app.request(req)
expect(res).not.toBeNull()
expect(await res.json()).toEqual({ message: 'hello world' })
expect(res.status).toBe(200)
expect(handlerExecuted).toBeTruthy()
})
it('Should authorize unprefixed cookie from a static array passed to options.keys', async () => {
const url = 'http://localhost/auth-with-keys-unprefixed/a'
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request(url, {
headers: new Headers({
Cookie: `access_token=${credential}`,
}),
})
const res = await app.request(req)
expect(res).not.toBeNull()
expect(await res.json()).toEqual({ message: 'hello world' })
expect(res.status).toBe(200)
expect(handlerExecuted).toBeTruthy()
})
it('Should authorize with Unicode payload from a static array passed to options.keys', async () => {
const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])
const req = new Request('http://localhost/auth-with-keys-unicode/a', {
headers: new Headers({
Cookie: `access_token=${credential}`,
}),
})
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ message: 'hello world' })
expect(handlerExecuted).toBeTruthy()
})
it('Should not authorize requests with invalid Unicode payload in cookie', async () => {
const invalidToken =
'ssyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'
const url = 'http://localhost/auth-with-keys-unicode/a'
const req = new Request(url)
req.headers.set('Cookie', `access_token=${invalidToken}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
expect(res.headers.get('www-authenticate')).toEqual(
`Bearer realm="${url}",error="invalid_token",error_description="token verification failure"`
)
expect(handlerExecuted).toBeFalsy()
})
it('Should not authorize requests with malformed token structure in cookie', async () => {
const invalidToken = 'invalid token'
const url = 'http://localhost/auth-with-keys/a'
const req = new Request(url)
req.headers.set('Cookie', `access_token=${invalidToken}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
expect(res.headers.get('www-authenticate')).toEqual(
`Bearer realm="${url}",error="invalid_token",error_description="token verification failure"`
)
expect(handlerExecuted).toBeFalsy()
})
})
describe('Credentials in a signed cookie', () => {
let handlerExecuted: boolean
beforeEach(() => {
handlerExecuted = false
})
const app = new Hono()
const test_secret = 'Shhh'
app.use(
'/auth-with-signed-cookie/*',
jwk({ keys: verify_keys, cookie: { key: 'access_token', secret: test_secret } })
)
app.use(
'/auth-with-signed-with-prefix-options-cookie/*',
jwk({
keys: verify_keys,
cookie: { key: 'access_token', secret: test_secret, prefixOptions: 'host' },
})
)
app.get('/sign-cookie', async (c) => {
const credential = await Jwt.sign(
{ message: 'signed hello world' },
test_keys.private_keys[0]
)
await setSignedCookie(c, 'access_token', credential, test_secret)
return c.text('OK')
})
app.get('/sign-cookie-with-prefix', async (c) => {
const credential = await Jwt.sign(
{ message: 'signed hello world' },
test_keys.private_keys[0]
)
await setSignedCookie(c, 'access_token', credential, test_secret, { prefix: 'host' })
return c.text('OK')
})
app.get('/auth-with-signed-cookie/*', async (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
app.get('/auth-with-signed-with-prefix-options-cookie/*', async (c) => {
handlerExecuted = true
const payload = c.get('jwtPayload')
return c.json(payload)
})
it('Should authorize signed cookie', async () => {
const url = 'http://localhost/auth-with-signed-cookie/a'
const sign_res = await app.request('http://localhost/sign-cookie')
const cookieHeader = sign_res.headers.get('Set-Cookie') as string
expect(cookieHeader).not.toBeNull()
const req = new Request(url)
req.headers.set('Cookie', cookieHeader)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ message: 'signed hello world' })
expect(handlerExecuted).toBeTruthy()
})
it('Should authorize prefixed signed cookie', async () => {
const url = 'http://localhost/auth-with-signed-with-prefix-options-cookie/a'
const sign_res = await app.request('http://localhost/sign-cookie-with-prefix')
const cookieHeader = sign_res.headers.get('Set-Cookie') as string
expect(cookieHeader).not.toBeNull()
const req = new Request(url)
req.headers.set('Cookie', cookieHeader)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ message: 'signed hello world' })
expect(handlerExecuted).toBeTruthy()
})
it('Should not authorize an unsigned cookie', async () => {
const url = 'http://localhost/auth-with-signed-cookie/a'
const credential = await Jwt.sign(
{ message: 'unsigned hello world' },
test_keys.private_keys[0]
)
const unsignedCookie = `access_token=${credential}`
const req = new Request(url)
req.headers.set('Cookie', unsignedCookie)
const res = await app.request(req)
expect(res.status).toBe(401)
expect(await res.text()).toBe('Unauthorized')
expect(handlerExecuted).toBeFalsy()
})
})
describe('Error handling with `cause`', () => {
const app = new Hono()
app.use('/auth-with-keys/*', jwk({ keys: verify_keys }))
app.get('/auth-with-keys/*', (c) => c.text('Authorized'))
app.onError((e, c) => {
if (e instanceof HTTPException && e.cause instanceof Error) {
return c.json({ name: e.cause.name, message: e.cause.message }, 401)
}
return c.text(e.message, 401)
})
it('Should not authorize', async () => {
const credential = 'abc.def.ghi'
const req = new Request('http://localhost/auth-with-keys')
req.headers.set('Authorization', `Bearer ${credential}`)
const res = await app.request(req)
expect(res.status).toBe(401)
expect(await res.json()).toEqual({
name: 'JwtTokenInvalid',
message: `invalid JWT token: ${credential}`,
})
})
})
})