|
| 1 | +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; |
| 2 | +import type { AddressInfo } from "node:net"; |
| 3 | +import { apiClientManager } from "@trigger.dev/core/v3"; |
| 4 | +import { validateJWT } from "@trigger.dev/core/v3/jwt"; |
| 5 | +import { afterEach, beforeEach, describe, expect, it } from "vitest"; |
| 6 | +import { auth } from "./auth.js"; |
| 7 | + |
| 8 | +type ReceivedRequest = { |
| 9 | + method: string; |
| 10 | + url: string; |
| 11 | + authorization?: string; |
| 12 | + body: unknown; |
| 13 | +}; |
| 14 | + |
| 15 | +describe("public token API key routing", () => { |
| 16 | + let server: Server; |
| 17 | + let baseUrl: string; |
| 18 | + let requests: ReceivedRequest[]; |
| 19 | + let publicTokenStatus: number; |
| 20 | + |
| 21 | + beforeEach(async () => { |
| 22 | + requests = []; |
| 23 | + publicTokenStatus = 200; |
| 24 | + server = createServer((request, response) => { |
| 25 | + void handleRequest(request, response, requests, () => publicTokenStatus); |
| 26 | + }); |
| 27 | + await new Promise<void>((resolve) => { |
| 28 | + server.listen(0, "127.0.0.1", () => { |
| 29 | + const address = server.address() as AddressInfo; |
| 30 | + baseUrl = `http://127.0.0.1:${address.port}`; |
| 31 | + resolve(); |
| 32 | + }); |
| 33 | + }); |
| 34 | + }); |
| 35 | + |
| 36 | + afterEach(async () => { |
| 37 | + await new Promise<void>((resolve) => server.close(() => resolve())); |
| 38 | + }); |
| 39 | + |
| 40 | + it("uses server minting for additional keys", async () => { |
| 41 | + const key = "tr_prod_ak_0123456789abcdefghijklmn"; |
| 42 | + const token = await apiClientManager.runWithConfig({ baseURL: baseUrl, accessToken: key }, () => |
| 43 | + auth.createPublicToken({ |
| 44 | + scopes: { read: { runs: ["run_123"] } }, |
| 45 | + expirationTime: new Date("2030-01-01T00:00:00.000Z"), |
| 46 | + realtime: { skipColumns: ["payload"] }, |
| 47 | + }) |
| 48 | + ); |
| 49 | + |
| 50 | + expect(token).toBe("server-minted-token"); |
| 51 | + expect(requests).toEqual([ |
| 52 | + { |
| 53 | + method: "POST", |
| 54 | + url: "/api/v1/auth/public-tokens", |
| 55 | + authorization: `Bearer ${key}`, |
| 56 | + body: { |
| 57 | + scopes: ["read:runs:run_123"], |
| 58 | + expirationTime: 1893456000, |
| 59 | + realtime: { skipColumns: ["payload"] }, |
| 60 | + }, |
| 61 | + }, |
| 62 | + ]); |
| 63 | + }); |
| 64 | + |
| 65 | + it("server-mints trigger tokens with one-time-use semantics", async () => { |
| 66 | + const key = "tr_dev_ak_0123456789abcdefghijklmn"; |
| 67 | + await apiClientManager.runWithConfig({ baseURL: baseUrl, accessToken: key }, () => |
| 68 | + auth.createTriggerPublicToken(["task-one", "task-two"], { multipleUse: true }) |
| 69 | + ); |
| 70 | + |
| 71 | + expect(requests[0]?.body).toEqual({ |
| 72 | + scopes: ["trigger:tasks:task-one", "trigger:tasks:task-two"], |
| 73 | + oneTimeUse: false, |
| 74 | + }); |
| 75 | + }); |
| 76 | + |
| 77 | + it("server-mints batch trigger tokens for additional keys", async () => { |
| 78 | + const key = "tr_stg_ak_0123456789abcdefghijklmn"; |
| 79 | + await apiClientManager.runWithConfig({ baseURL: baseUrl, accessToken: key }, () => |
| 80 | + auth.createBatchTriggerPublicToken("batch-task", { |
| 81 | + expirationTime: "2h", |
| 82 | + multipleUse: false, |
| 83 | + realtime: { skipColumns: ["payload"] }, |
| 84 | + }) |
| 85 | + ); |
| 86 | + |
| 87 | + expect(requests).toEqual([ |
| 88 | + { |
| 89 | + method: "POST", |
| 90 | + url: "/api/v1/auth/public-tokens", |
| 91 | + authorization: `Bearer ${key}`, |
| 92 | + body: { |
| 93 | + scopes: ["batchTrigger:tasks:batch-task"], |
| 94 | + expirationTime: "2h", |
| 95 | + oneTimeUse: true, |
| 96 | + realtime: { skipColumns: ["payload"] }, |
| 97 | + }, |
| 98 | + }, |
| 99 | + ]); |
| 100 | + }); |
| 101 | + |
| 102 | + it("keeps root key self-minting unchanged", async () => { |
| 103 | + const key = "tr_prod_0123456789abcdefghijklmn"; |
| 104 | + const token = await apiClientManager.runWithConfig({ baseURL: baseUrl, accessToken: key }, () => |
| 105 | + auth.createPublicToken({ scopes: { read: { runs: true } } }) |
| 106 | + ); |
| 107 | + |
| 108 | + expect(requests.map((request) => request.url)).toEqual(["/api/v1/auth/jwt/claims"]); |
| 109 | + const validation = await validateJWT(token, key); |
| 110 | + expect(validation.ok).toBe(true); |
| 111 | + if (!validation.ok) return; |
| 112 | + expect(validation.payload).toMatchObject({ |
| 113 | + sub: "env_test", |
| 114 | + pub: true, |
| 115 | + scopes: ["read:runs"], |
| 116 | + }); |
| 117 | + }); |
| 118 | + |
| 119 | + it.each([ |
| 120 | + ["no options at all", undefined], |
| 121 | + ["an empty scopes object", {}], |
| 122 | + ["a scope group with nothing selected", { read: {} }], |
| 123 | + ])("keeps root-key behavior unchanged for %s", async (_label, scopes) => { |
| 124 | + const key = "tr_prod_0123456789abcdefghijklmn"; |
| 125 | + const token = await apiClientManager.runWithConfig({ baseURL: baseUrl, accessToken: key }, () => |
| 126 | + auth.createPublicToken(scopes === undefined ? undefined : { scopes }) |
| 127 | + ); |
| 128 | + |
| 129 | + expect(requests.map((request) => request.url)).toEqual(["/api/v1/auth/jwt/claims"]); |
| 130 | + const validation = await validateJWT(token, key); |
| 131 | + expect(validation.ok).toBe(true); |
| 132 | + }); |
| 133 | + |
| 134 | + it.each([ |
| 135 | + ["no options at all", undefined], |
| 136 | + ["an empty scopes object", {}], |
| 137 | + ["a scope group with nothing selected", { read: {} }], |
| 138 | + ])("rejects %s clearly for additional keys", async (_label, scopes) => { |
| 139 | + const key = "tr_prod_ak_0123456789abcdefghijklmn"; |
| 140 | + const promise = apiClientManager.runWithConfig({ baseURL: baseUrl, accessToken: key }, () => |
| 141 | + auth.createPublicToken(scopes === undefined ? undefined : { scopes }) |
| 142 | + ); |
| 143 | + |
| 144 | + await expect(promise).rejects.toThrow( |
| 145 | + "requires at least one scope when using an additional API key" |
| 146 | + ); |
| 147 | + expect(requests).toEqual([]); |
| 148 | + }); |
| 149 | + |
| 150 | + it("explains how to recover when the server lacks the mint endpoint", async () => { |
| 151 | + publicTokenStatus = 404; |
| 152 | + const promise = apiClientManager.runWithConfig( |
| 153 | + { |
| 154 | + baseURL: baseUrl, |
| 155 | + accessToken: "tr_prod_ak_0123456789abcdefghijklmn", |
| 156 | + }, |
| 157 | + () => auth.createPublicToken({ scopes: { read: { runs: true } } }) |
| 158 | + ); |
| 159 | + |
| 160 | + await expect(promise).rejects.toThrow("Upgrade the server or use the root API key"); |
| 161 | + }); |
| 162 | +}); |
| 163 | + |
| 164 | +async function handleRequest( |
| 165 | + request: IncomingMessage, |
| 166 | + response: ServerResponse, |
| 167 | + requests: ReceivedRequest[], |
| 168 | + publicTokenStatus: () => number |
| 169 | +) { |
| 170 | + const chunks: Buffer[] = []; |
| 171 | + for await (const chunk of request) { |
| 172 | + chunks.push(Buffer.from(chunk)); |
| 173 | + } |
| 174 | + const rawBody = Buffer.concat(chunks).toString(); |
| 175 | + requests.push({ |
| 176 | + method: request.method ?? "", |
| 177 | + url: request.url ?? "", |
| 178 | + authorization: request.headers.authorization, |
| 179 | + body: rawBody ? JSON.parse(rawBody) : undefined, |
| 180 | + }); |
| 181 | + |
| 182 | + if (request.url === "/api/v1/auth/jwt/claims") { |
| 183 | + return json(response, { sub: "env_test", pub: true }); |
| 184 | + } |
| 185 | + if (request.url === "/api/v1/auth/public-tokens") { |
| 186 | + const status = publicTokenStatus(); |
| 187 | + return json( |
| 188 | + response, |
| 189 | + status === 200 ? { token: "server-minted-token" } : { error: "Not found" }, |
| 190 | + status |
| 191 | + ); |
| 192 | + } |
| 193 | + |
| 194 | + return json(response, { error: "Not found" }, 404); |
| 195 | +} |
| 196 | + |
| 197 | +function json(response: ServerResponse, body: unknown, status = 200) { |
| 198 | + response.writeHead(status, { "content-type": "application/json" }); |
| 199 | + response.end(JSON.stringify(body)); |
| 200 | +} |
0 commit comments