import { describe, expect, it } from "vitest"; import { hasScope } from "../src/http/auth.ts"; import { DEV_KEY, json, memoryStore, testApp } from "./helpers.ts"; const store = memoryStore({ "key-read": { id: "k1", scopes: ["read"] }, "key-org": { id: "k2", scopes: ["organize.execute"] }, "key-revoked": { id: "k3", scopes: ["admin"], revoked: true }, }); const whoami = (app: ReturnType["app"], key?: string) => app.request("/api/v1/auth/whoami", key ? { headers: { Authorization: `Bearer ${key}` } } : {}); describe("API Key 鉴权", () => { it("缺少 Key → 401", async () => { const res = await whoami(testApp({ store }).app); expect(res.status).toBe(401); expect((await json(res)).error.code).toBe("unauthorized"); }); it("有效 Key 通过,返回 principal", async () => { const res = await whoami(testApp({ store }).app, "key-read"); expect(res.status).toBe(200); expect((await json(res)).data.id).toBe("k1"); }); it("未知或已撤销 Key → 401", async () => { const { app } = testApp({ store }); expect((await whoami(app, "bogus")).status).toBe(401); expect((await whoami(app, "key-revoked")).status).toBe(401); }); it("scope 不足 → 403", async () => { const res = await whoami(testApp({ store }).app, "key-org"); expect(res.status).toBe(403); expect((await json(res)).error.code).toBe("forbidden"); }); it("开发模式 DEV_ADMIN_KEY 可用,生产模式不可用", async () => { expect((await whoami(testApp({ store }).app, DEV_KEY)).status).toBe(200); expect((await whoami(testApp({ store, nodeEnv: "production" }).app, DEV_KEY)).status).toBe(401); }); it("scope 蕴含关系", () => { expect(hasScope(["admin"], "organize.execute")).toBe(true); expect(hasScope(["organize.execute"], "organize.read")).toBe(true); expect(hasScope(["organize.read"], "organize.execute")).toBe(false); expect(hasScope(["read"], "organize.read")).toBe(false); }); });