|
| 1 | +/** |
| 2 | + * Unit tests for API key scoped permissions (#219): |
| 3 | + * - Legacy key migration defaults to write scope |
| 4 | + * - Read-only key rejected on write endpoints |
| 5 | + * - Write key allowed on write endpoints |
| 6 | + */ |
| 7 | + |
| 8 | +import { |
| 9 | + STORAGE_KEY, |
| 10 | + checkWriteScope, |
| 11 | + generateKeyValue, |
| 12 | + loadKeys, |
| 13 | + parseScopeFromKey, |
| 14 | +} from "@/lib/apiKeys"; |
| 15 | +import { generateSignedApiKey, verifySignedApiKey } from "@/lib/signedApiKeys"; |
| 16 | +import { POST as testWebhookPost } from "@/app/api/test-webhook/route"; |
| 17 | + |
| 18 | +const store: Record<string, string> = {}; |
| 19 | +const localStorageMock = { |
| 20 | + getItem: (k: string) => store[k] ?? null, |
| 21 | + setItem: (k: string, v: string) => { |
| 22 | + store[k] = v; |
| 23 | + }, |
| 24 | + removeItem: (k: string) => { |
| 25 | + delete store[k]; |
| 26 | + }, |
| 27 | + clear: () => { |
| 28 | + Object.keys(store).forEach((k) => delete store[k]); |
| 29 | + }, |
| 30 | +}; |
| 31 | +Object.defineProperty(global, "localStorage", { value: localStorageMock }); |
| 32 | + |
| 33 | +let fetchMock: jest.Mock; |
| 34 | + |
| 35 | +beforeEach(() => { |
| 36 | + localStorageMock.clear(); |
| 37 | + fetchMock = jest.fn().mockResolvedValue({ |
| 38 | + ok: true, |
| 39 | + status: 200, |
| 40 | + text: async () => "ok", |
| 41 | + headers: { forEach: () => {} }, |
| 42 | + }); |
| 43 | + global.fetch = fetchMock; |
| 44 | +}); |
| 45 | + |
| 46 | +describe("parseScopeFromKey", () => { |
| 47 | + it("returns read for sk_read_ keys", () => { |
| 48 | + expect(parseScopeFromKey("sk_read_abc-123")).toBe("read"); |
| 49 | + }); |
| 50 | + |
| 51 | + it("returns write for sk_write_ keys", () => { |
| 52 | + expect(parseScopeFromKey("sk_write_abc-123")).toBe("write"); |
| 53 | + }); |
| 54 | + |
| 55 | + it("returns write for legacy sk_<uuid> keys", () => { |
| 56 | + expect(parseScopeFromKey("sk_550e8400-e29b-41d4-a716-446655440000")).toBe("write"); |
| 57 | + }); |
| 58 | + |
| 59 | + it("returns null for invalid keys", () => { |
| 60 | + expect(parseScopeFromKey("invalid")).toBeNull(); |
| 61 | + }); |
| 62 | +}); |
| 63 | + |
| 64 | +describe("checkWriteScope", () => { |
| 65 | + it("rejects read-only keys with 403", () => { |
| 66 | + const result = checkWriteScope(generateSignedApiKey("read").key, verifySignedApiKey); |
| 67 | + expect(result).toEqual({ |
| 68 | + ok: false, |
| 69 | + status: 403, |
| 70 | + error: "This endpoint requires write scope. Your API key is read-only.", |
| 71 | + }); |
| 72 | + }); |
| 73 | + |
| 74 | + it("allows write-scoped keys", () => { |
| 75 | + const result = checkWriteScope(generateSignedApiKey("write").key, verifySignedApiKey); |
| 76 | + expect(result).toEqual({ ok: true, scope: "write" }); |
| 77 | + }); |
| 78 | + |
| 79 | + it("rejects forged write-prefixed keys", () => { |
| 80 | + const result = checkWriteScope("sk_write_anything", verifySignedApiKey); |
| 81 | + expect(result).toEqual({ ok: false, status: 401, error: "Invalid API key." }); |
| 82 | + }); |
| 83 | + |
| 84 | + it("returns 401 when token is missing", () => { |
| 85 | + const result = checkWriteScope(null); |
| 86 | + expect(result.ok).toBe(false); |
| 87 | + if (!result.ok) expect(result.status).toBe(401); |
| 88 | + }); |
| 89 | +}); |
| 90 | + |
| 91 | +describe("loadKeys migration", () => { |
| 92 | + it("defaults legacy keys without scope to write", () => { |
| 93 | + localStorageMock.setItem( |
| 94 | + STORAGE_KEY, |
| 95 | + JSON.stringify([ |
| 96 | + { |
| 97 | + id: "legacy-1", |
| 98 | + name: "old-service", |
| 99 | + key: "sk_550e8400-e29b-41d4-a716-446655440000", |
| 100 | + createdAt: 1_700_000_000_000, |
| 101 | + }, |
| 102 | + ]) |
| 103 | + ); |
| 104 | + |
| 105 | + const { keys, migratedLegacy } = loadKeys(); |
| 106 | + expect(migratedLegacy).toBe(true); |
| 107 | + expect(keys).toHaveLength(1); |
| 108 | + expect(keys[0]?.scope).toBe("write"); |
| 109 | + }); |
| 110 | + |
| 111 | + it("does not flag keys that already have scope", () => { |
| 112 | + localStorageMock.setItem( |
| 113 | + STORAGE_KEY, |
| 114 | + JSON.stringify([ |
| 115 | + { |
| 116 | + id: "new-1", |
| 117 | + name: "readonly", |
| 118 | + key: generateKeyValue("read"), |
| 119 | + scope: "read", |
| 120 | + createdAt: Date.now(), |
| 121 | + }, |
| 122 | + ]) |
| 123 | + ); |
| 124 | + |
| 125 | + const { keys, migratedLegacy } = loadKeys(); |
| 126 | + expect(migratedLegacy).toBe(false); |
| 127 | + expect(keys[0]?.scope).toBe("read"); |
| 128 | + }); |
| 129 | +}); |
| 130 | + |
| 131 | +describe("POST /api/test-webhook scope enforcement", () => { |
| 132 | + const url = "https://example.com/hook"; |
| 133 | + |
| 134 | + async function callWebhook(token: string | null) { |
| 135 | + const headers: Record<string, string> = { "Content-Type": "application/json" }; |
| 136 | + if (token) headers.Authorization = `Bearer ${token}`; |
| 137 | + |
| 138 | + const req = new Request("http://localhost/api/test-webhook", { |
| 139 | + method: "POST", |
| 140 | + headers, |
| 141 | + body: JSON.stringify({ url }), |
| 142 | + }); |
| 143 | + |
| 144 | + return testWebhookPost(req as unknown as import("next/server").NextRequest); |
| 145 | + } |
| 146 | + |
| 147 | + it("rejects read-only keys with 403", async () => { |
| 148 | + const res = await callWebhook(generateSignedApiKey("read").key); |
| 149 | + expect(res.status).toBe(403); |
| 150 | + const body = await res.json(); |
| 151 | + expect(body.error).toContain("write scope"); |
| 152 | + expect(fetchMock).not.toHaveBeenCalled(); |
| 153 | + }); |
| 154 | + |
| 155 | + it("allows write-scoped keys", async () => { |
| 156 | + const res = await callWebhook(generateSignedApiKey("write").key); |
| 157 | + expect(res.status).toBe(200); |
| 158 | + expect(fetchMock).toHaveBeenCalled(); |
| 159 | + }); |
| 160 | + |
| 161 | + it("rejects forged write keys", async () => { |
| 162 | + const res = await callWebhook("sk_write_anything"); |
| 163 | + expect(res.status).toBe(401); |
| 164 | + const body = await res.json(); |
| 165 | + expect(body.error).toBe("Invalid API key."); |
| 166 | + expect(fetchMock).not.toHaveBeenCalled(); |
| 167 | + }); |
| 168 | +}); |
0 commit comments