Reorganize repo structure and standards references

This commit is contained in:
david committed 2026-06-29 05:03:42 +02:00
1 parent 3cb93a81be
commit be2054274d
5885 files changed
+2588 -195

No files matched your search

@@ -0,0 +1,750 @@
import { describe, expect, it, vi } from "vitest";
import {
adminFindLegacyApiKeyById,
adminDeleteLegacyApiKeyLogsByIds,
countLegacyApiKeyLogsForKey,
countLegacyTenantApiKeyLogs,
countLegacyApiKeyLogs,
createLegacyApiKeyLog,
createLegacyApiKey,
deleteLegacyApiKey,
deleteTenantLegacyApiKeyLogsByIds,
findLegacyApiKeyByKey,
findLegacyApiKeyByAlias,
findLegacyApiKeyById,
findFirstLegacyActiveApiKey,
getAllLegacyApiKeys,
getLegacyApiKeyLogsForKey,
getLegacyApiKeysForTenant,
getLegacyApiKeyLogAdminDetails,
groupLegacyApiKeyLogs,
legacyApiKeyDetailsInclude,
rotateLegacyApiKey,
setLegacyApiKeyLogStatus,
tenantLegacyApiKeyLogScope,
updateLegacyApiKey,
deriveLegacyApiKeyHashMetadata,
backfillLegacyApiKeyHashes,
DEFAULT_LEGACY_API_KEY_HASH_BACKFILL_BATCH_SIZE,
type LegacyApiKeyHashBackfillClient,
type LegacyApiKeyLogWriterClient,
type LegacyApiKeyRotationClient,
type LegacyApiKeyReaderClient,
} from "./api-keys.server.js";
function createApiKeyHashBackfillClient(rows: Awaited<ReturnType<LegacyApiKeyHashBackfillClient["apiKey"]["findMany"]>>): LegacyApiKeyHashBackfillClient {
return {
apiKey: {
findMany: vi.fn().mockResolvedValue(rows),
update: vi.fn().mockResolvedValue({}),
},
};
}
function createApiKeyRotationClient(): LegacyApiKeyRotationClient {
return {
apiKey: {
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
findFirst: vi.fn().mockImplementation(() => Promise.resolve({ id: "api_key_1", tenantId: "tenant_1", key: "rotated-secret" })),
},
};
}
function createApiKeyLogClient(): LegacyApiKeyLogWriterClient & LegacyApiKeyReaderClient {
return {
apiKey: {
create: vi.fn().mockResolvedValue({ id: "api_key_1", key: "raw-secret" }),
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
findUnique: vi.fn().mockResolvedValue({ id: "api_key_1", tenantId: "tenant_1", key: "updated-secret" }),
findFirst: vi.fn().mockResolvedValue(null),
deleteMany: vi.fn().mockResolvedValue({ count: 1 }),
findMany: vi.fn().mockResolvedValue([]),
},
apiKeyEntity: {
create: vi.fn().mockResolvedValue({}),
deleteMany: vi.fn().mockResolvedValue({ count: 1 }),
},
entity: {
findMany: vi.fn().mockImplementation(({ where }: { where: { id: { in: string[] } } }) => {
return Promise.resolve(where.id.in.map((id) => ({ id })));
}),
},
apiKeyLog: {
create: vi.fn().mockResolvedValue({ id: "log_1" }),
findMany: vi.fn().mockResolvedValue([]),
groupBy: vi.fn().mockResolvedValue([]),
update: vi.fn().mockResolvedValue({}),
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
count: vi.fn().mockResolvedValue(3),
deleteMany: vi.fn().mockResolvedValue({ count: 2 }),
},
} as unknown as LegacyApiKeyLogWriterClient & LegacyApiKeyReaderClient;
}
describe("legacy API key log writes", () => {
it("updates status and calculates duration when a start time is provided", async () => {
const client = createApiKeyLogClient();
vi.spyOn(performance, "now").mockReturnValue(25);
await setLegacyApiKeyLogStatus({ id: "log_1", tenantId: "tenant_1" }, { status: 200, startTime: 10 }, client);
expect(client.apiKeyLog.updateMany).toHaveBeenCalledWith({
where: { id: "log_1", tenantId: "tenant_1" },
data: {
status: 200,
error: undefined,
duration: 15,
},
});
});
it("persists errors without calculating duration for synthetic failures", async () => {
const client = createApiKeyLogClient();
await setLegacyApiKeyLogStatus({ id: "log_1", tenantId: "tenant_1" }, { status: 400, startTime: null, error: "Invalid API key" }, client);
expect(client.apiKeyLog.updateMany).toHaveBeenCalledWith({
where: { id: "log_1", tenantId: "tenant_1" },
data: {
status: 400,
error: "Invalid API key",
duration: null,
},
});
});
it("updates status with tenant scope when provided", async () => {
const client = createApiKeyLogClient();
await expect(setLegacyApiKeyLogStatus({ id: "log_1", tenantId: "tenant_1" }, { status: 200, startTime: null }, client)).resolves.toEqual({
count: 1,
});
expect(client.apiKeyLog.updateMany).toHaveBeenCalledWith({
where: { id: "log_1", tenantId: "tenant_1" },
data: {
status: 200,
error: undefined,
duration: null,
},
});
expect(client.apiKeyLog.update).not.toHaveBeenCalled();
});
it("rejects tenant-scoped status updates that miss", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.apiKeyLog.updateMany).mockResolvedValue({ count: 0 });
await expect(setLegacyApiKeyLogStatus({ id: "log_foreign", tenantId: "tenant_1" }, { status: 404, startTime: null }, client)).rejects.toThrow(
"API key log log_foreign not found"
);
});
it("counts tenant API key logs through the package boundary", async () => {
const client = createApiKeyLogClient();
await expect(countLegacyTenantApiKeyLogs("tenant_1", client)).resolves.toBe(3);
expect(client.apiKeyLog.count).toHaveBeenCalledWith({
where: tenantLegacyApiKeyLogScope("tenant_1"),
});
});
it("fetches API key lists and details through the package boundary", async () => {
const client = createApiKeyLogClient();
const apiKey = {
id: "api_key_1",
alias: "Production",
expires: null,
tenantId: "tenant_1",
active: true,
entities: [],
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
_count: { apiKeyLogs: 0 },
};
vi.mocked(client.apiKey.findMany).mockResolvedValue([apiKey] as never);
vi.mocked(client.apiKey.findUnique).mockResolvedValue(apiKey as never);
vi.mocked(client.apiKey.findFirst).mockResolvedValue(apiKey as never);
await expect(getAllLegacyApiKeys(client)).resolves.toEqual([apiKey]);
expect(client.apiKey.findMany).toHaveBeenCalledWith({
include: legacyApiKeyDetailsInclude,
orderBy: { createdAt: "desc" },
});
await expect(getLegacyApiKeysForTenant("tenant_1", client)).resolves.toEqual([apiKey]);
expect(client.apiKey.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
include: legacyApiKeyDetailsInclude,
orderBy: { createdAt: "desc" },
});
await expect(adminFindLegacyApiKeyById("api_key_1", client)).resolves.toBe(apiKey);
expect(client.apiKey.findUnique).toHaveBeenCalledWith({
where: { id: "api_key_1" },
include: legacyApiKeyDetailsInclude,
});
await expect(findLegacyApiKeyById({ id: "api_key_1", tenantId: "tenant_1" }, client)).resolves.toBe(apiKey);
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
include: legacyApiKeyDetailsInclude,
});
await expect(findLegacyApiKeyByAlias("tenant_1", "Production", client)).resolves.toBe(apiKey);
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", alias: "Production" },
include: legacyApiKeyDetailsInclude,
});
});
it("fetches logs for one API key with tenant details", async () => {
const client = createApiKeyLogClient();
await expect(getLegacyApiKeyLogsForKey({ id: "api_key_1", tenantId: "tenant_1" }, client)).resolves.toEqual([]);
expect(client.apiKeyLog.findMany).toHaveBeenCalledWith({
where: {
apiKeyId: "api_key_1",
tenantId: "tenant_1",
},
include: {
apiKey: {
include: {
tenant: true,
},
},
},
orderBy: {
createdAt: "desc",
},
});
});
it("counts logs for one API key through direct tenant scope", async () => {
const client = createApiKeyLogClient();
await expect(countLegacyApiKeyLogsForKey({ id: "api_key_1", tenantId: "tenant_1" }, client)).resolves.toBe(3);
expect(client.apiKeyLog.count).toHaveBeenCalledWith({
where: {
apiKeyId: "api_key_1",
tenantId: "tenant_1",
},
});
});
it("groups API key logs for admin summaries", async () => {
const client = createApiKeyLogClient();
await expect(groupLegacyApiKeyLogs({ by: ["method", "endpoint"], where: { tenantId: "tenant_1" } }, client)).resolves.toEqual([]);
expect(client.apiKeyLog.groupBy).toHaveBeenCalledWith({
by: ["method", "endpoint"],
where: { tenantId: "tenant_1" },
_avg: { duration: true },
_count: { _all: true },
orderBy: {
_avg: { duration: "desc" },
},
});
});
it("fetches paginated API key log admin details", async () => {
const client = createApiKeyLogClient();
await expect(
getLegacyApiKeyLogAdminDetails(
{
take: 10,
skip: 20,
where: { tenantId: "tenant_1" },
includeTenant: true,
orderBy: { createdAt: "desc" },
},
client,
),
).resolves.toEqual([]);
expect(client.apiKeyLog.findMany).toHaveBeenCalledWith({
take: 10,
skip: 20,
where: { tenantId: "tenant_1" },
include: {
apiKey: {
select: { alias: true, tenant: { select: { id: true, name: true } } },
},
tenant: { select: { id: true, name: true, slug: true } },
},
orderBy: { createdAt: "desc" },
});
});
it("counts and deletes API key logs through the package boundary", async () => {
const client = createApiKeyLogClient();
await expect(countLegacyApiKeyLogs({ tenantId: "tenant_1" }, client)).resolves.toBe(3);
expect(client.apiKeyLog.count).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
});
await expect(adminDeleteLegacyApiKeyLogsByIds(["log_1", "log_2"], client)).resolves.toEqual({ count: 2 });
expect(client.apiKeyLog.deleteMany).toHaveBeenCalledWith({
where: { id: { in: ["log_1", "log_2"] } },
});
await expect(deleteTenantLegacyApiKeyLogsByIds({ ids: ["log_1", "log_2"], tenantId: "tenant_1" }, client)).resolves.toEqual({ count: 2 });
expect(client.apiKeyLog.deleteMany).toHaveBeenLastCalledWith({
where: {
id: { in: ["log_1", "log_2"] },
...tenantLegacyApiKeyLogScope("tenant_1"),
},
});
});
it("fetches the first active tenant API key", async () => {
const client = createApiKeyLogClient();
const apiKey = { id: "api_key_1", tenantId: "tenant_1", active: true };
vi.mocked(client.apiKey.findFirst).mockResolvedValue(apiKey as never);
await expect(findFirstLegacyActiveApiKey("tenant_1", client)).resolves.toBe(apiKey);
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
active: true,
},
});
});
it("creates API keys with deterministic hash metadata and returns plaintext only once", async () => {
const client = createApiKeyLogClient();
const expires = new Date("2026-05-01T00:00:00.000Z");
const key = "api_test_plaintext_secret";
const expectedMetadata = deriveLegacyApiKeyHashMetadata(key, "hash-secret");
await expect(
createLegacyApiKey(
{
tenantId: "tenant_1",
createdByUserId: "user_1",
alias: "Production",
expires,
active: false,
key,
},
[{ entityId: "entity_1", create: true, read: true, update: false, delete: false }],
client,
"hash-secret",
),
).resolves.toEqual({ id: "api_key_1", key });
expect(client.apiKey.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: "tenant_1",
createdByUserId: "user_1",
alias: "Production",
expires,
active: false,
key,
keyHash: expectedMetadata.keyHash,
keyPrefix: "api_test",
keyLastFour: "cret",
keyVersion: 1,
}),
});
expect(vi.mocked(client.apiKey.create).mock.calls[0]?.[0].data.hashedAt).toBeInstanceOf(Date);
expect(client.apiKeyEntity.create).toHaveBeenCalledWith({
data: {
apiKeyId: "api_key_1",
entityId: "entity_1",
create: true,
read: true,
update: false,
delete: false,
},
});
expect(client.entity.findMany).toHaveBeenCalledWith({
where: {
id: { in: ["entity_1"] },
active: true,
hasApi: true,
type: { in: ["app", "all"] },
},
select: { id: true },
});
});
it("rejects API key entity scopes outside tenant API-eligible entities", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.entity.findMany).mockResolvedValue([{ id: "entity_allowed" }]);
await expect(
createLegacyApiKey(
{
tenantId: "tenant_1",
createdByUserId: "user_1",
alias: "Production",
expires: null,
active: true,
key: "api_test_plaintext_secret",
},
[
{ entityId: "entity_allowed", create: true, read: true, update: false, delete: false },
{ entityId: "entity_admin", create: true, read: true, update: true, delete: true },
],
client,
"hash-secret",
),
).rejects.toThrow("API key entity scope is not allowed");
expect(client.apiKey.create).not.toHaveBeenCalled();
expect(client.apiKeyEntity.create).not.toHaveBeenCalled();
});
it("derives stable and distinct API key hashes", () => {
const hashedAt = new Date("2026-05-07T12:30:00.000Z");
const first = deriveLegacyApiKeyHashMetadata("api_test_plaintext_secret", "hash-secret", hashedAt);
const second = deriveLegacyApiKeyHashMetadata("api_test_plaintext_secret", "hash-secret", hashedAt);
const different = deriveLegacyApiKeyHashMetadata("api_test_plaintext_other", "hash-secret", hashedAt);
expect(first).toEqual(second);
expect(first.keyHash).not.toBe(different.keyHash);
expect(first).toMatchObject({
keyPrefix: "api_test",
keyLastFour: "cret",
hashedAt,
keyVersion: 1,
});
});
it("backfills legacy plaintext API key hash metadata in a bounded batch", async () => {
const hashedAt = new Date("2026-05-07T13:00:00.000Z");
const client = createApiKeyHashBackfillClient([
{ id: "api_key_1", key: "api_test_plaintext_secret", keyHash: null, hashedAt: null },
{ id: "api_key_2", key: "api_test_plaintext_other", keyHash: null, hashedAt: null },
]);
await expect(backfillLegacyApiKeyHashes({ batchSize: 2, hashSecret: "hash-secret", now: hashedAt, client })).resolves.toEqual({
scanned: 2,
updated: 2,
skipped: 0,
failed: 0,
failures: [],
});
expect(client.apiKey.findMany).toHaveBeenCalledWith({
take: 2,
where: { OR: [{ keyHash: null }, { hashedAt: null }] },
select: { id: true, key: true, keyHash: true, hashedAt: true },
orderBy: { createdAt: "asc" },
});
expect(client.apiKey.update).toHaveBeenNthCalledWith(1, {
where: { id: "api_key_1" },
data: deriveLegacyApiKeyHashMetadata("api_test_plaintext_secret", "hash-secret", hashedAt),
});
expect(client.apiKey.update).toHaveBeenNthCalledWith(2, {
where: { id: "api_key_2" },
data: deriveLegacyApiKeyHashMetadata("api_test_plaintext_other", "hash-secret", hashedAt),
});
});
it("uses the default backfill batch size and skips guarded rows", async () => {
const existingHash = deriveLegacyApiKeyHashMetadata("api_test_already_hashed", "hash-secret");
const client = createApiKeyHashBackfillClient([
{ id: "api_key_empty", key: "", keyHash: null, hashedAt: null },
{ id: "api_key_hashed", key: "api_test_already_hashed", keyHash: existingHash.keyHash, hashedAt: null },
{ id: "api_key_timestamped", key: "api_test_timestamped", keyHash: null, hashedAt: existingHash.hashedAt },
]);
await expect(backfillLegacyApiKeyHashes({ client })).resolves.toEqual({
scanned: 3,
updated: 0,
skipped: 3,
failed: 0,
failures: [],
});
expect(client.apiKey.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: DEFAULT_LEGACY_API_KEY_HASH_BACKFILL_BATCH_SIZE }));
expect(client.apiKey.update).not.toHaveBeenCalled();
});
it("records per-row backfill failures by id only and continues the batch", async () => {
const leakedSecret = "api_test_plaintext_secret";
const client = createApiKeyHashBackfillClient([
{ id: "api_key_fails", key: leakedSecret, keyHash: null, hashedAt: null },
{ id: "api_key_succeeds", key: "api_test_plaintext_other", keyHash: null, hashedAt: null },
]);
vi.mocked(client.apiKey.update)
.mockRejectedValueOnce(new Error(`unique constraint leaked ${leakedSecret}`))
.mockResolvedValueOnce({});
const result = await backfillLegacyApiKeyHashes({ hashSecret: "hash-secret", now: new Date("2026-05-07T13:00:00.000Z"), client });
expect(result).toEqual({
scanned: 2,
updated: 1,
skipped: 0,
failed: 1,
failures: [{ id: "api_key_fails", error: "Error" }],
});
expect(JSON.stringify(result)).not.toContain(leakedSecret);
expect(client.apiKey.update).toHaveBeenCalledTimes(2);
});
it("rotates API keys with new plaintext and persisted hash metadata", async () => {
const client = createApiKeyRotationClient();
const oldMetadata = deriveLegacyApiKeyHashMetadata("old-secret", "hash-secret");
const rotated = await rotateLegacyApiKey({ id: "api_key_1", tenantId: "tenant_1" }, client, "hash-secret");
expect(rotated.key).toEqual(expect.any(String));
expect(rotated.key).not.toBe("old-secret");
expect(client.apiKey.updateMany).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
data: expect.objectContaining({
key: rotated.key,
keyHash: deriveLegacyApiKeyHashMetadata(rotated.key, "hash-secret").keyHash,
keyPrefix: rotated.key.slice(0, 8),
keyLastFour: rotated.key.slice(-4),
keyVersion: 1,
}),
});
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
});
expect(vi.mocked(client.apiKey.updateMany).mock.calls[0]?.[0].data.keyHash).not.toBe(oldMetadata.keyHash);
expect(vi.mocked(client.apiKey.updateMany).mock.calls[0]?.[0].data.hashedAt).toBeInstanceOf(Date);
});
it("redacts generated plaintext from rotation update errors", async () => {
const client = createApiKeyRotationClient();
vi.mocked(client.apiKey.updateMany).mockRejectedValue(new Error("database unavailable"));
await expect(rotateLegacyApiKey({ id: "api_key_1", tenantId: "tenant_1" }, client, "hash-secret")).rejects.toThrow("database unavailable");
const generatedKey = vi.mocked(client.apiKey.updateMany).mock.calls[0]?.[0].data.key;
await expect(rotateLegacyApiKey({ id: "api_key_1", tenantId: "tenant_1" }, client, "hash-secret")).rejects.not.toThrow(generatedKey);
});
it("keeps rotated API key validation hash-first and rejects old plaintext after persistence", async () => {
const client = createApiKeyLogClient();
const oldKey = "api_test_old_plaintext";
const newKey = "api_test_new_plaintext";
const apiKey = {
id: "api_key_1",
alias: "Production",
expires: null,
tenantId: "tenant_1",
active: true,
entities: [],
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
};
vi.mocked(client.apiKey.findFirst).mockImplementation(({ where }) => {
if ("keyHash" in where && where.keyHash === deriveLegacyApiKeyHashMetadata(newKey, "hash-secret").keyHash) {
return Promise.resolve(apiKey) as never;
}
return Promise.resolve(null) as never;
});
await expect(findLegacyApiKeyByKey(newKey, client, "hash-secret")).resolves.toBe(apiKey);
await expect(findLegacyApiKeyByKey(oldKey, client, "hash-secret")).resolves.toBeNull();
expect(client.apiKey.findFirst).toHaveBeenNthCalledWith(1, {
where: { keyHash: deriveLegacyApiKeyHashMetadata(newKey, "hash-secret").keyHash },
select: expect.any(Object),
});
expect(client.apiKey.findFirst).toHaveBeenNthCalledWith(2, expect.objectContaining({
where: { keyHash: deriveLegacyApiKeyHashMetadata(oldKey, "hash-secret").keyHash },
}));
});
it("updates API keys and replaces entity permissions", async () => {
const client = createApiKeyLogClient();
const expires = new Date("2026-05-01T00:00:00.000Z");
vi.mocked(client.apiKey.findFirst).mockResolvedValue({ id: "api_key_1", tenantId: "tenant_1", key: "updated-secret" } as never);
await expect(
updateLegacyApiKey(
"api_key_1",
{
tenantId: "tenant_1",
alias: "Production",
expires,
active: true,
},
[{ entityId: "entity_1", create: false, read: true, update: true, delete: false }],
client,
),
).resolves.toEqual({ id: "api_key_1", tenantId: "tenant_1", key: "updated-secret" });
expect(client.apiKey.updateMany).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
data: {
tenantId: "tenant_1",
alias: "Production",
expires,
active: true,
},
});
expect(client.apiKeyEntity.deleteMany).toHaveBeenCalledWith({
where: {
apiKeyId: "api_key_1",
apiKey: { tenantId: "tenant_1" },
},
});
expect(client.apiKeyEntity.create).toHaveBeenCalledWith({
data: {
apiKeyId: "api_key_1",
entityId: "entity_1",
create: false,
read: true,
update: true,
delete: false,
},
});
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
});
});
it("deletes API keys through the package boundary", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.apiKey.findFirst).mockResolvedValue({ id: "api_key_1", tenantId: "tenant_1", key: "deleted-secret" } as never);
await expect(deleteLegacyApiKey({ id: "api_key_1", tenantId: "tenant_1" }, client)).resolves.toEqual({ id: "api_key_1", tenantId: "tenant_1", key: "deleted-secret" });
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
});
expect(client.apiKey.deleteMany).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
});
});
it("returns null when no tenant id is provided for first active API key lookup", async () => {
const client = createApiKeyLogClient();
await expect(findFirstLegacyActiveApiKey(null, client)).resolves.toBeNull();
expect(client.apiKey.findFirst).not.toHaveBeenCalled();
});
it("finds tenant API keys by hash without selecting the secret back out", async () => {
const client = createApiKeyLogClient();
const apiKey = {
id: "api_key_1",
alias: "Production",
expires: null,
tenantId: "tenant_1",
active: true,
entities: [],
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
};
vi.mocked(client.apiKey.findFirst).mockResolvedValue(apiKey);
await expect(findLegacyApiKeyByKey("raw-secret", client, "hash-secret", { allowPlaintextFallback: true })).resolves.toBe(apiKey);
expect(client.apiKey.findFirst).toHaveBeenCalledTimes(1);
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { keyHash: deriveLegacyApiKeyHashMetadata("raw-secret", "hash-secret").keyHash },
select: {
id: true,
alias: true,
expires: true,
tenantId: true,
active: true,
entities: { select: { create: true, read: true, update: true, delete: true, entityId: true } },
tenant: { select: { id: true, name: true, slug: true, deactivatedReason: true } },
},
});
});
it("creates API key logs from normalized request data", async () => {
const client = createApiKeyLogClient();
const data = {
tenantId: "tenant_1",
apiKeyId: "api_key_1",
endpoint: "/v1/usage",
ip: "127.0.0.1",
method: "GET",
params: "tenantId=tenant_1",
status: 200,
};
await expect(createLegacyApiKeyLog(data, client)).resolves.toEqual({ id: "log_1" });
expect(client.apiKeyLog.create).toHaveBeenCalledWith({
data,
});
});
it("falls back to legacy raw-key lookup when hash lookup misses", async () => {
const client = createApiKeyLogClient();
const apiKey = {
id: "api_key_1",
alias: "Production",
expires: null,
tenantId: "tenant_1",
active: true,
entities: [],
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
};
vi.mocked(client.apiKey.findFirst).mockResolvedValueOnce(null).mockResolvedValueOnce(apiKey);
await expect(findLegacyApiKeyByKey("raw-secret", client, "hash-secret", { allowPlaintextFallback: true })).resolves.toBe(apiKey);
expect(client.apiKey.findFirst).toHaveBeenNthCalledWith(1, {
where: { keyHash: deriveLegacyApiKeyHashMetadata("raw-secret", "hash-secret").keyHash },
select: expect.any(Object),
});
expect(client.apiKey.findFirst).toHaveBeenNthCalledWith(2, {
where: { key: "raw-secret" },
select: expect.any(Object),
});
});
it("can disable legacy raw-key fallback after cutover", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.apiKey.findFirst).mockResolvedValue(null);
await expect(findLegacyApiKeyByKey("raw-secret", client, "hash-secret", { allowPlaintextFallback: false })).resolves.toBeNull();
expect(client.apiKey.findFirst).toHaveBeenCalledTimes(1);
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { keyHash: deriveLegacyApiKeyHashMetadata("raw-secret", "hash-secret").keyHash },
select: expect.any(Object),
});
});
it("does not fall back to raw-key lookup when hash lookup fails and fallback is disabled", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.apiKey.findFirst).mockRejectedValueOnce(new Error("hash index unavailable"));
await expect(findLegacyApiKeyByKey("raw-secret", client, "hash-secret", { allowPlaintextFallback: false })).resolves.toBeNull();
expect(client.apiKey.findFirst).toHaveBeenCalledTimes(1);
});
it("falls back to legacy raw-key lookup when hash lookup fails", async () => {
const client = createApiKeyLogClient();
const apiKey = {
id: "api_key_1",
alias: "Production",
expires: null,
tenantId: "tenant_1",
active: true,
entities: [],
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
};
vi.mocked(client.apiKey.findFirst).mockRejectedValueOnce(new Error("hash index unavailable")).mockResolvedValueOnce(apiKey);
await expect(findLegacyApiKeyByKey("raw-secret", client, "hash-secret", { allowPlaintextFallback: true })).resolves.toBe(apiKey);
expect(client.apiKey.findFirst).toHaveBeenCalledTimes(2);
});
it("keeps legacy raw-key fallback disabled by default", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.apiKey.findFirst).mockResolvedValue(null);
await expect(findLegacyApiKeyByKey("raw-secret", client, "hash-secret")).resolves.toBeNull();
expect(client.apiKey.findFirst).toHaveBeenCalledTimes(1);
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { keyHash: deriveLegacyApiKeyHashMetadata("raw-secret", "hash-secret").keyHash },
select: expect.any(Object),
});
});
it("preserves legacy null behavior when both API key lookups fail", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.apiKey.findFirst).mockRejectedValue(new Error("database unavailable"));
await expect(findLegacyApiKeyByKey("raw-secret", client)).resolves.toBeNull();
});
});