Add account API key management
This commit is contained in:
1 parent
98b824ce48
commit
f1c5b4f7bb
32 files changed
+1618
-15
No files matched your search
@@ -0,0 +1,89 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import {
|
||||
API_KEY_PREFIX,
|
||||
generateApiKey,
|
||||
getApiKeyPrefix,
|
||||
hashApiKey,
|
||||
isApiKey,
|
||||
isApiKeyBlockedPath,
|
||||
isApiKeyEnabled,
|
||||
} from './api-key';
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe('generateApiKey', () => {
|
||||
test('produces umami_ followed by 32 base62 characters', () => {
|
||||
const key = generateApiKey();
|
||||
|
||||
expect(key).toMatch(/^umami_[0-9a-zA-Z]{32}$/);
|
||||
});
|
||||
|
||||
test('produces unique keys', () => {
|
||||
expect(generateApiKey()).not.toBe(generateApiKey());
|
||||
});
|
||||
});
|
||||
|
||||
describe('hashApiKey', () => {
|
||||
test('is deterministic and does not equal the key', () => {
|
||||
const key = generateApiKey();
|
||||
|
||||
expect(hashApiKey(key)).toBe(hashApiKey(key));
|
||||
expect(hashApiKey(key)).not.toBe(key);
|
||||
expect(hashApiKey(key)).toHaveLength(128);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getApiKeyPrefix', () => {
|
||||
test('returns the prefix plus the first 8 characters', () => {
|
||||
const key = `${API_KEY_PREFIX}abcdefghijklmnopqrstuvwxyz012345`;
|
||||
|
||||
expect(getApiKeyPrefix(key)).toBe('umami_abcdefgh');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isApiKey', () => {
|
||||
test('detects api keys by prefix', () => {
|
||||
expect(isApiKey('umami_abc')).toBe(true);
|
||||
expect(isApiKey('eyJhbGciOi')).toBe(false);
|
||||
expect(isApiKey(undefined)).toBe(false);
|
||||
expect(isApiKey(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isApiKeyBlockedPath', () => {
|
||||
test('blocks credential and admin routes', () => {
|
||||
expect(isApiKeyBlockedPath('/api/me/password')).toBe(true);
|
||||
expect(isApiKeyBlockedPath('/api/me/api-keys')).toBe(true);
|
||||
expect(isApiKeyBlockedPath('/api/me/api-keys/abc')).toBe(true);
|
||||
expect(isApiKeyBlockedPath('/api/2fa/status')).toBe(true);
|
||||
expect(isApiKeyBlockedPath('/api/auth/logout')).toBe(true);
|
||||
expect(isApiKeyBlockedPath('/api/users')).toBe(true);
|
||||
expect(isApiKeyBlockedPath('/api/users/abc/websites')).toBe(true);
|
||||
expect(isApiKeyBlockedPath('/api/admin/users')).toBe(true);
|
||||
});
|
||||
|
||||
test('allows data routes', () => {
|
||||
expect(isApiKeyBlockedPath('/api/me')).toBe(false);
|
||||
expect(isApiKeyBlockedPath('/api/me/websites')).toBe(false);
|
||||
expect(isApiKeyBlockedPath('/api/me/teams')).toBe(false);
|
||||
expect(isApiKeyBlockedPath('/api/websites')).toBe(false);
|
||||
expect(isApiKeyBlockedPath('/api/websites/abc/stats')).toBe(false);
|
||||
expect(isApiKeyBlockedPath('/api/authors')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isApiKeyEnabled', () => {
|
||||
test('is disabled in cloud mode', () => {
|
||||
vi.stubEnv('CLOUD_MODE', '1');
|
||||
|
||||
expect(isApiKeyEnabled()).toBe(false);
|
||||
});
|
||||
|
||||
test('is enabled when CLOUD_MODE is unset', () => {
|
||||
vi.stubEnv('CLOUD_MODE', '');
|
||||
|
||||
expect(isApiKeyEnabled()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { hash } from '@/lib/crypto';
|
||||
import { getRandomChars } from '@/lib/generate';
|
||||
|
||||
export const API_KEY_PREFIX = 'umami_';
|
||||
export const API_KEY_LENGTH = 32;
|
||||
export const API_KEY_DISPLAY_LENGTH = API_KEY_PREFIX.length + 8;
|
||||
export const API_KEY_LAST_USED_INTERVAL = 5 * 60 * 1000;
|
||||
|
||||
// Routes that manage account credentials or admin state must not be
|
||||
// reachable with an API key. Matched as path prefixes.
|
||||
export const API_KEY_BLOCKED_PATHS = [
|
||||
'/api/me/password',
|
||||
'/api/me/api-keys',
|
||||
'/api/2fa',
|
||||
'/api/auth',
|
||||
'/api/users',
|
||||
'/api/admin',
|
||||
];
|
||||
|
||||
export function generateApiKey() {
|
||||
return `${API_KEY_PREFIX}${getRandomChars(API_KEY_LENGTH)}`;
|
||||
}
|
||||
|
||||
export function hashApiKey(key: string) {
|
||||
return hash(key);
|
||||
}
|
||||
|
||||
export function getApiKeyPrefix(key: string) {
|
||||
return key.slice(0, API_KEY_DISPLAY_LENGTH);
|
||||
}
|
||||
|
||||
export function isApiKey(token?: string | null): token is string {
|
||||
return typeof token === 'string' && token.startsWith(API_KEY_PREFIX);
|
||||
}
|
||||
|
||||
export function isApiKeyBlockedPath(pathname: string) {
|
||||
return API_KEY_BLOCKED_PATHS.some(path => pathname === path || pathname.startsWith(`${path}/`));
|
||||
}
|
||||
|
||||
export function isApiKeyEnabled() {
|
||||
return !process.env.CLOUD_MODE;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import debug from 'debug';
|
||||
import {
|
||||
API_KEY_LAST_USED_INTERVAL,
|
||||
hashApiKey,
|
||||
isApiKey,
|
||||
isApiKeyBlockedPath,
|
||||
isApiKeyEnabled,
|
||||
} from '@/lib/api-key';
|
||||
import {
|
||||
ROLE_PERMISSIONS,
|
||||
ROLES,
|
||||
@@ -10,6 +17,7 @@ import { createAuthKey, hash, secret } from '@/lib/crypto';
|
||||
import { createSecureToken, parseSecureToken, parseToken } from '@/lib/jwt';
|
||||
import redis from '@/lib/redis';
|
||||
import { ensureArray } from '@/lib/utils';
|
||||
import { getApiKeyByHash, updateApiKeyLastUsed } from '@/queries/prisma/apiKey';
|
||||
import { getUser } from '@/queries/prisma/user';
|
||||
|
||||
const log = debug('umami:auth');
|
||||
@@ -20,8 +28,51 @@ export function getBearerToken(request: Request) {
|
||||
return auth?.split(' ')[1];
|
||||
}
|
||||
|
||||
export async function checkApiKeyAuth(request: Request, token: string) {
|
||||
const { pathname } = new URL(request.url);
|
||||
|
||||
if (isApiKeyBlockedPath(pathname)) {
|
||||
log('API key not allowed for path', pathname);
|
||||
return null;
|
||||
}
|
||||
|
||||
const apiKey = await getApiKeyByHash(hashApiKey(token));
|
||||
|
||||
if (!apiKey) {
|
||||
log('API key not found');
|
||||
return null;
|
||||
}
|
||||
|
||||
const user: any = await getUser(apiKey.userId);
|
||||
|
||||
if (!user?.id) {
|
||||
log('API key user not found');
|
||||
return null;
|
||||
}
|
||||
|
||||
const lastUsedAt = apiKey.lastUsedAt?.getTime() ?? 0;
|
||||
|
||||
if (Date.now() - lastUsedAt > API_KEY_LAST_USED_INTERVAL) {
|
||||
updateApiKeyLastUsed(apiKey.id).catch(e => log(e));
|
||||
}
|
||||
|
||||
delete user.password;
|
||||
user.isAdmin = user.role === ROLES.admin;
|
||||
|
||||
return {
|
||||
token,
|
||||
user,
|
||||
apiKey: { id: apiKey.id, name: apiKey.name },
|
||||
};
|
||||
}
|
||||
|
||||
export async function checkAuth(request: Request) {
|
||||
const token = getBearerToken(request);
|
||||
|
||||
if (isApiKeyEnabled() && isApiKey(token)) {
|
||||
return checkApiKeyAuth(request, token);
|
||||
}
|
||||
|
||||
const payload = parseSecureToken(token, secret());
|
||||
const shareToken = await parseShareToken(request);
|
||||
|
||||
|
||||
@@ -19,6 +19,10 @@ export interface Auth {
|
||||
role: string;
|
||||
isAdmin: boolean;
|
||||
};
|
||||
apiKey?: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
shareToken?: {
|
||||
shareType?: number;
|
||||
websiteId?: string;
|
||||
|
||||
Reference in new issue
Block a user