File size: 1,379 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { ExecutionContext } from '@nestjs/common';
import { SignJWT } from 'jose';
import type { AppConfig } from '../../config/app-config.interface.js';
import { InternalTokenGuard } from './internal-token.guard.js';

const SECRET = 'test-processing-secret-0123456789abcdef012';
const guard = new InternalTokenGuard({ processingToken: { secret: SECRET }, internalTokenAudience: 'prevision-internal' } as AppConfig);

const sign = (audience: string, expiresIn = 60) => {
  const now = Math.floor(Date.now() / 1000);
  return new SignJWT({}).setProtectedHeader({ alg: 'HS256' }).setAudience(audience).setIssuedAt(now).setExpirationTime(now + expiresIn).sign(new TextEncoder().encode(SECRET));
};
const check = (token?: string) =>
  guard.canActivate({
    switchToHttp: () => ({ getRequest: () => ({ headers: token ? { authorization: `Bearer ${token}` } : {} }) }),
  } as ExecutionContext);

describe('InternalTokenGuard', () => {
  it('accepts the renderer token', async () => {
    expect(await check(await sign('prevision-internal'))).toBe(true);
  });

  it.each([
    ['missing', async () => undefined],
    ['browser processing token', () => sign('prevision-processing')],
    ['expired', () => sign('prevision-internal', -120)],
  ])('refuses a %s token', async (_, token) => {
    await expect(check(await token())).rejects.toMatchObject({ status: 401 });
  });
});