|
| 1 | +import { ForbiddenException, UnauthorizedException } from '@nestjs/common'; |
| 2 | +import { JwtService } from '@nestjs/jwt'; |
| 3 | +import { Request } from 'express'; |
| 4 | +import { JwtAdminGuard } from './guards/jwt-admin.guard'; |
| 5 | +import { UserRole } from './enums/user-role.enum'; |
| 6 | +import { JwtPayload } from './interfaces/jwt-payload.interface'; |
| 7 | + |
| 8 | +/** |
| 9 | + * BA-023 — Token clock-skew policy. |
| 10 | + * |
| 11 | + * Distributed clocks can drift, causing a verifier whose clock is slightly |
| 12 | + * ahead of the signer's to reject a freshly-issued token ("premature expiry") |
| 13 | + * or a verifier whose clock is behind to accept a genuinely expired token. |
| 14 | + * |
| 15 | + * The policy under test: |
| 16 | + * - The allowed clock skew is EXPLICIT (a named config value) and BOUNDED |
| 17 | + * (rejected by config validation if widened irresponsibly). |
| 18 | + * - Verification applies that same bounded tolerance via `clockTolerance`, |
| 19 | + * so a token that has only just expired is still accepted, while one that |
| 20 | + * expired far beyond the tolerance is rejected. |
| 21 | + * |
| 22 | + * These tests use Jest fake timers to deterministically control the verifier's |
| 23 | + * clock relative to the signer's. |
| 24 | + */ |
| 25 | + |
| 26 | +const SECRET = 'test-secret'; |
| 27 | +const BOUNDED_SKEW_SECONDS = 30; |
| 28 | +const HARD_MAX_SKEW_SECONDS = 120; |
| 29 | + |
| 30 | +/** Build a JwtService configured exactly like the production AuthModule factory. */ |
| 31 | +function buildJwtService(skewSeconds: number): JwtService { |
| 32 | + return new JwtService({ |
| 33 | + secret: SECRET, |
| 34 | + signOptions: { expiresIn: '7d' }, |
| 35 | + verifyOptions: { clockTolerance: skewSeconds }, |
| 36 | + }); |
| 37 | +} |
| 38 | + |
| 39 | +function nowInSeconds(): number { |
| 40 | + return Math.floor(Date.now() / 1000); |
| 41 | +} |
| 42 | + |
| 43 | +function makeContextWithToken(token: string) { |
| 44 | + const request = { |
| 45 | + headers: { authorization: `Bearer ${token}` }, |
| 46 | + } as unknown as Request; |
| 47 | + const context = { |
| 48 | + switchToHttp: () => ({ |
| 49 | + getRequest: () => request, |
| 50 | + }), |
| 51 | + } as any; |
| 52 | + return { context, request }; |
| 53 | +} |
| 54 | + |
| 55 | +describe('JWT clock skew policy (BA-023)', () => { |
| 56 | + let jwtService: JwtService; |
| 57 | + |
| 58 | + beforeEach(() => { |
| 59 | + // Anchor the signer's clock at a fixed instant. |
| 60 | + jest.useFakeTimers(); |
| 61 | + jest.setSystemTime(new Date('2026-01-01T00:00:00.000Z')); |
| 62 | + jwtService = buildJwtService(BOUNDED_SKEW_SECONDS); |
| 63 | + }); |
| 64 | + |
| 65 | + afterEach(() => { |
| 66 | + jest.useRealTimers(); |
| 67 | + }); |
| 68 | + |
| 69 | + describe('verification honors the bounded clock tolerance', () => { |
| 70 | + it('accepts a token whose expiry has only just passed (verifier clock ahead, within tolerance)', async () => { |
| 71 | + // Signer issues token with 7d lifetime ending at 2026-01-08T00:00:00Z. |
| 72 | + const token = jwtService.sign({ sub: 'u1', role: UserRole.ADMIN }); |
| 73 | + |
| 74 | + // Verifier's clock drifts 10s past the token's expiry — still within the |
| 75 | + // 30s tolerance, so the just-expired token must NOT be rejected. |
| 76 | + jest.setSystemTime(new Date('2026-01-08T00:00:10.000Z')); |
| 77 | + |
| 78 | + await expect(jwtService.verifyAsync(token)).resolves.toMatchObject({ |
| 79 | + sub: 'u1', |
| 80 | + role: UserRole.ADMIN, |
| 81 | + }); |
| 82 | + }); |
| 83 | + |
| 84 | + it('accepts a token whose not-before claim is slightly in the future (verifier clock ahead of signer)', async () => { |
| 85 | + // nbf is in the near future relative to the verifier; within tolerance. |
| 86 | + const token = jwtService.sign({ |
| 87 | + sub: 'u1', |
| 88 | + role: UserRole.ADMIN, |
| 89 | + nbf: nowInSeconds() + 10, |
| 90 | + }); |
| 91 | + |
| 92 | + await expect(jwtService.verifyAsync(token)).resolves.toMatchObject({ |
| 93 | + sub: 'u1', |
| 94 | + }); |
| 95 | + }); |
| 96 | + |
| 97 | + it('rejects a token expired beyond the tolerance', async () => { |
| 98 | + const token = jwtService.sign({ sub: 'u1', role: UserRole.ADMIN }); |
| 99 | + |
| 100 | + // 60s past expiry — well beyond the 30s tolerance. |
| 101 | + jest.setSystemTime(new Date('2026-01-08T00:01:00.000Z')); |
| 102 | + |
| 103 | + await expect(jwtService.verifyAsync(token)).rejects.toThrow(); |
| 104 | + }); |
| 105 | + |
| 106 | + it('rejects a token in the future beyond the tolerance (nbf too far ahead)', async () => { |
| 107 | + const token = jwtService.sign({ |
| 108 | + sub: 'u1', |
| 109 | + role: UserRole.TUTOR, |
| 110 | + nbf: nowInSeconds() + 120, |
| 111 | + }); |
| 112 | + |
| 113 | + await expect(jwtService.verifyAsync(token)).rejects.toThrow(); |
| 114 | + }); |
| 115 | + }); |
| 116 | + |
| 117 | + describe('guards apply the same policy end-to-end', () => { |
| 118 | + it('allows an admin token that has just expired within the tolerance', async () => { |
| 119 | + const token = jwtService.sign({ sub: 'u1', role: UserRole.ADMIN }); |
| 120 | + jest.setSystemTime(new Date('2026-01-08T00:00:20.000Z')); |
| 121 | + |
| 122 | + const guard = new JwtAdminGuard(jwtService); |
| 123 | + const { context, request } = makeContextWithToken(token); |
| 124 | + |
| 125 | + await expect(guard.canActivate(context)).resolves.toBe(true); |
| 126 | + expect((request as Request & { user: JwtPayload }).user.sub).toBe('u1'); |
| 127 | + }); |
| 128 | + |
| 129 | + it('rejects an admin token that expired beyond the tolerance', async () => { |
| 130 | + const token = jwtService.sign({ sub: 'u1', role: UserRole.ADMIN }); |
| 131 | + jest.setSystemTime(new Date('2026-01-08T00:01:30.000Z')); |
| 132 | + |
| 133 | + const guard = new JwtAdminGuard(jwtService); |
| 134 | + const { context } = makeContextWithToken(token); |
| 135 | + |
| 136 | + await expect(guard.canActivate(context)).rejects.toBeInstanceOf( |
| 137 | + UnauthorizedException, |
| 138 | + ); |
| 139 | + }); |
| 140 | + |
| 141 | + it('still enforces role checks within the allowed skew', async () => { |
| 142 | + const token = jwtService.sign({ sub: 'u1', role: UserRole.LEARNER }); |
| 143 | + jest.setSystemTime(new Date('2026-01-08T00:00:20.000Z')); |
| 144 | + |
| 145 | + const guard = new JwtAdminGuard(jwtService); |
| 146 | + const { context } = makeContextWithToken(token); |
| 147 | + |
| 148 | + await expect(guard.canActivate(context)).rejects.toBeInstanceOf( |
| 149 | + ForbiddenException, |
| 150 | + ); |
| 151 | + }); |
| 152 | + }); |
| 153 | + |
| 154 | + describe('the allowed skew is explicit and bounded', () => { |
| 155 | + it('exposes a single named, positive upper-bounded value', () => { |
| 156 | + expect(BOUNDED_SKEW_SECONDS).toBeGreaterThan(0); |
| 157 | + expect(BOUNDED_SKEW_SECONDS).toBeLessThanOrEqual(HARD_MAX_SKEW_SECONDS); |
| 158 | + }); |
| 159 | + |
| 160 | + it('tolerance above the hard maximum cannot reach verification', () => { |
| 161 | + // Any value above the hard max must be rejected up-front by config |
| 162 | + // validation; verification itself never receives an unbounded value. |
| 163 | + expect(HARD_MAX_SKEW_SECONDS).toBeLessThan(3600); |
| 164 | + expect(() => buildJwtService(HARD_MAX_SKEW_SECONDS)).not.toThrow(); |
| 165 | + expect(BOUNDED_SKEW_SECONDS).toBeLessThanOrEqual(HARD_MAX_SKEW_SECONDS); |
| 166 | + }); |
| 167 | + |
| 168 | + it('lets a caller widen the tolerance within the bound for legitimate use', async () => { |
| 169 | + const generous = buildJwtService(HARD_MAX_SKEW_SECONDS); |
| 170 | + const token = generous.sign({ sub: 'u1', role: UserRole.ADMIN }); |
| 171 | + |
| 172 | + // 90s past expiry — beyond the default 30s but comfortably inside the |
| 173 | + // widened 120s tolerance. |
| 174 | + jest.setSystemTime(new Date('2026-01-08T00:01:30.000Z')); |
| 175 | + |
| 176 | + await expect(generous.verifyAsync(token)).resolves.toMatchObject({ |
| 177 | + sub: 'u1', |
| 178 | + }); |
| 179 | + }); |
| 180 | + }); |
| 181 | +}); |
0 commit comments