-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.test.ts
75 lines (67 loc) · 2.24 KB
/
utils.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
import { assert, assertEquals, assertThrows } from 'https://deno.land/[email protected]/assert/mod.ts';
import * as jwt from 'https://deno.land/x/[email protected]/mod.ts';
import { env, verifyAuthorizationHeader } from './utils.ts';
Deno.test('utils', async (t) => {
await t.step('env', async (t) => {
await t.step('it should return the environment variable value', () => {
Deno.env.set('TEST', 'foobar');
assertEquals(env('TEST'), 'foobar');
});
await t.step(
'it should throw if the environment variable is not defined',
() => {
Deno.env.delete('TEST');
assertThrows(() => env('TEST'));
},
);
});
await t.step('verifyAuthorizationHeader', async (t) => {
const verify = verifyAuthorizationHeader({ sub: 'foo', secret: 'bar' });
// deno-lint-ignore no-explicit-any
const createToken = ({ sub, secret }: any, headers: any) =>
jwt.create(headers, { sub }, secret);
await t.step('it should verify the header value', async () => {
const token = await createToken(
{ sub: 'foo', secret: 'bar' },
{ alg: 'HS256', type: 'JWT' },
);
await verify(`Bearer ${token}`)
.then(() => assert(true))
.catch((err) => assert(false, err));
});
await t.step(
'it should throw an UnauthorizedError if token signing verification fails',
async () => {
const token = await createToken(
{ sub: 'foo', secret: 'NOT_RIGHT' },
{
alg: 'HS256',
type: 'JWT',
},
);
await verify(`Bearer ${token}`)
.then(() => assert(false, 'should have thrown'))
.catch((err) => {
assertEquals(err.name, 'UnauthorizedError');
});
},
);
await t.step(
'it should throw an UnauthorizedError if the sub in the payload is incorrect',
async () => {
const token = await createToken(
{ sub: 'NOT_RIGHT', secret: 'bar' },
{
alg: 'HS256',
type: 'JWT',
},
);
await verify(`Bearer ${token}`)
.then(() => assert(false, 'should have thrown'))
.catch((err) => {
assertEquals(err.name, 'UnauthorizedError');
});
},
);
});
});