🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(public-api): refuse project keys whose path names another project (#18957)
Mark Salpeter5a421dbdac45
diff --git a/web/src/__tests__/server/shadowAuth.servertest.ts b/web/src/__tests__/server/shadowAuth.servertest.tsindex 7b93a0ee1f..6ce0723cc4 100644--- a/web/src/__tests__/server/shadowAuth.servertest.ts+++ b/web/src/__tests__/server/shadowAuth.servertest.ts@@ -57,8 +57,9 @@ let originalCloudRegion: string | undefined;const reqWith = (headers: Record<string, string | undefined>,query: Record<string, string> = {},+ url?: string,): NextApiRequest =>- ({ headers, method: "GET", query }) as unknown as NextApiRequest;+ ({ headers, method: "GET", query, url }) as unknown as NextApiRequest;const setMode = (mode: string) => {(env as any).API_AUTH_MIGRATION = mode;@@ -107,7 +108,11 @@ const projectNestedUnderModes = async (action: ProjectAction = "apiKeys:read",) => {const params: ShadowAuthParams = {- req: reqWith({ authorization }, { projectId: target }),+ req: reqWith(+ { authorization },+ { projectId: target },+ `/api/public/projects/${target}/apiKeys`,+ ),action,allowedAccessLevels: ["organization"],};@@ -519,6 +524,59 @@ describe("shadowAuth maps principals to legacy-identical scopes", () => {expect(enforce).toMatchObject({ success: false, error: { httpCode: 403 } });});+ it("a project ADMIN key on a project-nested route authorizes only its own project in enforce", async () => {+ const { apiKey, authorization } = await createUnassignedApiKey("PROJECT");+ await prisma.roleAssignment.create({+ data: {+ orgId,+ projectId,+ apiKeyId: apiKey.id,+ ownerId: `project/${projectId}`,+ principalId: `apiKey/${apiKey.id}`,+ roleId: "system/ADMIN",+ systemRole: "ADMIN",+ },+ });+ const sibling = await prisma.project.create({+ data: { orgId, name: `sibling-${randomUUID()}` },+ });++ const own = await projectNestedUnderModes(+ authorization,+ projectId,+ "apiKeys:CUD",+ );+ expect(scopeOf(own.enforce).projectId).toBe(projectId);++ const foreign = await projectNestedUnderModes(+ authorization,+ sibling.id,+ "apiKeys:CUD",+ );+ expect(foreign.legacy).toMatchObject({+ success: false,+ error: { httpCode: 403 },+ });+ expect(foreign.enforce).toMatchObject({+ success: false,+ error: { httpCode: 403 },+ });+ });++ it("a project key ignores a query-string projectId naming another project", async () => {+ const { legacy, enforce } = await resultsUnderModes({+ req: reqWith(+ { authorization: projectAuth },+ { projectId: "llm-app" },+ "/api/public/ingestion?projectId=llm-app",+ ),+ action: "traces:create",+ allowedAccessLevels: ["project"],+ });+ expect(scopeOf(legacy).projectId).toBe(projectId);+ expect(scopeOf(enforce).projectId).toBe(projectId);+ });+it("an organization key is granted project:read on a project it owns", async () => {const context = await contextFor(orgAuth);expect(ownedProjectIds(context)).toContain(projectId);diff --git a/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts b/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.tsindex 1bbe9d5dc9..8b18f2e040 100644--- a/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts+++ b/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts@@ -84,8 +84,8 @@ const adminKey = (): AuthorizationContext => ({policies: [],});-const req = (query = {}, headers = {}) =>- ({ query, headers }) as unknown as NextApiRequest;+const req = (query = {}, headers = {}, url?: string) =>+ ({ query, headers, url }) as unknown as NextApiRequest;describe("getOrgId", () => {it("resolves the bound org without a header", () => {@@ -162,17 +162,40 @@ describe.each(["x-langfuse-project-id", "langfuse-project-id"])(getProjectId(projectKey(), req({}, { [projectIdHeader]: "prj_2" })),).toEqual({ success: true, projectId: PRJ });});- it("ignores a URL disagreeing with the bound project", () => {- expect(getProjectId(projectKey(), req({ projectId: "prj_2" }))).toEqual({- success: true,- projectId: PRJ,- });+ it("403s a bound key whose path names another project", () => {+ expect(+ getProjectId(+ projectKey(),+ req({ projectId: "prj_2" }, {}, "/api/public/projects/prj_2/apiKeys"),+ ),+ ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });+ });+ it("403s a bound key whose percent-encoded path names another project", () => {+ expect(+ getProjectId(+ projectKey(),+ req(+ { projectId: "prj_2" },+ {},+ "/api/public/projects/%70rj_2/apiKeys",+ ),+ ),+ ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });});- it("ignores conflicting URL and header projects when bound", () => {+ it("403s a bound key whose URL project disagrees when the path is unknown", () => {+ expect(+ getProjectId(projectKey(), req({ projectId: "prj_2" })),+ ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });+ });+ it("ignores a query-string project disagreeing with the bound project", () => {expect(getProjectId(projectKey(),- req({ projectId: "prj_2" }, { [projectIdHeader]: "prj_3" }),+ req(+ { projectId: "llm-app" },+ { [projectIdHeader]: "prj_3" },+ "/api/public/ingestion?projectId=llm-app",+ ),),).toEqual({ success: true, projectId: PRJ });});@@ -227,6 +250,7 @@ describe("enforceAuth span metadata", () => {"x-langfuse-project-id": "ignored-header-project",authorization: "Bearer untrusted-submitted-credential",},+ "/api/public/traces?projectId=ignored-url-project",),action: "traces:read",});diff --git a/web/src/features/public-api/server/enforceAuth.ts b/web/src/features/public-api/server/enforceAuth.tsindex 37bdb4b553..13ac761ef5 100644--- a/web/src/features/public-api/server/enforceAuth.ts+++ b/web/src/features/public-api/server/enforceAuth.ts@@ -195,15 +195,18 @@ function getOrgId(return { success: true, orgId };}-/** getProjectId prioritizes the bound project, then the query parameter, then the header. */+/** getProjectId prioritizes the bound project, then the query parameter, then the header, refusing a bound key whose path names another project. */function getProjectId(context: AuthorizationContext,req: NextApiRequest,): ResolvedProject | ErrorResult<ForbiddenError> {+ const boundProjectId = getBoundProjectId(context);+ if (!equal([boundProjectId, getPathProjectId(req)])) {+ return forbiddenError();+ }+const projectId =- getBoundProjectId(context) ??- getUrlProjectId(req) ??- getHeaderProjectId(req);+ boundProjectId ?? getUrlProjectId(req) ?? getHeaderProjectId(req);if (!projectId) {return forbiddenError();}@@ -259,6 +262,24 @@ function getUrlProjectId(req: NextApiRequest): string | undefined {: undefined;}+/** getPathProjectId returns the URL projectId only when it is a path segment, ignoring a query-string projectId. */+function getPathProjectId(req: NextApiRequest): string | undefined {+ const projectId = getUrlProjectId(req);+ if (!projectId || isQueryOnly(req.url, projectId)) return undefined;+ return projectId;+}++/** isQueryOnly reports whether a value is absent from the url's path, failing closed when the path is missing or undecodable. */+function isQueryOnly(url: string | undefined, value: string): boolean {+ if (!url) return false;+ const path = url.split("?")[0] ?? "";+ try {+ return !path.split("/").map(decodeURIComponent).includes(value);+ } catch {+ return false;+ }+}+/** getHeaderValue prefers the X-prefixed alias and normalizes repeated headers to their first value. */function getHeaderValue(req: NextApiRequest,