πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
fix: resolve list_sites 401 for organization-owned API keys (#1172)
Saam.exe592db3b7af25
diff --git a/server/src/api/user/getMyOrganizations.test.ts b/server/src/api/user/getMyOrganizations.test.tsindex 45a8226ad..f480754ee 100644--- a/server/src/api/user/getMyOrganizations.test.ts+++ b/server/src/api/user/getMyOrganizations.test.ts@@ -2,14 +2,18 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({getSessionFromReq: vi.fn(),- getUserIdFromRequest: vi.fn(),+ getRequestIdentity: vi.fn(),+ wasRateLimited: vi.fn(),}));-// Keep the real db (PGlite below) but stub the two auth resolvers so we can-// drive the session-vs-bearer branch directly.+// Keep the real db (PGlite below) but stub the auth resolvers so we can drive+// the session-vs-bearer-vs-org-key branch directly.+// getRequestIdentity is stubbed as a unit; auth-utils.test.ts covers its+// single-resolution guarantee.vi.mock("../../lib/auth-utils.js", () => ({getSessionFromReq: mocks.getSessionFromReq,- getUserIdFromRequest: mocks.getUserIdFromRequest,+ getRequestIdentity: mocks.getRequestIdentity,+ wasRateLimited: mocks.wasRateLimited,}));vi.mock("../../db/postgres/postgres.js", async () => {@@ -32,7 +36,7 @@ CREATE TABLE "sites" ("id" text, "site_id" serial PRIMARY KEY, "name" text, "dom`;function replyStub() {- const reply: any = { statusCode: 200 };+ const reply: any = { statusCode: 200, headers: {} };reply.status = (code: number) => {reply.statusCode = code;return reply;@@ -41,6 +45,10 @@ function replyStub() {reply.body = body;return reply;};+ reply.header = (name: string, value: unknown) => {+ reply.headers[name] = value;+ return reply;+ };return reply;}@@ -52,12 +60,14 @@ beforeEach(async () => {vi.clearAllMocks();await (sql as any).exec(`TRUNCATE "organization", "user", "member", "sites"`);await (sql as any).exec(`- INSERT INTO "organization" ("id","name","slug") VALUES ('org_1','Acme','acme');+ INSERT INTO "organization" ("id","name","slug") VALUES ('org_1','Acme','acme'),('org_2','Beta','beta');INSERT INTO "user" ("id","name","email") VALUES ('u_caller','Owner','[email protected]'),('u_peer','Peer','[email protected]');INSERT INTO "member" ("id","organizationId","userId","role") VALUES ('m_caller','org_1','u_caller','owner'),('m_peer','org_1','u_peer','member');INSERT INTO "sites" ("id","name","domain","organization_id","public") VALUES ('hex1','Acme Site','acme.com','org_1',false);+ INSERT INTO "sites" ("id","name","domain","organization_id","public") VALUES ('hex_beta1','Beta Site 1','beta1.com','org_2',false),('hex_beta2','Beta Site 2','beta2.com','org_2',false);`);- mocks.getUserIdFromRequest.mockResolvedValue("u_caller");+ mocks.getRequestIdentity.mockResolvedValue({ userId: "u_caller", organizationId: null });+ mocks.wasRateLimited.mockReturnValue(undefined);});describe("getMyOrganizations β member roster exposure", () => {@@ -86,3 +96,60 @@ describe("getMyOrganizations β member roster exposure", () => {expect(JSON.stringify(reply.body)).not.toContain("[email protected]");});});++describe("getMyOrganizations β organization-owned API keys", () => {+ beforeEach(() => {+ mocks.getSessionFromReq.mockResolvedValue(null);+ });++ it("returns only its own organization, with all its sites and no member PII", async () => {+ mocks.getRequestIdentity.mockResolvedValue({ userId: null, organizationId: "org_2" });+ const reply = replyStub();++ await getMyOrganizations({ headers: { authorization: "Bearer rb_org_key" } } as any, reply);++ expect(reply.body).toHaveLength(1);+ const [org] = reply.body;+ expect(org.id).toBe("org_2");+ expect(org.role).toBe("admin");+ expect(org.members).toEqual([]);+ expect(org.sites.map((s: any) => s.domain).sort()).toEqual(["beta1.com", "beta2.com"]);+ expect(JSON.stringify(reply.body)).not.toContain("[email protected]");+ expect(JSON.stringify(reply.body)).not.toContain("[email protected]");+ });++ it("never returns another organization's data (org A key can't see org B)", async () => {+ mocks.getRequestIdentity.mockResolvedValue({ userId: null, organizationId: "org_1" });+ const reply = replyStub();++ await getMyOrganizations({ headers: { authorization: "Bearer rb_org_key" } } as any, reply);++ expect(reply.body).toHaveLength(1);+ const [org] = reply.body;+ expect(org.id).toBe("org_1");+ expect(org.sites.map((s: any) => s.domain)).toEqual(["acme.com"]);+ // Only org_1's data is present anywhere in the payload β org_2 never leaks in.+ expect(JSON.stringify(reply.body)).not.toContain("org_2");+ expect(JSON.stringify(reply.body)).not.toContain("beta1.com");+ expect(JSON.stringify(reply.body)).not.toContain("beta2.com");+ });++ it("401s when neither a user id nor an org key resolve", async () => {+ mocks.getRequestIdentity.mockResolvedValue({ userId: null, organizationId: null });+ const reply = replyStub();++ await getMyOrganizations({ headers: {} } as any, reply);++ expect(reply.statusCode).toBe(401);+ });++ it("429s instead of 401 when the credential was only rate-limited", async () => {+ mocks.getRequestIdentity.mockResolvedValue({ userId: null, organizationId: null });+ mocks.wasRateLimited.mockReturnValue({ retryAfterSeconds: 30, scope: "org" });+ const reply = replyStub();++ await getMyOrganizations({ headers: { authorization: "Bearer rb_org_key" } } as any, reply);++ expect(reply.statusCode).toBe(429);+ });+});diff --git a/server/src/api/user/getMyOrganizations.ts b/server/src/api/user/getMyOrganizations.tsindex 5a8bf3624..0858d3d1c 100644--- a/server/src/api/user/getMyOrganizations.ts+++ b/server/src/api/user/getMyOrganizations.ts@@ -2,13 +2,15 @@ import { FastifyRequest, FastifyReply } from "fastify";import { db } from "../../db/postgres/postgres.js";import { eq } from "drizzle-orm";import { member, organization, sites, user } from "../../db/postgres/schema.js";-import { getSessionFromReq, getUserIdFromRequest, wasRateLimited } from "../../lib/auth-utils.js";+import { getRequestIdentity, getSessionFromReq, wasRateLimited } from "../../lib/auth-utils.js";import { filterSitesByMemberAccess, getOrgMembership } from "../../lib/access.js";export const getMyOrganizations = async (request: FastifyRequest, reply: FastifyReply) => {try {- const userId = await getUserIdFromRequest(request);- if (!userId) {+ // Organization-owned API keys have no user id β they resolve to their+ // single organization instead. One resolution covers both cases.+ const { userId, organizationId: apiKeyOrganizationId } = await getRequestIdentity(request);+ if (!userId && !apiKeyOrganizationId) {// This route has no auth pre-handler, so a throttled credential resolves// to no user. Reporting that as 401 would tell a caller their key is// invalid when it is merely out of budget.@@ -32,19 +34,38 @@ export const getMyOrganizations = async (request: FastifyRequest, reply: Fastifyconst session = await getSessionFromReq(request);const includeMembers = !!session?.user;- // First, get all organizations the user is a member of- const userOrganizations = await db- .select({- id: organization.id,- name: organization.name,- slug: organization.slug,- logo: organization.logo,- createdAt: organization.createdAt,- role: member.role,- })- .from(member)- .innerJoin(organization, eq(member.organizationId, organization.id))- .where(eq(member.userId, userId));+ // First, get all organizations the user is a member of β or, for an+ // org-owned key, just its own organization (it has no member row).+ let userOrganizations;+ if (userId) {+ userOrganizations = await db+ .select({+ id: organization.id,+ name: organization.name,+ slug: organization.slug,+ logo: organization.logo,+ createdAt: organization.createdAt,+ role: member.role,+ })+ .from(member)+ .innerJoin(organization, eq(member.organizationId, organization.id))+ .where(eq(member.userId, userId));+ } else {+ const orgRows = await db+ .select({+ id: organization.id,+ name: organization.name,+ slug: organization.slug,+ logo: organization.logo,+ createdAt: organization.createdAt,+ })+ .from(organization)+ // apiKeyOrganizationId is guaranteed set here: the guard above already+ // returned if both it and userId were missing.+ .where(eq(organization.id, apiKeyOrganizationId!))+ .limit(1);+ userOrganizations = orgRows.map(org => ({ ...org, role: "admin" as const }));+ }// For each organization, get all members with user details and sitesconst organizationsWithMembersAndSites = await Promise.all(@@ -88,10 +109,12 @@ export const getMyOrganizations = async (request: FastifyRequest, reply: Fastifylet organizationSites = allOrgSites;if (callerMemberRecord?.role === "member") {+ // getOrgMembership null-guards a missing userId, so a non-null+ // callerMemberRecord here means userId was set.organizationSites = await filterSitesByMemberAccess(allOrgSites,org.id,- userId,+ userId!,callerMemberRecord.id,callerMemberRecord.hasRestrictedSiteAccess);diff --git a/server/src/lib/auth-utils.test.ts b/server/src/lib/auth-utils.test.tsindex 5d50df9dc..2d3cbf16f 100644--- a/server/src/lib/auth-utils.test.ts+++ b/server/src/lib/auth-utils.test.ts@@ -51,6 +51,7 @@ import {getSitesUserHasAccessTo,getUserHasAccessToSite,getUserHasAdminAccessToSite,+ getRequestIdentity,getUserIdFromRequest,invalidateSitesAccessCache,} from "./auth-utils.js";@@ -602,6 +603,13 @@ describe("checkApiKey β organization-owned keys", () => {expect(await getUserIdFromRequest(request())).toBeNull();});+ it("resolves to its organization id with a single key verification", async () => {+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(orgKeyVerification("org_a"));++ expect(await getRequestIdentity(request())).toEqual({ userId: null, organizationId: "org_a" });+ expect(auth.api.verifyApiKey).toHaveBeenCalledTimes(1);+ });+it("keys from the default configuration still resolve through user membership", async () => {await db.delete(member).where(eq(member.organizationId, "org_a"));await dbdiff --git a/server/src/lib/auth-utils.ts b/server/src/lib/auth-utils.tsindex d44b19893..48e38957f 100644--- a/server/src/lib/auth-utils.ts+++ b/server/src/lib/auth-utils.ts@@ -420,15 +420,31 @@ export async function checkApiKey(return { valid: false, role: null, statements: null };}-export async function getUserIdFromRequest(req: FastifyRequest): Promise<string | null> {+export interface RequestIdentity {+ userId: string | null;+ // Set for organization-owned API keys, which authenticate as the org itself+ // and carry no user id.+ organizationId: string | null;+}++const ANONYMOUS_IDENTITY: RequestIdentity = { userId: null, organizationId: null };++/**+ * Resolve who a request is acting as: a person (dashboard session, personal+ * API key, OAuth token) or an organization (org-owned API key). Resolves the+ * bearer credential exactly once β the MCP proxy's bearer handoff is single+ * use, so a second resolution would fall through to a fresh key verification+ * and charge the caller again.+ */+export async function getRequestIdentity(req: FastifyRequest): Promise<RequestIdentity> {if (req.user?.id) {- return req.user.id;+ return { userId: req.user.id, organizationId: null };}// First, check for session-based authconst session = await getSessionFromReq(req);if (session?.user?.id) {- return session.user.id;+ return { userId: session.user.id, organizationId: null };}// Fall back to bearer auth (API key or OAuth token).@@ -437,12 +453,16 @@ export async function getUserIdFromRequest(req: FastifyRequest): Promise<stringconst identity =consumeBearerHandoff(req.headers[INTERNAL_BEARER_HANDOFF_HEADER], apiKey) ??(await resolveBearerIdentity(apiKey, bearerResolverDeps));- if (identity.status === "valid" && identity.userId) {- return identity.userId;+ if (identity.status === "valid") {+ return { userId: identity.userId ?? null, organizationId: identity.organizationId ?? null };}}- return null;+ return ANONYMOUS_IDENTITY;+}++export async function getUserIdFromRequest(req: FastifyRequest): Promise<string | null> {+ return (await getRequestIdentity(req)).userId;}// for routes that are potentially public