From fd7d3d4641213abdae767aec3fc580c996683d1e Mon Sep 17 00:00:00 2001 From: Brendan Date: Thu, 17 Sep 2026 05:49:40 +0000 Subject: [PATCH] Collapse API authorization into one tenant round trip --- packages/app/src/flow-service.ts | 15 +++++------ packages/app/src/tenant.ts | 13 ++++++++++ packages/app/test/flow-service.test.ts | 35 +++++++++++++++++++++++--- 3 files changed, 53 insertions(+), 10 deletions(-) diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 4536441e..132514ee 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -15,13 +15,14 @@ export class ApiService { private async authorize(scope: Scope): Promise { if (!this.auth.scopes.includes(scope)) throw new ServiceError(403, "insufficient_scope", `The ${scope} scope is required.`); - const response = await this.stub().fetch(`https://tenant/members/${encodeURIComponent(this.auth.userId)}`); - if (!response.ok) throw new ServiceError(401, "invalid_token", "The resource owner is no longer a member."); - const member = await response.json() as { role?: string; session_version?: number }; - if (member.role !== "owner" || member.session_version !== this.auth.sessionVersion) throw new ServiceError(401, "invalid_token", "The resource owner's session has been revoked."); - if (this.auth.accessTokenId) { - const token = await this.stub().fetch(`https://tenant/access-tokens/${encodeURIComponent(this.auth.accessTokenId)}/active`); - if (!token.ok) throw new ServiceError(401, "invalid_token", "The access token has expired or been revoked."); + const response = await this.stub().fetch("https://tenant/authorize", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ userId: this.auth.userId, sessionVersion: this.auth.sessionVersion, accessTokenId: this.auth.accessTokenId }), + }); + if (!response.ok) { + const body = await response.json().catch(() => ({})) as { error?: string }; + throw new ServiceError(401, "invalid_token", body.error ?? "The request is not authorized."); } } diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 158552ae..61ef963b 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -223,6 +223,7 @@ export class TenantV2 extends DurableObject { if (request.method === "PUT" && url.pathname === "/connections/clickup") return await this.saveClickUp(await request.json()); if (request.method === "PUT" && url.pathname === "/connections/exe") return await this.saveExe(await request.json()); if (request.method === "POST" && url.pathname === "/connections/exe/test") return await this.testExe(await request.json()); + if (request.method === "POST" && url.pathname === "/authorize") return this.authorize(await request.json()); const exeModelsMatch = url.pathname.match(/^\/connections\/exe\/([^/]+)\/models$/); if (request.method === "POST" && exeModelsMatch) return await this.refreshExeModels(decodeURIComponent(exeModelsMatch[1])); if (request.method === "PUT" && url.pathname === "/connections/amp") return await this.saveAmp(await request.json()); @@ -1716,6 +1717,18 @@ export class TenantV2 extends DurableObject { return member ? json(member) : new Response("Not found", { status: 404 }); } + private authorize(input: unknown): Response { + const value = object(input); + const userId = text(value.userId); + const sessionVersion = Number(value.sessionVersion); + const accessTokenId = text(value.accessTokenId); + const member = this.one("SELECT role,session_version FROM members WHERE user_id = ?", userId) as Row | undefined; + if (!member) return Response.json({ error: "The resource owner is no longer a member." }, { status: 401 }); + if (member.role !== "owner" || Number(member.session_version) !== sessionVersion) return Response.json({ error: "The resource owner's session has been revoked." }, { status: 401 }); + if (accessTokenId && !this.one("SELECT id FROM access_tokens WHERE id=? AND revoked_at IS NULL AND expires_at>?", accessTokenId, now())) return Response.json({ error: "The access token has expired or been revoked." }, { status: 401 }); + return json({ authorized: true }); + } + private revokeMember(userId: string): Response { this.ctx.storage.sql.exec("UPDATE members SET session_version = session_version + 1 WHERE user_id = ?", userId); return json({ ok: true }); diff --git a/packages/app/test/flow-service.test.ts b/packages/app/test/flow-service.test.ts index d3298173..4355d3a8 100644 --- a/packages/app/test/flow-service.test.ts +++ b/packages/app/test/flow-service.test.ts @@ -12,15 +12,21 @@ const auth: OAuthProps = { tenantId: "tenant-a", userId: "owner-a", sessionVersi describe("ApiService", () => { it("invalidates tokens when the owner session version changes", async () => { - const service = new ApiService(environment(() => Response.json({ role: "owner", session_version: 5 })), auth); + const requests: Request[] = []; + const service = new ApiService(environment(request => { + requests.push(request); + return Response.json({ error: "The resource owner's session has been revoked." }, { status: 401 }); + }), auth); await expect(service.listJobs()).rejects.toMatchObject({ status: 401, code: "invalid_token" }); + const authorizationRequests = requests.filter(request => new URL(request.url).pathname === "/authorize"); + expect(authorizationRequests).toHaveLength(1); }); it("uses flow scopes for job management and run scopes for invocation", async () => { const requests: string[] = []; const service = new ApiService(environment(request => { const path = new URL(request.url).pathname; - if (path === "/members/owner-a") return Response.json({ role: "owner", session_version: 4 }); + if (path === "/authorize") return Response.json({ authorized: true }); requests.push(`${request.method} ${path}`); return Response.json({ ok: true }); }), { ...auth, scopes: ["flows:read", "flows:write", "runs:write"] }); @@ -33,7 +39,7 @@ describe("ApiService", () => { const installations = [{ installationId: 123, accountLogin: "generation", accountType: "Organization", state: "active", updatedAt: "2026-09-17T00:00:00.000Z" }]; const service = new ApiService(environment(request => { const path = new URL(request.url).pathname; - if (path === "/members/owner-a") return Response.json({ role: "owner", session_version: 4 }); + if (path === "/authorize") return Response.json({ authorized: true }); if (path === "/github/installations") return Response.json(installations); return new Response("Not found", { status: 404 }); }), auth); @@ -43,6 +49,29 @@ describe("ApiService", () => { }); }); +describe("authorization round trip", () => { + it.each([ + ["valid", Response.json({ authorized: true }), undefined], + ["revoked token", Response.json({ error: "The access token has expired or been revoked." }, { status: 401 }), "The access token has expired or been revoked."], + ["removed member", Response.json({ error: "The resource owner is no longer a member." }, { status: 401 }), "The resource owner is no longer a member."], + ["session mismatch", Response.json({ error: "The resource owner's session has been revoked." }, { status: 401 }), "The resource owner's session has been revoked."], + ])("handles %s authorization in one request", async (_name, response, message) => { + const requests: Request[] = []; + const service = new ApiService(environment(request => { + requests.push(request); + return new URL(request.url).pathname === "/authorize" ? response : Response.json([]); + }), auth); + if (message) await expect(service.listJobs()).rejects.toMatchObject({ status: 401, message }); + else { + const result = await service.listJobs(); + expect(result).toEqual([]); + } + const authorizationRequests = requests.filter(request => new URL(request.url).pathname === "/authorize"); + expect(authorizationRequests).toHaveLength(1); + expect(new URL(authorizationRequests[0].url).pathname).toBe("/authorize"); + }); +}); + describe("shared API schemas", () => { it("bounds pagination and run states", () => { expect(listRunsSchema.parse({ limit: "100", state: "running", contextQuery: "literal.*text" })).toMatchObject({ limit: 100, state: "running", contextQuery: "literal.*text" });