Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

wake-token.test.ts

37 lines2.5 KB

1import { randomBytes, randomUUID } from 'node:crypto'
2import { expect, test } from 'vitest'
3import { WakeTokens } from '../../src/wake-token.js'
4​
5const identity = () => ({ installationId: randomUUID(), servingEpoch: randomUUID(), tenantId: 'tenant', subscriptionId: randomUUID(),
6 name: 'worker', wakeId: randomUUID(), generation: 5, kind: 'pull-wake' as const })
7test('signed tokens authenticate wake identity without a persisted wake record', () => {
8 const tokens = new WakeTokens({ currentKeyId: 'v1', keys: { v1: randomBytes(32) } }), claims = identity()
9 const token = tokens.sign(claims)
10 expect(tokens.verify(token)).toMatchObject({ ...claims, v: 2 })
11 expect(tokens.sign(claims)).not.toBe(token)
12})
13test('key rotation verifies retained keys and rejects missing or incorrect keys', () => {
14 const v1 = randomBytes(32), v2 = randomBytes(32)
15 const token = new WakeTokens({ currentKeyId: 'v1', keys: { v1 } }).sign(identity())
16 expect(new WakeTokens({ currentKeyId: 'v2', keys: { v1, v2 } }).verify(token)).toBeDefined()
17 expect(new WakeTokens({ currentKeyId: 'v2', keys: { v2 } }).verify(token)).toBeUndefined()
18 expect(new WakeTokens({ currentKeyId: 'v1', keys: { v1: v2 } }).verify(token)).toBeUndefined()
19})
20test('payload, key ID, signature, and oversized input mutations cannot authenticate', () => {
21 const tokens = new WakeTokens({ currentKeyId: 'v1', keys: { v1: randomBytes(32) } }), token = tokens.sign(identity())
22 const parts = token.split('.')
23 const body = JSON.parse(Buffer.from(parts[3]!, 'base64url').toString('utf8')) as Record<string, unknown>
24 body.tenantId = 'another-tenant'
25 expect(tokens.verify([...parts.slice(0, 3), Buffer.from(JSON.stringify(body)).toString('base64url'), parts[4]].join('.'))).toBeUndefined()
26 expect(tokens.verify(token.replace('.v1.', '.v2.'))).toBeUndefined()
27 expect(tokens.verify(token.slice(0, -2))).toBeUndefined()
28 expect(tokens.verify(token + '=' )).toBeUndefined()
29 expect(tokens.verify('x'.repeat(8193))).toBeUndefined()
30})
31test('the keyring is captured before caller mutation and identities have finite bounds', () => {
32 const key = randomBytes(32), ring = { currentKeyId: 'v1', keys: { v1: key } }, tokens = new WakeTokens(ring)
33 const token = tokens.sign(identity()); key.fill(0); ring.currentKeyId = 'missing'
34 expect(tokens.verify(token)).toBeDefined()
35 expect(() => tokens.sign({ ...identity(), generation: Number.MAX_SAFE_INTEGER + 1 })).toThrow('identity')
36 expect(() => tokens.sign({ ...identity(), tenantId: 'x'.repeat(513) })).toThrow('identity')
37})