4
} from "@/src/features/public-api/lib/apiKeys";
5
import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
6
import { prisma } from "@/src/server/db";
8
describe("Validate api calls", () => {
9
beforeEach(async () => {
10
await prisma.score.deleteMany();
11
await prisma.observation.deleteMany();
12
await prisma.trace.deleteMany();
13
await prisma.apiKey.deleteMany();
16
it("should create new api key", async () => {
18
const auth = await verifyAuthHeaderAndReturnScope(
19
"Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
21
expect(auth.validKey).toBe(true);
23
const apiKey = await prisma.apiKey.findUnique({
24
where: { publicKey: "pk-lf-1234567890" },
26
expect(apiKey).not.toBeNull();
27
expect(apiKey?.fastHashedSecretKey).not.toBeNull();
30
it("should create new api key and succeed with new key", async () => {
32
const auth = await verifyAuthHeaderAndReturnScope(
33
"Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
35
expect(auth.validKey).toBe(true);
37
const apiKey = await prisma.apiKey.findUnique({
38
where: { publicKey: "pk-lf-1234567890" },
40
expect(apiKey).not.toBeNull();
41
expect(apiKey?.fastHashedSecretKey).not.toBeNull();
43
const auth2 = await verifyAuthHeaderAndReturnScope(
44
"Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
46
expect(auth2.validKey).toBe(true);
49
it("should fail on wrong api key with new key", async () => {
51
const auth = await verifyAuthHeaderAndReturnScope(
52
"Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
54
expect(auth.validKey).toBe(true);
56
const apiKey = await prisma.apiKey.findUnique({
57
where: { publicKey: "pk-lf-1234567890" },
59
expect(apiKey).not.toBeNull();
60
expect(apiKey?.fastHashedSecretKey).not.toBeNull();
62
const wrongAuth = await verifyAuthHeaderAndReturnScope(
63
"Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkx",
65
expect(wrongAuth.validKey).toBe(false);
68
it("should fail on wrong api key without new key", async () => {
70
const initialApiKey = await prisma.apiKey.findUnique({
71
where: { publicKey: "pk-lf-1234567890" },
73
expect(initialApiKey).not.toBeNull();
74
expect(initialApiKey?.fastHashedSecretKey).toBeNull();
76
const auth = await verifyAuthHeaderAndReturnScope(
77
"Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkx",
79
expect(auth.validKey).toBe(false);
81
const apiKey = await prisma.apiKey.findUnique({
82
where: { publicKey: "pk-lf-1234567890" },
84
expect(apiKey).not.toBeNull();
85
expect(apiKey?.fastHashedSecretKey).toBeNull();
88
const createAPIKey = async () => {
91
secret: "sk-lf-1234567890",
92
public: "pk-lf-1234567890",
95
await prisma.apiKey.create({
97
note: seedApiKey.note,
99
publicKey: seedApiKey.public,
100
hashedSecretKey: await hashSecretKey(seedApiKey.secret),
101
displaySecretKey: getDisplaySecretKey(seedApiKey.secret),
104
id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
111
afterAll(async () => {
112
await prisma.apiKey.deleteMany();
113
await createAPIKey();