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

@@ -0,0 +1,80 @@
// Generated by `pnpm openapi:contracts`. Do not edit directly.
import type { ZodOpenApiOperationObject } from 'zod-openapi';
import { defineOperation } from '@/openapi/operation';
const operation1 = defineOperation({
method: 'delete',
path: '/api/me/api-keys/{keyId}',
audience: 'public',
auth: 'bearer',
operation: {
operationId: 'deleteMeApiKeysKeyId',
summary: 'Delete me api keys key id',
tags: ['Account'],
parameters: [
{
name: 'keyId',
in: 'path',
required: true,
schema: {
type: 'string',
},
},
],
responses: {
'200': {
description: 'The operation completed successfully.',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
ok: {
const: true,
},
},
required: ['ok'],
},
},
},
},
'401': {
description: 'Unauthorized.',
content: {
'application/json': {
example: {
error: {
message: 'Unauthorized.',
code: 'unauthorized',
status: 401,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
'404': {
description: 'Not found.',
content: {
'application/json': {
example: {
error: {
message: 'Not found.',
code: 'not-found',
status: 404,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
},
} as ZodOpenApiOperationObject,
});
export const operations = [operation1] as const;
@@ -0,0 +1,61 @@
import { beforeEach, expect, test, vi } from 'vitest';
import { parseRequest } from '@/lib/request';
import { DELETE } from './route';
const mocks = vi.hoisted(() => ({
deleteApiKey: vi.fn(),
}));
vi.mock('@/lib/request', () => ({
parseRequest: vi.fn(),
}));
vi.mock('@/queries/prisma/apiKey', () => ({
deleteApiKey: mocks.deleteApiKey,
}));
const parseRequestMock = vi.mocked(parseRequest);
function deleteRequest(keyId = 'key-1') {
return DELETE(new Request(`http://localhost/api/me/api-keys/${keyId}`, { method: 'DELETE' }), {
params: Promise.resolve({ keyId }),
});
}
beforeEach(() => {
vi.unstubAllEnvs();
vi.stubEnv('CLOUD_MODE', '');
parseRequestMock.mockReset();
mocks.deleteApiKey.mockReset();
parseRequestMock.mockResolvedValue({
auth: { user: { id: 'user-1' } },
error: undefined,
});
});
test('DELETE removes a key owned by the current user', async () => {
mocks.deleteApiKey.mockResolvedValue(1);
const response = await deleteRequest();
expect(response.status).toBe(200);
expect(mocks.deleteApiKey).toHaveBeenCalledWith('key-1', 'user-1');
});
test('DELETE returns 404 when the key does not belong to the user', async () => {
mocks.deleteApiKey.mockResolvedValue(0);
const response = await deleteRequest('someone-elses-key');
expect(response.status).toBe(404);
});
test('DELETE returns 404 in cloud mode', async () => {
vi.stubEnv('CLOUD_MODE', '1');
const response = await deleteRequest();
expect(response.status).toBe(404);
expect(mocks.deleteApiKey).not.toHaveBeenCalled();
});
+26
View File
@@ -0,0 +1,26 @@
import { isApiKeyEnabled } from '@/lib/api-key';
import { parseRequest } from '@/lib/request';
import { notFound, ok } from '@/lib/response';
import { deleteApiKey } from '@/queries/prisma/apiKey';
export async function DELETE(request: Request, { params }: { params: Promise<{ keyId: string }> }) {
const { auth, error } = await parseRequest(request);
if (error) {
return error();
}
if (!isApiKeyEnabled()) {
return notFound();
}
const { keyId } = await params;
const count = await deleteApiKey(keyId, auth.user.id);
if (!count) {
return notFound();
}
return ok();
}
@@ -0,0 +1,198 @@
// Generated by `pnpm openapi:contracts`. Do not edit directly.
import type { ZodOpenApiOperationObject } from 'zod-openapi';
import { defineOperation } from '@/openapi/operation';
const operation1 = defineOperation({
method: 'get',
path: '/api/me/api-keys',
audience: 'public',
auth: 'bearer',
operation: {
operationId: 'getMeApiKeys',
summary: 'Get me api keys',
tags: ['Account'],
responses: {
'200': {
description: 'The operation completed successfully.',
content: {
'application/json': {
schema: {
type: 'array',
items: {
type: 'object',
properties: {
id: {
type: 'string',
},
createdAt: {
type: 'string',
format: 'date-time',
},
name: {
type: 'string',
},
keyPrefix: {
type: 'string',
},
lastUsedAt: {
type: 'string',
format: 'date-time',
},
},
required: ['id', 'createdAt', 'name', 'keyPrefix', 'lastUsedAt'],
},
},
},
},
},
'401': {
description: 'Unauthorized.',
content: {
'application/json': {
example: {
error: {
message: 'Unauthorized.',
code: 'unauthorized',
status: 401,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
'404': {
description: 'Not found.',
content: {
'application/json': {
example: {
error: {
message: 'Not found.',
code: 'not-found',
status: 404,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
},
} as ZodOpenApiOperationObject,
});
const operation2 = defineOperation({
method: 'post',
path: '/api/me/api-keys',
audience: 'public',
auth: 'bearer',
operation: {
operationId: 'postMeApiKeys',
summary: 'Create or update me api keys',
tags: ['Account'],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
properties: {
name: {
minimum: 1,
maximum: 255,
},
},
required: ['name'],
},
},
},
},
responses: {
'200': {
description: 'The operation completed successfully.',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
key: {
type: 'string',
},
id: {
type: 'string',
},
createdAt: {
type: 'string',
format: 'date-time',
},
name: {
type: 'string',
},
keyPrefix: {
type: 'string',
},
},
required: ['key', 'id', 'createdAt', 'name', 'keyPrefix'],
},
},
},
},
'400': {
description: 'Bad request.',
content: {
'application/json': {
example: {
error: {
message: 'Bad request.',
code: 'bad-request',
status: 400,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
'401': {
description: 'Unauthorized.',
content: {
'application/json': {
example: {
error: {
message: 'Unauthorized.',
code: 'unauthorized',
status: 401,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
'404': {
description: 'Not found.',
content: {
'application/json': {
example: {
error: {
message: 'Not found.',
code: 'not-found',
status: 404,
},
},
schema: {
$ref: '#/components/schemas/ApiError',
},
},
},
},
},
} as ZodOpenApiOperationObject,
});
export const operations = [operation1, operation2] as const;
+100
View File
@@ -0,0 +1,100 @@
import { beforeEach, expect, test, vi } from 'vitest';
import { parseRequest } from '@/lib/request';
import { GET, POST } from './route';
const mocks = vi.hoisted(() => ({
createApiKey: vi.fn(),
getUserApiKeys: vi.fn(),
}));
vi.mock('@/lib/request', () => ({
parseRequest: vi.fn(),
}));
vi.mock('@/queries/prisma/apiKey', () => ({
createApiKey: mocks.createApiKey,
getUserApiKeys: mocks.getUserApiKeys,
}));
const parseRequestMock = vi.mocked(parseRequest);
beforeEach(() => {
vi.unstubAllEnvs();
vi.stubEnv('CLOUD_MODE', '');
parseRequestMock.mockReset();
mocks.createApiKey.mockReset();
mocks.getUserApiKeys.mockReset();
parseRequestMock.mockResolvedValue({
auth: { user: { id: 'user-1' } },
body: { name: 'CI pipeline' },
error: undefined,
});
});
test('GET returns the current user api keys', async () => {
const keys = [{ id: 'key-1', name: 'CI pipeline', keyPrefix: 'umami_abcdefgh' }];
mocks.getUserApiKeys.mockResolvedValue(keys as any);
const response = await GET(new Request('http://localhost/api/me/api-keys'));
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual(keys);
expect(mocks.getUserApiKeys).toHaveBeenCalledWith('user-1');
});
test('GET returns 404 in cloud mode', async () => {
vi.stubEnv('CLOUD_MODE', '1');
const response = await GET(new Request('http://localhost/api/me/api-keys'));
expect(response.status).toBe(404);
expect(mocks.getUserApiKeys).not.toHaveBeenCalled();
});
test('GET returns the auth error when unauthenticated', async () => {
parseRequestMock.mockResolvedValue({
auth: null,
error: () => new Response(null, { status: 401 }),
});
const response = await GET(new Request('http://localhost/api/me/api-keys'));
expect(response.status).toBe(401);
});
test('POST creates a key, stores only the hash, and returns the plaintext once', async () => {
mocks.createApiKey.mockImplementation(async data => ({
id: data.id,
name: data.name,
keyPrefix: data.keyPrefix,
createdAt: new Date('2026-01-01T00:00:00Z'),
}));
const response = await POST(new Request('http://localhost/api/me/api-keys', { method: 'POST' }));
expect(response.status).toBe(200);
const body = await response.json();
expect(body.key).toMatch(/^umami_[0-9a-zA-Z]{32}$/);
expect(body.name).toBe('CI pipeline');
expect(body.keyPrefix).toBe(body.key.slice(0, 14));
expect(body).not.toHaveProperty('keyHash');
const stored = mocks.createApiKey.mock.calls[0][0];
expect(stored.userId).toBe('user-1');
expect(stored.keyHash).not.toBe(body.key);
expect(stored.keyHash).toHaveLength(128);
expect(stored).not.toHaveProperty('key');
});
test('POST returns 404 in cloud mode', async () => {
vi.stubEnv('CLOUD_MODE', '1');
const response = await POST(new Request('http://localhost/api/me/api-keys', { method: 'POST' }));
expect(response.status).toBe(404);
expect(mocks.createApiKey).not.toHaveBeenCalled();
});
+49
View File
@@ -0,0 +1,49 @@
import { z } from 'zod';
import { generateApiKey, getApiKeyPrefix, hashApiKey, isApiKeyEnabled } from '@/lib/api-key';
import { uuid } from '@/lib/crypto';
import { parseRequest } from '@/lib/request';
import { json, notFound } from '@/lib/response';
import { createApiKey, getUserApiKeys } from '@/queries/prisma/apiKey';
export async function GET(request: Request) {
const { auth, error } = await parseRequest(request);
if (error) {
return error();
}
if (!isApiKeyEnabled()) {
return notFound();
}
return json(await getUserApiKeys(auth.user.id));
}
export async function POST(request: Request) {
const schema = z.object({
name: z.string().trim().min(1).max(255),
});
const { auth, body, error } = await parseRequest(request, schema);
if (error) {
return error();
}
if (!isApiKeyEnabled()) {
return notFound();
}
const key = generateApiKey();
const apiKey = await createApiKey({
id: uuid(),
userId: auth.user.id,
name: body.name,
keyHash: hashApiKey(key),
keyPrefix: getApiKeyPrefix(key),
});
// The plaintext key is only returned once, at creation time.
return json({ ...apiKey, key });
}
+12
View File
@@ -38,6 +38,18 @@ const operation1 = defineOperation({
},
required: ['id', 'username', 'role', 'isAdmin'],
},
apiKey: {
type: 'object',
properties: {
id: {
type: 'string',
},
name: {
type: 'string',
},
},
required: ['id', 'name'],
},
shareToken: {
type: 'object',
properties: {