Add account API key management

This commit is contained in:
Mike Cao committed 2026-09-01 21:50:07 -07:00
1 parent 98b824ce48
commit f1c5b4f7bb
32 files changed
+1618 -15

No files matched your search

+126
View File
@@ -2,7 +2,9 @@ import { beforeEach, describe, expect, test, vi } from 'vitest';
import { hash } from '@/lib/crypto';
import { parseSecureToken } from '@/lib/jwt';
import redis from '@/lib/redis';
import { getApiKeyByHash, updateApiKeyLastUsed } from '@/queries/prisma/apiKey';
import { getUser } from '@/queries/prisma/user';
import { hashApiKey } from './api-key';
import { checkAuth } from './auth';
vi.mock('@/lib/jwt', () => ({
@@ -14,6 +16,11 @@ vi.mock('@/queries/prisma/user', () => ({
getUser: vi.fn(),
}));
vi.mock('@/queries/prisma/apiKey', () => ({
getApiKeyByHash: vi.fn(),
updateApiKeyLastUsed: vi.fn(() => Promise.resolve()),
}));
vi.mock('@/lib/redis', () => ({
default: {
enabled: false,
@@ -25,6 +32,8 @@ vi.mock('@/lib/redis', () => ({
const parseSecureTokenMock = vi.mocked(parseSecureToken);
const getUserMock = vi.mocked(getUser);
const getApiKeyByHashMock = vi.mocked(getApiKeyByHash);
const updateApiKeyLastUsedMock = vi.mocked(updateApiKeyLastUsed);
const redisMock = redis as unknown as {
enabled: boolean;
client: {
@@ -50,12 +59,129 @@ function mockUser() {
}
beforeEach(() => {
vi.unstubAllEnvs();
vi.stubEnv('CLOUD_MODE', '');
parseSecureTokenMock.mockReset();
getUserMock.mockReset();
getApiKeyByHashMock.mockReset();
updateApiKeyLastUsedMock.mockClear();
redisMock.enabled = false;
redisMock.client.get.mockReset();
});
describe('checkAuth api keys', () => {
const API_KEY = 'umami_abcdefghijklmnopqrstuvwxyz012345';
function apiKeyRequest(path = '/api/websites') {
return new Request(`http://localhost${path}`, {
headers: { authorization: `Bearer ${API_KEY}` },
});
}
function mockApiKey(lastUsedAt: Date | null = null) {
getApiKeyByHashMock.mockResolvedValue({
id: 'key-1',
userId: 'user-1',
name: 'CI',
keyHash: hashApiKey(API_KEY),
keyPrefix: 'umami_abcdefgh',
lastUsedAt,
createdAt: new Date(),
} as any);
}
test('authorizes a valid api key and looks it up by hash', async () => {
mockApiKey();
mockUser();
const result: any = await checkAuth(apiKeyRequest());
expect(getApiKeyByHashMock).toHaveBeenCalledWith(hashApiKey(API_KEY));
expect(result?.user?.id).toBe('user-1');
expect(result?.user).not.toHaveProperty('password');
expect(result?.apiKey).toEqual({ id: 'key-1', name: 'CI' });
expect(parseSecureTokenMock).not.toHaveBeenCalled();
});
test('rejects an unknown api key', async () => {
getApiKeyByHashMock.mockResolvedValue(null);
const result = await checkAuth(apiKeyRequest());
expect(result).toBeNull();
expect(getUserMock).not.toHaveBeenCalled();
});
test('rejects an api key whose user no longer exists', async () => {
mockApiKey();
getUserMock.mockResolvedValue(null as any);
const result = await checkAuth(apiKeyRequest());
expect(result).toBeNull();
});
test('rejects api keys on sensitive routes', async () => {
mockApiKey();
mockUser();
for (const path of [
'/api/me/password',
'/api/me/api-keys',
'/api/me/api-keys/key-1',
'/api/2fa/status',
'/api/auth/logout',
'/api/users',
'/api/admin/users',
]) {
expect(await checkAuth(apiKeyRequest(path))).toBeNull();
}
expect(getApiKeyByHashMock).not.toHaveBeenCalled();
});
test('ignores api keys in cloud mode', async () => {
vi.stubEnv('CLOUD_MODE', '1');
mockApiKey();
mockUser();
parseSecureTokenMock.mockReturnValue(null);
const result = await checkAuth(apiKeyRequest());
expect(result).toBeNull();
expect(getApiKeyByHashMock).not.toHaveBeenCalled();
expect(parseSecureTokenMock).toHaveBeenCalled();
});
test('updates lastUsedAt when stale', async () => {
mockApiKey(new Date(Date.now() - 60 * 60 * 1000));
mockUser();
await checkAuth(apiKeyRequest());
expect(updateApiKeyLastUsedMock).toHaveBeenCalledWith('key-1');
});
test('does not update lastUsedAt when recently used', async () => {
mockApiKey(new Date());
mockUser();
await checkAuth(apiKeyRequest());
expect(updateApiKeyLastUsedMock).not.toHaveBeenCalled();
});
test('does not treat a jwt as an api key', async () => {
parseSecureTokenMock.mockReturnValue({ userId: 'user-1' } as any);
mockUser();
const result = await checkAuth(authedRequest());
expect(result?.user?.id).toBe('user-1');
expect(getApiKeyByHashMock).not.toHaveBeenCalled();
});
});
describe('checkAuth password fingerprint', () => {
test('authorizes a stateless token whose fingerprint matches the current password', async () => {
parseSecureTokenMock.mockReturnValue({ userId: 'user-1', pwd: hash(PASSWORD_HASH) } as any);