Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 0 additions & 19 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -496,25 +496,6 @@ export const createApp = (dependencies?: Partial<AppDependencies>) => {
vaultController.getBalance(req, res);
});

// Revoke API key endpoint
app.delete('/api/keys/:id', requireAuth, (req, res: express.Response<unknown, AuthenticatedLocals>, next) => {
const user = res.locals.authenticatedUser;
if (!user) {
next(new UnauthorizedError());
return;
}

const { id } = req.params;
const result = apiKeyRepository.revoke(id, user.id);

if (result === 'forbidden') {
next(new ForbiddenError());
return;
}

res.status(204).send();
});

/**
* POST /api/developers/apis
*
Expand Down
31 changes: 31 additions & 0 deletions src/repositories/apiKeyRepository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ describe("ApiKeyRepository Security Tests", () => {
expect(storedKey.keyHash).not.toBe(result.key);
expect(storedKey.keyHash).not.toContain(result.key);
expect(storedKey.keyHash.length).toBeGreaterThan(50); // bcrypt hashes are long
expect(result.id).toBeTruthy();
expect(result.createdAt).toBeInstanceOf(Date);
});

it("should use different salts for different keys", () => {
Expand Down Expand Up @@ -267,6 +269,35 @@ describe("ApiKeyRepository Security Tests", () => {
});

describe("Error Handling and Edge Cases", () => {
it("lists keys for a specific user and API", () => {
apiKeyRepository.create({
apiId: "api-1",
userId: "user-1",
scopes: ["*"],
rateLimitPerMinute: null,
});
apiKeyRepository.create({
apiId: "api-2",
userId: "user-1",
scopes: ["read"],
rateLimitPerMinute: 60,
});
apiKeyRepository.create({
apiId: "api-1",
userId: "user-2",
scopes: ["write"],
rateLimitPerMinute: null,
});

const userKeys = apiKeyRepository.list({ userId: "user-1" });
const apiKeys = apiKeyRepository.list({ userId: "user-1", apiId: "api-1" });

expect(userKeys).toHaveLength(2);
expect(apiKeys).toHaveLength(1);
expect(apiKeys[0].apiId).toBe("api-1");
expect(apiKeys[0].userId).toBe("user-1");
});

it("should handle concurrent operations safely", () => {
const userId = "user-1";
const promises = Array.from({ length: 10 }, (_, i) =>
Expand Down
30 changes: 24 additions & 6 deletions src/repositories/apiKeyRepository.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createHash, randomBytes, timingSafeEqual } from "crypto";
import { randomBytes, timingSafeEqual } from "crypto";
import bcrypt from "bcryptjs";
import { config } from "../config/index.js";

Expand All @@ -16,6 +16,13 @@ export interface ApiKeyRecord {

const apiKeys: ApiKeyRecord[] = [];

export interface ApiKeyCreateResult {
id: string;
key: string;
prefix: string;
createdAt: Date;
}

function generatePlainKey(): string {
return `ck_live_${randomBytes(24).toString("hex")}`;
}
Expand Down Expand Up @@ -47,24 +54,35 @@ export const apiKeyRepository = {
userId: string;
scopes: string[];
rateLimitPerMinute: number | null;
}): { key: string; prefix: string } {
const p = params || {} as any;
}): ApiKeyCreateResult {
const p = params as any;
const key = generatePlainKey();
const prefix = key.slice(0, 16);
const id = randomBytes(8).toString('hex');
const createdAt = new Date();

apiKeys.push({
id: randomBytes(8).toString('hex'),
id,
apiId: p.apiId,
userId: p.userId,
prefix,
keyHash: toHash(key),
scopes: p.scopes,
rateLimitPerMinute: p.rateLimitPerMinute,
createdAt: new Date(),
createdAt,
revoked: false
});

return { key, prefix };
return { id, key, prefix, createdAt };
},
list(params: { userId: string; apiId?: string }): ApiKeyRecord[] {
const { userId, apiId } = params;
return apiKeys
.filter((record) =>
record.userId === userId &&
(apiId === undefined || record.apiId === apiId)
)
.map((record) => ({ ...record }));
},
revoke(id: string, userId: string): 'success' | 'not_found' | 'forbidden' {
const key = apiKeys.find(k => k.id === id);
Expand Down
Loading
Loading