Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/db/src/api-key-schema.test.ts
T

60 lines
2.9 KiB
TypeScript

import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import { readBaselineLegacyMigration } from "./baseline-legacy-migration.test-helper";
const repoRoot = resolve(__dirname, "../../..");
const schemaPath = resolve(repoRoot, "prisma/schema/core.prisma");
async function readApiKeyModel() {
const schema = await readFile(schemaPath, "utf8");
const match = schema.match(/model ApiKey \{(?<body>[\s\S]*?)\n\}/);
expect(match?.groups?.body, "ApiKey model exists in core Prisma schema").toBeTruthy();
return match?.groups?.body ?? "";
}
describe("ApiKey hash schema contract", () => {
it("keeps the legacy plaintext key while defining nullable hash metadata", async () => {
const apiKeyModel = await readApiKeyModel();
expect(apiKeyModel, "legacy plaintext key remains available for cutover").toMatch(
/^\s*key\s+String\s+@default\(uuid\(\)\)/m,
);
expect(apiKeyModel, "keyHash is nullable until existing keys are backfilled").toMatch(/^\s*keyHash\s+String\?/m);
expect(apiKeyModel, "keyPrefix is nullable lookup/display metadata").toMatch(/^\s*keyPrefix\s+String\?/m);
expect(apiKeyModel, "keyLastFour is nullable display metadata").toMatch(/^\s*keyLastFour\s+String\?/m);
expect(apiKeyModel, "hashedAt is nullable until each key is hashed").toMatch(/^\s*hashedAt\s+DateTime\?/m);
expect(apiKeyModel, "keyVersion defaults new rows onto the initial hash version").toMatch(
/^\s*keyVersion\s+Int\s+@default\(1\)/m,
);
});
it("adds forward-only hash columns and lookup index without raw key fixtures", async () => {
const migrationSql = readBaselineLegacyMigration("20260507123000_api_key_hash_columns");
expect(migrationSql, "migration adds nullable keyHash storage").toMatch(
/ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]keyHash["`]\s+TEXT/i,
);
expect(migrationSql, "migration adds nullable keyPrefix metadata").toMatch(
/ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]keyPrefix["`]\s+TEXT/i,
);
expect(migrationSql, "migration adds nullable keyLastFour metadata").toMatch(
/ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]keyLastFour["`]\s+TEXT/i,
);
expect(migrationSql, "migration adds nullable hashedAt metadata").toMatch(
/ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]hashedAt["`]\s+TIMESTAMP(?:\(\d+\))?/i,
);
expect(migrationSql, "migration adds defaulted keyVersion metadata").toMatch(
/ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]keyVersion["`]\s+INTEGER\s+NOT\s+NULL\s+DEFAULT\s+1/i,
);
expect(migrationSql, "migration creates the unique hash lookup index").toMatch(
/CREATE\s+UNIQUE\s+INDEX\s+["`]api_key_hash_key["`]\s+ON\s+["`]ApiKey["`]\s*\(\s*["`]keyHash["`]\s*\)/i,
);
expect(migrationSql, "migration must not persist raw API-key fixtures").not.toContain("raw-secret");
});
});