Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(rbac): let cloud admins view org & project settings pages (#14072)

Steffen Schmitz7bcb5fba5b3d
diff --git a/web/src/__tests__/server/admin-org-context-trpc.servertest.ts b/web/src/__tests__/server/admin-org-context-trpc.servertest.ts
new file mode 100644
index 0000000000..2a7a0bb50a
--- /dev/null
+++ b/web/src/__tests__/server/admin-org-context-trpc.servertest.ts
@@ -0,0 +1,134 @@
+import type { Session } from "next-auth";
+import { prisma } from "@langfuse/shared/src/db";
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+import { randomUUID } from "crypto";
+
+const orgId = `org-${randomUUID()}`;
+const projectId = `project-${randomUUID()}`;
+const siblingProjectId = `project-${randomUUID()}`;
+
+const createSession = (opts: { admin: boolean; member: boolean }): Session => ({
+ expires: "1",
+ user: {
+ id: "user-admin-org-context-test",
+ canCreateOrganizations: true,
+ name: "Test User",
+ organizations: opts.member
+ ? [
+ {
+ id: orgId,
+ name: "Admin Org Context Test Org",
+ role: "MEMBER",
+ plan: "cloud:hobby",
+ cloudConfig: undefined,
+ projects: [
+ {
+ id: projectId,
+ role: "VIEWER",
+ retentionDays: 30,
+ deletedAt: null,
+ name: "Admin Org Context Test Project",
+ },
+ ],
+ },
+ ]
+ : [],
+ featureFlags: {
+ excludeClickhouseRead: false,
+ templateFlag: true,
+ },
+ admin: opts.admin,
+ },
+ environment: {} as any,
+});
+
+const createCaller = (opts: { admin: boolean; member: boolean }) => {
+ const ctx = createInnerTRPCContext({ session: createSession(opts) });
+ return appRouter.createCaller({ ...ctx, prisma });
+};
+
+beforeAll(async () => {
+ await prisma.organization.create({
+ data: {
+ id: orgId,
+ name: "Admin Org Context Test Org",
+ projects: {
+ create: [
+ { id: projectId, name: "Admin Org Context Test Project" },
+ { id: siblingProjectId, name: "Admin Org Context Sibling Project" },
+ ],
+ },
+ },
+ });
+});
+
+afterAll(async () => {
+ await prisma.project.deleteMany({ where: { orgId } });
+ await prisma.organization.delete({ where: { id: orgId } });
+});
+
+describe("organizations.byId", () => {
+ it("returns the session-shaped org for an admin who is not a member", async () => {
+ const caller = createCaller({ admin: true, member: false });
+ const org = await caller.organizations.byId({ orgId });
+ expect(org.id).toBe(orgId);
+ expect(org.role).toBe("OWNER");
+ expect(org.projects.map((p) => p.id).sort()).toEqual(
+ [projectId, siblingProjectId].sort(),
+ );
+ });
+
+ it("rejects non-admin org members", async () => {
+ const caller = createCaller({ admin: false, member: true });
+ await expect(caller.organizations.byId({ orgId })).rejects.toMatchObject({
+ code: "FORBIDDEN",
+ });
+ });
+
+ it("rejects non-admin non-members", async () => {
+ const caller = createCaller({ admin: false, member: false });
+ await expect(caller.organizations.byId({ orgId })).rejects.toMatchObject({
+ code: "UNAUTHORIZED",
+ });
+ });
+
+ it("returns NOT_FOUND for an admin querying an unknown org", async () => {
+ const caller = createCaller({ admin: true, member: false });
+ await expect(
+ caller.organizations.byId({ orgId: randomUUID() }),
+ ).rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+});
+
+describe("projects.byId", () => {
+ it("returns the project and its org for an admin who is not a member", async () => {
+ const caller = createCaller({ admin: true, member: false });
+ const { project, organization } = await caller.projects.byId({
+ projectId,
+ });
+ expect(project.id).toBe(projectId);
+ expect(organization.id).toBe(orgId);
+ });
+
+ it("rejects non-admin project members (must not expose sibling projects)", async () => {
+ const caller = createCaller({ admin: false, member: true });
+ await expect(caller.projects.byId({ projectId })).rejects.toMatchObject({
+ code: "FORBIDDEN",
+ });
+ });
+
+ it("rejects non-admin non-members", async () => {
+ const caller = createCaller({ admin: false, member: false });
+ await expect(caller.projects.byId({ projectId })).rejects.toMatchObject({
+ code: "UNAUTHORIZED",
+ });
+ });
+
+ it("returns NOT_FOUND for an admin querying an unknown project", async () => {
+ const caller = createCaller({ admin: true, member: false });
+ await expect(
+ caller.projects.byId({ projectId: randomUUID() }),
+ ).rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+});
diff --git a/web/src/features/organizations/components/AIFeatureSwitch.tsx b/web/src/features/organizations/components/AIFeatureSwitch.tsx
index 90d161268d..81b62bfcfe 100644
--- a/web/src/features/organizations/components/AIFeatureSwitch.tsx
+++ b/web/src/features/organizations/components/AIFeatureSwitch.tsx
@@ -23,6 +23,7 @@ import { useSession } from "next-auth/react";
export default function AIFeatureSwitch() {
const { update: updateSession } = useSession();
+ const utils = api.useUtils();
const { isLangfuseCloud } = useLangfuseCloudRegion();
const capture = usePostHogClientCapture();
const organization = useQueryOrganization();
@@ -43,6 +44,8 @@ export default function AIFeatureSwitch() {
const updateAIFeatures = api.organizations.update.useMutation({
onSuccess: async () => {
await updateSession();
+ // Admins resolve org context from this query, not the session
+ utils.organizations.byId.invalidate();
setConfirmOpen(false);
},
onError: () => {
@@ -53,6 +56,8 @@ export default function AIFeatureSwitch() {
const updateAITelemetry = api.organizations.update.useMutation({
onSuccess: async () => {
await updateSession();
+ // Admins resolve org context from this query, not the session
+ utils.organizations.byId.invalidate();
},
onError: () => {
setIsAITelemetrySwitchEnabled(aiTelemetryEnabled ?? true);
diff --git a/web/src/features/organizations/components/RenameOrganization.tsx b/web/src/features/organizations/components/RenameOrganization.tsx
index 2a987650be..30551b0c31 100644
--- a/web/src/features/organizations/components/RenameOrganization.tsx
+++ b/web/src/features/organizations/components/RenameOrganization.tsx
@@ -22,6 +22,7 @@ import { useSession } from "next-auth/react";
export default function RenameOrganization() {
const { update: updateSession } = useSession();
+ const utils = api.useUtils();
const capture = usePostHogClientCapture();
const organization = useQueryOrganization();
const hasAccess = useHasOrganizationAccess({
@@ -41,6 +42,9 @@ export default function RenameOrganization() {
const renameOrganization = api.organizations.update.useMutation({
onSuccess: () => {
updateSession();
+ // Admins resolve org/project context from these queries, not the session
+ utils.organizations.byId.invalidate();
+ utils.projects.byId.invalidate();
},
onError: (error) => form.setError("name", { message: error.message }),
});
diff --git a/web/src/features/organizations/hooks.ts b/web/src/features/organizations/hooks.ts
index ba1e800d6b..69fe22f024 100644
--- a/web/src/features/organizations/hooks.ts
+++ b/web/src/features/organizations/hooks.ts
@@ -1,4 +1,5 @@
import { env } from "@/src/env.mjs";
+import { api } from "@/src/utils/api";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
@@ -15,13 +16,33 @@ export const useQueryOrganization = () => {
export const useOrganization = (organizationId: string | null) => {
const session = useSession();
+ const isAdmin = session.data?.user?.admin === true;
// Always call hooks first, then handle conditional logic in the return
- const organization = organizationId
+ const fromSession = organizationId
? session.data?.user?.organizations.find((org) => org.id === organizationId)
: null;
- return organization ?? null;
+ // Admin fallback: Langfuse admins are not members of customer orgs, so the
+ // org is absent from their session. Resolve it from the admin-aware API
+ // instead. The query is disabled for everyone else, so non-admins keep the
+ // exact previous behavior (membership-only, no extra request).
+ const adminFallback = api.organizations.byId.useQuery(
+ { orgId: organizationId as string },
+ {
+ enabled: Boolean(organizationId) && isAdmin && !fromSession,
+ staleTime: 60_000,
+ // A stale/deleted org id is an expected miss for admins: resolve to
+ // null like the session-only lookup, without retries, error toast, or
+ // Sentry noise.
+ retry: false,
+ meta: { silentHttpCodes: [404] },
+ },
+ );
+
+ if (fromSession) return fromSession;
+ if (isAdmin) return adminFallback.data ?? null;
+ return null;
};
export const useLangfuseCloudRegion = (): {
diff --git a/web/src/features/organizations/server/adminOrgContext.ts b/web/src/features/organizations/server/adminOrgContext.ts
new file mode 100644
index 0000000000..4ac43d7864
--- /dev/null
+++ b/web/src/features/organizations/server/adminOrgContext.ts
@@ -0,0 +1,85 @@
+import { CloudConfigSchema } from "@langfuse/shared";
+import { Role, type PrismaClient } from "@langfuse/shared/src/db";
+import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server/getPlan";
+import { type Session } from "next-auth";
+import { TRPCError } from "@trpc/server";
+
+/**
+ * The organization shape attached to the next-auth session. Kept in sync with
+ * the module augmentation in web/types/next-auth.d.ts via this derivation, so
+ * the admin fallback returns exactly what useOrganization/useProject consumers
+ * already expect.
+ */
+type SessionOrganization = NonNullable<
+ Session["user"]
+>["organizations"][number];
+
+/**
+ * Builds the same organization shape that the next-auth session callback puts
+ * on `session.user.organizations[number]`, for a single organization fetched
+ * directly from the database.
+ *
+ * This exists so Langfuse admins — who are not members of customer orgs and
+ * therefore have no entry in their session — can still resolve an org/project
+ * for client hooks (useOrganization/useProject) when viewing customer settings.
+ *
+ * SECURITY: takes the caller's request context and enforces admin access
+ * itself (throws FORBIDDEN otherwise), and reads the org from the
+ * server-resolved ctx.session.orgId — never a raw client-supplied id. Admins
+ * are represented as Role.OWNER, mirroring the tRPC middleware elevation.
+ * Callers must still run it behind protectedOrganizationProcedure /
+ * protectedProjectProcedure so membership resolution and admin-access
+ * auditing happen first.
+ */
+export async function buildAdminOrgContext(ctx: {
+ prisma: PrismaClient;
+ session: {
+ user: { admin?: boolean } | null;
+ orgId: string;
+ };
+}): Promise<SessionOrganization | null> {
+ if (ctx.session.user?.admin !== true) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "Only Langfuse admins can access this endpoint",
+ });
+ }
+
+ const organization = await ctx.prisma.organization.findUnique({
+ where: { id: ctx.session.orgId },
+ include: {
+ projects: {
+ where: { deletedAt: null },
+ // Newest first, matching the session callback's project ordering
+ orderBy: { createdAt: "desc" },
+ },
+ },
+ });
+
+ if (!organization) return null;
+
+ const parsedCloudConfig = CloudConfigSchema.safeParse(
+ organization.cloudConfig,
+ );
+
+ return {
+ id: organization.id,
+ name: organization.name,
+ role: Role.OWNER,
+ metadata: (organization.metadata as Record<string, unknown>) ?? {},
+ aiFeaturesEnabled: organization.aiFeaturesEnabled,
+ aiTelemetryEnabled: organization.aiTelemetryEnabled,
+ cloudConfig: parsedCloudConfig.data,
+ projects: organization.projects.map((project) => ({
+ id: project.id,
+ name: project.name,
+ role: Role.OWNER,
+ retentionDays: project.retentionDays,
+ hasTraces: project.hasTraces,
+ deletedAt: project.deletedAt,
+ metadata: (project.metadata as Record<string, unknown>) ?? {},
+ createdAt: project.createdAt.toISOString(),
+ })),
+ plan: getOrganizationPlanServerSide(parsedCloudConfig.data),
+ };
+}
diff --git a/web/src/features/organizations/server/organizationRouter.ts b/web/src/features/organizations/server/organizationRouter.ts
index 935d3f2926..a9f41a6385 100644
--- a/web/src/features/organizations/server/organizationRouter.ts
+++ b/web/src/features/organizations/server/organizationRouter.ts
@@ -16,11 +16,27 @@ import { redis } from "@langfuse/shared/src/server";
import { createBillingServiceFromContext } from "@/src/ee/features/billing/server/stripeBillingService";
import { isCloudBillingEnabled } from "@/src/ee/features/billing/utils/isCloudBilling";
import { shouldAutoEnableV4 } from "@/src/features/events/lib/v4Rollout";
+import { buildAdminOrgContext } from "@/src/features/organizations/server/adminOrgContext";
import { getSfdcService } from "@/src/ee/features/sfdc-sync/server";
import { env } from "@/src/env.mjs";
export const organizationsRouter = createTRPCRouter({
+ // Admin-only fallback for useOrganization: returns the org in the same shape
+ // as session.user.organizations[number], since admins are not members of
+ // customer orgs and have no session entry.
+ byId: protectedOrganizationProcedure
+ .input(z.object({ orgId: z.string() }))
+ .query(async ({ ctx }) => {
+ const organization = await buildAdminOrgContext(ctx);
+ if (!organization) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Organization not found",
+ });
+ }
+ return organization;
+ }),
create: authenticatedProcedure
.input(organizationNameSchema)
.mutation(async ({ input, ctx }) => {
diff --git a/web/src/features/projects/components/ConfigureRetention.tsx b/web/src/features/projects/components/ConfigureRetention.tsx
index 652d4ea007..845fe889fd 100644
--- a/web/src/features/projects/components/ConfigureRetention.tsx
+++ b/web/src/features/projects/components/ConfigureRetention.tsx
@@ -23,6 +23,7 @@ import { useHasEntitlement } from "@/src/features/entitlements/hooks";
export default function ConfigureRetention() {
const { update: updateSession } = useSession();
+ const utils = api.useUtils();
const { project } = useQueryProject();
const capture = usePostHogClientCapture();
const hasAccess = useHasProjectAccess({
@@ -40,6 +41,9 @@ export default function ConfigureRetention() {
const setRetention = api.projects.setRetention.useMutation({
onSuccess: (_) => {
updateSession();
+ // Admins resolve org/project context from these queries, not the session
+ utils.organizations.byId.invalidate();
+ utils.projects.byId.invalidate();
},
onError: (error) => form.setError("retention", { message: error.message }),
});
diff --git a/web/src/features/projects/components/RenameProject.tsx b/web/src/features/projects/components/RenameProject.tsx
index 9dac82fa79..8c4db92496 100644
--- a/web/src/features/projects/components/RenameProject.tsx
+++ b/web/src/features/projects/components/RenameProject.tsx
@@ -22,6 +22,7 @@ import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAcces
export default function RenameProject() {
const { update: updateSession } = useSession();
+ const utils = api.useUtils();
const { project } = useQueryProject();
const capture = usePostHogClientCapture();
const hasAccess = useHasProjectAccess({
@@ -38,6 +39,9 @@ export default function RenameProject() {
const renameProject = api.projects.update.useMutation({
onSuccess: (_) => {
updateSession();
+ // Admins resolve org/project context from these queries, not the session
+ utils.organizations.byId.invalidate();
+ utils.projects.byId.invalidate();
},
onError: (error) => form.setError("name", { message: error.message }),
});
diff --git a/web/src/features/projects/hooks.ts b/web/src/features/projects/hooks.ts
index 087d4c6867..9c7ccd9b86 100644
--- a/web/src/features/projects/hooks.ts
+++ b/web/src/features/projects/hooks.ts
@@ -1,4 +1,5 @@
import { useQueryOrganization } from "@/src/features/organizations/hooks";
+import { api } from "@/src/utils/api";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
@@ -10,9 +11,10 @@ export const useQueryProject = () => {
export const useProject = (projectId: string | null) => {
const session = useSession();
+ const isAdmin = session.data?.user?.admin === true;
// Always call hooks first, then handle conditional logic in the return
- const data = projectId
+ const fromSession = projectId
? session.data?.user?.organizations
// map to {project, organization}[]
.flatMap((org) =>
@@ -22,15 +24,41 @@ export const useProject = (projectId: string | null) => {
.find(({ project }) => project.id === projectId)
: null;
- return data
- ? {
- project: data.project,
- organization: data.organization,
- }
- : {
- project: null,
- organization: null,
- };
+ // Admin fallback: Langfuse admins are not members of customer projects, so
+ // the project/org is absent from their session. Resolve it (and its parent
+ // org) from the admin-aware API instead. Disabled for everyone else, so
+ // non-admins keep the exact previous behavior.
+ const adminFallback = api.projects.byId.useQuery(
+ { projectId: projectId as string },
+ {
+ enabled: Boolean(projectId) && isAdmin && !fromSession,
+ staleTime: 60_000,
+ // A stale/deleted project id is an expected miss for admins: resolve to
+ // null like the session-only lookup, without retries, error toast, or
+ // Sentry noise.
+ retry: false,
+ meta: { silentHttpCodes: [404] },
+ },
+ );
+
+ if (fromSession) {
+ return {
+ project: fromSession.project,
+ organization: fromSession.organization,
+ };
+ }
+
+ if (isAdmin && adminFallback.data) {
+ return {
+ project: adminFallback.data.project,
+ organization: adminFallback.data.organization,
+ };
+ }
+
+ return {
+ project: null,
+ organization: null,
+ };
};
export const useQueryProjectOrOrganization = () => {
diff --git a/web/src/features/projects/server/projectsRouter.ts b/web/src/features/projects/server/projectsRouter.ts
index ccc416637d..138197c059 100644
--- a/web/src/features/projects/server/projectsRouter.ts
+++ b/web/src/features/projects/server/projectsRouter.ts
@@ -19,6 +19,7 @@ import {
} from "@langfuse/shared/src/server";
import { randomUUID } from "crypto";
import { StringNoHTMLNonEmpty } from "@langfuse/shared";
+import { buildAdminOrgContext } from "@/src/features/organizations/server/adminOrgContext";
export const projectsRouter = createTRPCRouter({
create: protectedOrganizationProcedure
@@ -304,4 +305,23 @@ export const projectsRouter = createTRPCRouter({
z.object({ projectId: z.string(), fromTimestamp: z.date().optional() }),
)
.query(async ({ input }) => getEnvironmentsForProject(input)),
+
+ // Admin-only fallback for useProject: returns the project and its org in the
+ // same shape as session.user.organizations[number], since admins are not
+ // members of customer projects and have no session entry.
+ byId: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ ctx }) => {
+ const organization = await buildAdminOrgContext(ctx);
+ const project = organization?.projects.find(
+ (p) => p.id === ctx.session.projectId,
+ );
+ if (!organization || !project) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Project not found",
+ });
+ }
+ return { project, organization };
+ }),
});