|
| 1 | +/** |
| 2 | + * Tests for authenticateApiKeyFromHeader. |
| 3 | + * |
| 4 | + * The path was rewritten to look up rows by the SHA-256 hash of the incoming |
| 5 | + * API key. A fallback loop — full scan + decrypt — is preserved while the |
| 6 | + * `key_hash` backfill runs, and emits a warn log whenever it actually matches |
| 7 | + * a row so we can tell when it's safe to delete. |
| 8 | + * |
| 9 | + * @vitest-environment node |
| 10 | + */ |
| 11 | +import { dbChainMock, dbChainMockFns } from '@sim/testing' |
| 12 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 13 | + |
| 14 | +vi.mock('@sim/db', () => dbChainMock) |
| 15 | + |
| 16 | +const { serviceLogger } = vi.hoisted(() => { |
| 17 | + const logger = { |
| 18 | + info: vi.fn(), |
| 19 | + warn: vi.fn(), |
| 20 | + error: vi.fn(), |
| 21 | + debug: vi.fn(), |
| 22 | + trace: vi.fn(), |
| 23 | + fatal: vi.fn(), |
| 24 | + child: vi.fn(), |
| 25 | + withMetadata: vi.fn(), |
| 26 | + } |
| 27 | + logger.child.mockReturnValue(logger) |
| 28 | + logger.withMetadata.mockReturnValue(logger) |
| 29 | + return { serviceLogger: logger } |
| 30 | +}) |
| 31 | + |
| 32 | +vi.mock('@sim/logger', () => ({ |
| 33 | + createLogger: vi.fn(() => serviceLogger), |
| 34 | + logger: serviceLogger, |
| 35 | + runWithRequestContext: vi.fn(<T>(_ctx: unknown, fn: () => T): T => fn()), |
| 36 | + getRequestContext: vi.fn(() => undefined), |
| 37 | +})) |
| 38 | + |
| 39 | +const { mockAuthenticateApiKey } = vi.hoisted(() => ({ |
| 40 | + mockAuthenticateApiKey: vi.fn(), |
| 41 | +})) |
| 42 | + |
| 43 | +vi.mock('@/lib/api-key/auth', () => ({ |
| 44 | + authenticateApiKey: mockAuthenticateApiKey, |
| 45 | +})) |
| 46 | + |
| 47 | +const { mockGetWorkspaceBillingSettings } = vi.hoisted(() => ({ |
| 48 | + mockGetWorkspaceBillingSettings: vi.fn(), |
| 49 | +})) |
| 50 | + |
| 51 | +vi.mock('@/lib/workspaces/utils', () => ({ |
| 52 | + getWorkspaceBillingSettings: mockGetWorkspaceBillingSettings, |
| 53 | +})) |
| 54 | + |
| 55 | +const { mockGetUserEntityPermissions } = vi.hoisted(() => ({ |
| 56 | + mockGetUserEntityPermissions: vi.fn(), |
| 57 | +})) |
| 58 | + |
| 59 | +vi.mock('@/lib/workspaces/permissions/utils', () => ({ |
| 60 | + getUserEntityPermissions: mockGetUserEntityPermissions, |
| 61 | +})) |
| 62 | + |
| 63 | +import { hashApiKey } from '@/lib/api-key/crypto' |
| 64 | +import { authenticateApiKeyFromHeader } from '@/lib/api-key/service' |
| 65 | + |
| 66 | +const warnSpy = serviceLogger.warn |
| 67 | + |
| 68 | +function personalKeyRecord(overrides: Partial<Record<string, unknown>> = {}) { |
| 69 | + return { |
| 70 | + id: 'key-1', |
| 71 | + userId: 'user-1', |
| 72 | + workspaceId: null as string | null, |
| 73 | + type: 'personal', |
| 74 | + key: 'encrypted:stored:value', |
| 75 | + expiresAt: null as Date | null, |
| 76 | + ...overrides, |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +describe('authenticateApiKeyFromHeader', () => { |
| 81 | + beforeEach(() => { |
| 82 | + vi.clearAllMocks() |
| 83 | + mockAuthenticateApiKey.mockReset() |
| 84 | + mockGetWorkspaceBillingSettings.mockReset() |
| 85 | + mockGetUserEntityPermissions.mockReset() |
| 86 | + }) |
| 87 | + |
| 88 | + it('returns error when no header is provided', async () => { |
| 89 | + const result = await authenticateApiKeyFromHeader('') |
| 90 | + expect(result).toEqual({ success: false, error: 'API key required' }) |
| 91 | + expect(dbChainMockFns.where).not.toHaveBeenCalled() |
| 92 | + }) |
| 93 | + |
| 94 | + it('resolves on the fast path when the hash lookup finds a row', async () => { |
| 95 | + const record = personalKeyRecord() |
| 96 | + dbChainMockFns.where.mockResolvedValueOnce([record]) |
| 97 | + |
| 98 | + const result = await authenticateApiKeyFromHeader('sk-sim-plain-key', { |
| 99 | + userId: 'user-1', |
| 100 | + }) |
| 101 | + |
| 102 | + expect(result).toEqual({ |
| 103 | + success: true, |
| 104 | + userId: 'user-1', |
| 105 | + keyId: 'key-1', |
| 106 | + keyType: 'personal', |
| 107 | + workspaceId: undefined, |
| 108 | + }) |
| 109 | + expect(dbChainMockFns.where).toHaveBeenCalledTimes(1) |
| 110 | + expect(mockAuthenticateApiKey).not.toHaveBeenCalled() |
| 111 | + expect(warnSpy).not.toHaveBeenCalled() |
| 112 | + }) |
| 113 | + |
| 114 | + it('returns invalid when the hash lookup finds a row that fails scope checks', async () => { |
| 115 | + const record = personalKeyRecord({ userId: 'other-user' }) |
| 116 | + dbChainMockFns.where.mockResolvedValueOnce([record]) |
| 117 | + |
| 118 | + const result = await authenticateApiKeyFromHeader('sk-sim-plain-key', { |
| 119 | + userId: 'user-1', |
| 120 | + }) |
| 121 | + |
| 122 | + expect(result).toEqual({ success: false, error: 'Invalid API key' }) |
| 123 | + expect(dbChainMockFns.where).toHaveBeenCalledTimes(1) |
| 124 | + expect(mockAuthenticateApiKey).not.toHaveBeenCalled() |
| 125 | + }) |
| 126 | + |
| 127 | + it('falls back to the decrypt loop when no row matches the hash, and warns on success', async () => { |
| 128 | + const record = personalKeyRecord() |
| 129 | + dbChainMockFns.where.mockResolvedValueOnce([]).mockResolvedValueOnce([record]) |
| 130 | + mockAuthenticateApiKey.mockResolvedValueOnce(true) |
| 131 | + |
| 132 | + const result = await authenticateApiKeyFromHeader('sk-sim-plain-key', { |
| 133 | + userId: 'user-1', |
| 134 | + }) |
| 135 | + |
| 136 | + expect(result).toEqual({ |
| 137 | + success: true, |
| 138 | + userId: 'user-1', |
| 139 | + keyId: 'key-1', |
| 140 | + keyType: 'personal', |
| 141 | + workspaceId: undefined, |
| 142 | + }) |
| 143 | + expect(dbChainMockFns.where).toHaveBeenCalledTimes(2) |
| 144 | + expect(mockAuthenticateApiKey).toHaveBeenCalledWith( |
| 145 | + 'sk-sim-plain-key', |
| 146 | + 'encrypted:stored:value' |
| 147 | + ) |
| 148 | + expect(warnSpy).toHaveBeenCalledWith('API key matched via fallback decrypt loop', { |
| 149 | + keyId: 'key-1', |
| 150 | + }) |
| 151 | + }) |
| 152 | + |
| 153 | + it('returns invalid when the hash lookup misses and the fallback scan also misses', async () => { |
| 154 | + dbChainMockFns.where.mockResolvedValueOnce([]).mockResolvedValueOnce([]) |
| 155 | + |
| 156 | + const result = await authenticateApiKeyFromHeader('sk-sim-plain-key', { |
| 157 | + userId: 'user-1', |
| 158 | + }) |
| 159 | + |
| 160 | + expect(result).toEqual({ success: false, error: 'Invalid API key' }) |
| 161 | + expect(dbChainMockFns.where).toHaveBeenCalledTimes(2) |
| 162 | + expect(mockAuthenticateApiKey).not.toHaveBeenCalled() |
| 163 | + expect(warnSpy).not.toHaveBeenCalled() |
| 164 | + }) |
| 165 | + |
| 166 | + it('returns invalid when the hash lookup misses and every fallback candidate fails decrypt comparison', async () => { |
| 167 | + const record = personalKeyRecord() |
| 168 | + dbChainMockFns.where.mockResolvedValueOnce([]).mockResolvedValueOnce([record]) |
| 169 | + mockAuthenticateApiKey.mockResolvedValueOnce(false) |
| 170 | + |
| 171 | + const result = await authenticateApiKeyFromHeader('sk-sim-plain-key', { |
| 172 | + userId: 'user-1', |
| 173 | + }) |
| 174 | + |
| 175 | + expect(result).toEqual({ success: false, error: 'Invalid API key' }) |
| 176 | + expect(mockAuthenticateApiKey).toHaveBeenCalledTimes(1) |
| 177 | + expect(warnSpy).not.toHaveBeenCalled() |
| 178 | + }) |
| 179 | + |
| 180 | + it('queries by the sha256 hash of the incoming header on the fast path', async () => { |
| 181 | + dbChainMockFns.where.mockResolvedValueOnce([personalKeyRecord()]) |
| 182 | + |
| 183 | + await authenticateApiKeyFromHeader('sk-sim-plain-key', { userId: 'user-1' }) |
| 184 | + |
| 185 | + const [filter] = dbChainMockFns.where.mock.calls[0] |
| 186 | + const expected = hashApiKey('sk-sim-plain-key') |
| 187 | + expect(JSON.stringify(filter)).toContain(expected) |
| 188 | + }) |
| 189 | +}) |
0 commit comments