🪢 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
feat: integrate support access with C1 (#19278)
jordibosch207289e94be504
diff --git a/packages/shared/prisma/migrations/20261023120000_add_user_support_access/migration.sql b/packages/shared/prisma/migrations/20261023120000_add_user_support_access/migration.sqlnew file mode 100644index 0000000000..12e09db78f--- /dev/null+++ b/packages/shared/prisma/migrations/20261023120000_add_user_support_access/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "users" ADD COLUMN "support_access" JSONB;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex fa5f514b9a..819956a4ad 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -59,6 +59,7 @@ model User {image String?admin Boolean @default(false)v4BetaEnabled Boolean @default(false) @map("v4_beta_enabled")+ supportAccess Json? @map("support_access")accounts Account[]sessions Session[]organizationMemberships OrganizationMembership[]diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 164c661327..a46bcb7452 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -834,6 +834,9 @@ importers:ioredis:specifier: ^5.10.1version: 5.10.1([email protected])+ jose:+ specifier: 6.2.3+ version: 6.2.3json-schema-faker:specifier: 0.6.1version: 0.6.1diff --git a/web/package.json b/web/package.jsonindex 99b9e2205f..b143ef9dc1 100644--- a/web/package.json+++ b/web/package.json@@ -135,6 +135,7 @@"highlight.js": "^11.12.0","https-proxy-agent": "^7.0.6","ioredis": "^5.10.1",+ "jose": "6.2.3","json-schema-faker": "0.6.1","langfuse": "3.38.4","lodash": "^4.18.1",diff --git a/web/src/__tests__/server/support-access-security.servertest.ts b/web/src/__tests__/server/support-access-security.servertest.tsnew file mode 100644index 0000000000..7142af7672--- /dev/null+++ b/web/src/__tests__/server/support-access-security.servertest.ts@@ -0,0 +1,343 @@+import { createHash, randomUUID } from "node:crypto";+import { Readable } from "node:stream";++import {+ createLocalJWKSet,+ exportJWK,+ generateKeyPair,+ SignJWT,+ type JWTPayload,+} from "jose";+import { type NextApiRequest, type NextApiResponse } from "next";+import type { Session } from "next-auth";+import type { JWT } from "next-auth/jwt";+import { createResponse } from "node-mocks-http";+import { beforeAll, describe, expect, it, vi } from "vitest";++import { prisma } from "@langfuse/shared/src/db";+import { env } from "@/src/env.mjs";+import { C1_PROVISION_EVENT } from "@/src/ee/features/support-access/server/conductorOnePayload";+import { conductorOneWebhookHandler } from "@/src/ee/features/support-access/server/conductorOneWebhook";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { getAuthOptions } from "@/src/server/auth";++// End-to-end security contracts for ConductorOne support access: only a+// correctly signed webhook can grant access, and a grant gives time-boxed,+// read-only access to exactly one organization.++const jwksHolder = vi.hoisted(() => ({+ jwks: undefined as unknown as ReturnType<typeof createLocalJWKSet>,+}));++vi.mock("@/src/env.mjs", async (importOriginal) => {+ const actual = await importOriginal<{ env: typeof env }>();+ return { ...actual, env: { ...actual.env } };+});++vi.mock(+ "@/src/ee/features/support-access/server/conductorOneAuth",+ async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ getConductorOneJwks: () => jwksHolder.jwks,+ }),+);++const issuer = "test.conductor.one";+const entitlementId = "ent-support-access";+const nextAuthUrl = "https://us.cloud.langfuse.com";+const audience = "us.cloud.langfuse.com";++let signingKey: CryptoKey;+let unknownKey: CryptoKey;++beforeAll(async () => {+ Object.assign(env, {+ LANGFUSE_CONDUCTORONE_ISSUER: issuer,+ LANGFUSE_CONDUCTORONE_ENTITLEMENT_ID: entitlementId,+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: "US",+ NEXTAUTH_URL: nextAuthUrl,+ });++ const pair = await generateKeyPair("RS256");+ signingKey = pair.privateKey;+ unknownKey = (await generateKeyPair("RS256")).privateKey;+ const jwk = { ...(await exportJWK(pair.publicKey)), kid: "k", alg: "RS256" };+ jwksHolder.jwks = createLocalJWKSet({ keys: [jwk] });+});++async function sign(+ body: Buffer,+ claims: JWTPayload = {},+ opts: { key?: CryptoKey; expiresIn?: string } = {},+) {+ const htb = createHash("sha256").update(body).digest("base64");+ const { iss = issuer, aud = audience, ...rest } = claims;+ return new SignJWT({ htb_s256: htb, ...rest })+ .setProtectedHeader({ alg: "RS256", kid: "k" })+ .setIssuer(iss)+ .setAudience(aud)+ .setIssuedAt()+ .setExpirationTime(opts.expiresIn ?? "2m")+ .sign(opts.key ?? signingKey);+}++async function callWebhook(body: Buffer, authorization?: string) {+ const req = Object.assign(Readable.from([body]), {+ method: "POST",+ headers: {+ "content-length": String(body.length),+ ...(authorization ? { authorization } : {}),+ },+ }) as unknown as NextApiRequest;+ const res = createResponse<NextApiResponse>();+ await conductorOneWebhookHandler(req, res);+ return { status: res.statusCode, body: res._getJSONData() };+}++function provisionBody(params: { email: string; orgId: string; type: object }) {+ return Buffer.from(+ JSON.stringify({+ version: "v1",+ event: C1_PROVISION_EVENT,+ payload: {+ taskView: {+ task: {+ id: `task-${randomUUID()}`,+ userId: "c1-user",+ type: params.type,+ data: { langfuse_organization_id_0: params.orgId },+ },+ },+ expanded: [+ {+ "@type": "type.googleapis.com/c1.api.user.v1.User",+ id: "c1-user",+ email: params.email,+ },+ ],+ },+ }),+ );+}++const grantType = (grantDuration = "3600s") => ({+ grant: { appEntitlementId: entitlementId, grantDuration },+});+const revokeType = { revoke: { appEntitlementId: entitlementId } };++async function createFixture() {+ const email = `support-${randomUUID()}@clickhouse.com`;+ const user = await prisma.user.create({ data: { email, name: "Support" } });+ const org = await prisma.organization.create({+ data: {+ name: `Support Access Org ${randomUUID()}`,+ projects: { create: { name: "Customer Project" } },+ },+ include: { projects: true },+ });+ return { email, user, orgId: org.id, projectId: org.projects[0].id };+}++async function readSupportAccess(userId: string) {+ const user = await prisma.user.findUniqueOrThrow({+ where: { id: userId },+ select: { supportAccess: true },+ });+ return user.supportAccess;+}++async function sessionFor(email: string): Promise<Session> {+ const sessionCallback = (await getAuthOptions()).callbacks+ ?.session as (params: { session: Session; token: JWT }) => Promise<Session>;+ return sessionCallback({+ session: { expires: "1", user: null } as unknown as Session,+ token: { email, loginAt: Date.now() },+ });+}++async function callerFor(email: string) {+ const session = await sessionFor(email);+ const ctx = createInnerTRPCContext({ session, headers: {} });+ return { session, caller: appRouter.createCaller({ ...ctx, prisma }) };+}++describe("ConductorOne webhook authentication", () => {+ it.each([+ ["no authorization header", async () => undefined],+ ["a non-bearer scheme", async () => "Basic abc"],+ [+ "a token for another region's host",+ async (body: Buffer) =>+ `Bearer ${await sign(body, { aud: "eu.cloud.langfuse.com" })}`,+ ],+ [+ "a token from another issuer",+ async (body: Buffer) =>+ `Bearer ${await sign(body, { iss: "evil.conductor.one" })}`,+ ],+ [+ "a token signed by an unknown key",+ async (body: Buffer) =>+ `Bearer ${await sign(body, {}, { key: unknownKey })}`,+ ],+ [+ "an expired token",+ async (body: Buffer) =>+ `Bearer ${await sign(body, {}, { expiresIn: "-1m" })}`,+ ],+ [+ "a token signed for a different body",+ async () => `Bearer ${await sign(Buffer.from('{"event":"other"}'))}`,+ ],+ ])("rejects %s with 401 and grants nothing", async (_, authFor) => {+ const { email, user, orgId } = await createFixture();+ const body = provisionBody({ email, orgId, type: grantType() });++ const response = await callWebhook(body, await authFor(body));++ expect(response.status).toBe(401);+ expect(await readSupportAccess(user.id)).toBeNull();+ });++ it("accepts a correctly signed grant", async () => {+ const { email, user, orgId } = await createFixture();+ const body = provisionBody({ email, orgId, type: grantType() });++ const response = await callWebhook(body, `Bearer ${await sign(body)}`);++ expect(response).toMatchObject({+ status: 200,+ body: { version: "v1", complete: {} },+ });+ expect(await readSupportAccess(user.id)).toMatchObject({+ [orgId]: { role: "VIEWER" },+ });+ });++ it.each([+ ["the issuer", "LANGFUSE_CONDUCTORONE_ISSUER"],+ ["the entitlement", "LANGFUSE_CONDUCTORONE_ENTITLEMENT_ID"],+ ["the Cloud region", "NEXT_PUBLIC_LANGFUSE_CLOUD_REGION"],+ ] as const)("is disabled (404) without %s configured", async (_, key) => {+ const { email, user, orgId } = await createFixture();+ const body = provisionBody({ email, orgId, type: grantType() });+ const previous = env[key];+ Object.assign(env, { [key]: undefined });+ try {+ const response = await callWebhook(body, `Bearer ${await sign(body)}`);+ expect(response.status).toBe(404);+ } finally {+ Object.assign(env, { [key]: previous });+ }+ expect(await readSupportAccess(user.id)).toBeNull();+ });+});++describe("support access in the product", () => {+ async function grant(email: string, orgId: string, duration?: string) {+ const body = provisionBody({ email, orgId, type: grantType(duration) });+ const response = await callWebhook(body, `Bearer ${await sign(body)}`);+ expect(response.body).toMatchObject({ complete: {} });+ }++ it("gives read access to the granted organization's projects", async () => {+ const { email, orgId, projectId } = await createFixture();+ await grant(email, orgId);++ const { session, caller } = await callerFor(email);++ expect(session.user?.organizations).toContainEqual(+ expect.objectContaining({+ id: orgId,+ role: "VIEWER",+ supportAccess: true,+ }),+ );+ await expect(caller.scoreConfigs.all({ projectId })).resolves.toMatchObject(+ { totalCount: 0 },+ );+ });++ it("is read-only", async () => {+ const { email, orgId, projectId } = await createFixture();+ await grant(email, orgId);++ const { caller } = await callerFor(email);++ await expect(+ caller.scoreConfigs.create({+ projectId,+ name: "support-write",+ dataType: "BOOLEAN",+ categories: [+ { label: "True", value: 1 },+ { label: "False", value: 0 },+ ],+ }),+ ).rejects.toMatchObject({ code: "FORBIDDEN" });+ });++ it("gives no access to other organizations", async () => {+ const { email, orgId } = await createFixture();+ const other = await createFixture();+ await grant(email, orgId);++ const { session, caller } = await callerFor(email);++ expect(session.user?.organizations.map((o) => o.id)).not.toContain(+ other.orgId,+ );+ await expect(+ caller.scoreConfigs.all({ projectId: other.projectId }),+ ).rejects.toMatchObject({ code: "UNAUTHORIZED" });+ });++ it("gives no access once the grant has expired", async () => {+ const { email, user, orgId, projectId } = await createFixture();+ await prisma.user.update({+ where: { id: user.id },+ data: {+ supportAccess: {+ [orgId]: {+ role: "VIEWER",+ expiresAt: new Date(Date.now() - 1000).toISOString(),+ },+ },+ },+ });++ const { session, caller } = await callerFor(email);++ expect(session.user?.organizations.map((o) => o.id)).not.toContain(orgId);+ await expect(caller.scoreConfigs.all({ projectId })).rejects.toMatchObject({+ code: "UNAUTHORIZED",+ });+ });++ it("gives no access after a revoke", async () => {+ const { email, orgId, projectId } = await createFixture();+ await grant(email, orgId);+ const body = provisionBody({ email, orgId, type: revokeType });+ await callWebhook(body, `Bearer ${await sign(body)}`);++ const { caller } = await callerFor(email);++ await expect(caller.scoreConfigs.all({ projectId })).rejects.toMatchObject({+ code: "UNAUTHORIZED",+ });+ });++ it.each([+ ["longer than 12h", "43201s"],+ ["without a duration", "permanent"],+ ])("refuses a grant %s", async (_, duration) => {+ const { email, user, orgId } = await createFixture();+ const body = provisionBody({ email, orgId, type: grantType(duration) });++ const response = await callWebhook(body, `Bearer ${await sign(body)}`);++ expect(response.body).toMatchObject({ errored: {} });+ expect(await readSupportAccess(user.id)).toBeNull();+ });+});diff --git a/web/src/__tests__/server/unit/conductorOneWebhook.servertest.ts b/web/src/__tests__/server/unit/conductorOneWebhook.servertest.tsnew file mode 100644index 0000000000..72d7d60437--- /dev/null+++ b/web/src/__tests__/server/unit/conductorOneWebhook.servertest.ts@@ -0,0 +1,377 @@+import { createHash } from "node:crypto";++import {+ createLocalJWKSet,+ exportJWK,+ generateKeyPair,+ SignJWT,+ type JWTPayload,+} from "jose";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++const db = vi.hoisted(() => ({+ user: { findUnique: vi.fn(), update: vi.fn() },+ organization: { findUnique: vi.fn(), findMany: vi.fn() },+ $executeRaw: vi.fn(),+}));++vi.mock("@langfuse/shared/src/db", () => ({+ prisma: db,+ Prisma: { DbNull: "DbNull" },+ Role: { VIEWER: "VIEWER" },+}));++import { verifyConductorOneRequest } from "@/src/ee/features/support-access/server/conductorOneAuth";+import {+ C1_PROVISION_EVENT,+ parseConductorOneEnvelope,+ parseProvisionPayload as toRequest,+ type GrantRequest,+ type RevokeRequest,+} from "@/src/ee/features/support-access/server/conductorOnePayload";+import { provisionSupportAccess } from "@/src/ee/features/support-access/server/provisionSupportAccess";+import {+ getActiveSupportAccessGrants,+ getSupportAccessMemberships,+ parseSupportAccess,+} from "@/src/ee/features/support-access/server/supportAccess";++describe("verifyConductorOneRequest", () => {+ const issuer = "clickhouse.conductor.one";+ const audience = "us.cloud.langfuse.com";+ const body = Buffer.from('{"event":"x"}');+ const bodyHash = createHash("sha256").update(body).digest("base64");+ let key: CryptoKey;+ let unknownKey: CryptoKey;+ let jwks: ReturnType<typeof createLocalJWKSet>;++ beforeAll(async () => {+ const pair = await generateKeyPair("RS256");+ key = pair.privateKey;+ unknownKey = (await generateKeyPair("RS256")).privateKey;+ const jwk = {+ ...(await exportJWK(pair.publicKey)),+ kid: "k",+ alg: "RS256",+ };+ jwks = createLocalJWKSet({ keys: [jwk] });+ });++ async function sign(+ claims: JWTPayload = {},+ opts: { key?: CryptoKey; expiresIn?: string } = {},+ ) {+ const { iss = issuer, aud = audience, ...rest } = claims;+ return new SignJWT({ htb_s256: bodyHash, ...rest })+ .setProtectedHeader({ alg: "RS256", kid: "k" })+ .setIssuer(iss)+ .setAudience(aud)+ .setIssuedAt()+ .setExpirationTime(opts.expiresIn ?? "2m")+ .sign(opts.key ?? key);+ }++ const verify = (authorization: string | null, rawBody = body) =>+ verifyConductorOneRequest({+ authorization,+ rawBody,+ issuer,+ audience,+ jwks,+ });++ it.each(["bearer", "Bearer"])(+ "accepts a valid token for this body (%s)",+ async (scheme) => {+ await expect(+ verify(`${scheme} ${await sign()}`),+ ).resolves.toBeUndefined();+ },+ );++ it.each([+ ["another issuer", { iss: "evil.conductor.one" }],+ ["another region's host", { aud: "cloud.langfuse.com" }],+ ["another body's hash", { htb_s256: "AAAA" }],+ ["no body hash", { htb_s256: undefined }],+ ])("rejects %s", async (_, claims) => {+ await expect(verify(`bearer ${await sign(claims)}`)).rejects.toThrow();+ });++ it("rejects a token moved onto a different body", async () => {+ const token = await sign();+ await expect(+ verify(`bearer ${token}`, Buffer.from('{"event":"y"}')),+ ).rejects.toThrow();+ });++ it("rejects an unknown key, an expired token and alg none", async () => {+ const forged = await sign({}, { key: unknownKey });+ const expired = await sign({}, { expiresIn: "-1m" });+ const part = (v: object) =>+ Buffer.from(JSON.stringify(v)).toString("base64url");+ const unsigned = `${part({ alg: "none" })}.${part({ iss: issuer, aud: audience, htb_s256: bodyHash })}.`;+ for (const token of [forged, expired, unsigned]) {+ await expect(verify(`bearer ${token}`)).rejects.toThrow();+ }+ });++ it("rejects missing authorization", async () => {+ for (const authorization of [null, "", "Basic abc"]) {+ await expect(verify(authorization)).rejects.toThrow();+ }+ });+});++describe("parseProvisionPayload", () => {+ const parseProvisionPayload = (payload: unknown) => {+ const body = JSON.stringify({ event: C1_PROVISION_EVENT, payload });+ const envelope = parseConductorOneEnvelope(Buffer.from(body));+ return envelope?.event === C1_PROVISION_EVENT+ ? toRequest(envelope.payload)+ : null;+ };+ const c1User = {+ "@type": "type.googleapis.com/c1.api.user.v1.User",+ id: "c1-user",+ email: "[email protected]",+ };+ const payload = (type: object, extra: object = {}) => ({+ taskView: { task: { id: "task-1", userId: "c1-user", type, ...extra } },+ expanded: [+ { ...c1User, id: "someone-else", email: "[email protected]" },+ c1User,+ ],+ });+ // C1 puts submitted values in `task.data`; `task.form` only holds field definitions.+ const form = {+ form: { fields: [{ name: "langfuse_organization_id_0" }] },+ data: { langfuse_organization_id_0: "org-1" },+ };++ it("reads a grant", () => {+ const grant = { appEntitlementId: "ent-1", grantDuration: "43200s" };+ expect(parseProvisionPayload(payload({ grant }, form))).toEqual({+ action: "grant",+ taskId: "task-1",+ entitlementId: "ent-1",+ email: "[email protected]",+ orgId: "org-1",+ durationMs: 43_200_000,+ });+ });++ it("reads a grant when C1 leaves empty objects in expanded", () => {+ const grant = { appEntitlementId: "ent-1", grantDuration: "43200s" };+ const withEmpty = payload({ grant }, form);+ withEmpty.expanded.push({} as never);+ expect(parseProvisionPayload(withEmpty)).toMatchObject({+ action: "grant",+ orgId: "org-1",+ });+ });++ it("reads a revoke", () => {+ const revoke = { appEntitlementId: "ent-1" };+ const extra = { data: { Justification_0: "done" } };+ expect(parseProvisionPayload(payload({ revoke }, extra))).toEqual({+ action: "revoke",+ taskId: "task-1",+ entitlementId: "ent-1",+ email: "[email protected]",+ });+ });++ it("treats a missing or non-protobuf duration as none", () => {+ for (const grantDuration of [null, "12h", "-1s"]) {+ const grant = { appEntitlementId: "ent-1", grantDuration };+ expect(parseProvisionPayload(payload({ grant }, form))).toMatchObject({+ durationMs: null,+ });+ }+ });++ it.each([+ [+ "a grant without form values",+ payload({ grant: { appEntitlementId: "e" } }),+ ],+ [+ "form values nested under task.form",+ payload(+ { grant: { appEntitlementId: "e" } },+ { form: { data: { langfuse_organization_id_0: "org-1" } } },+ ),+ ],+ ["no task type", payload({})],+ ["something that isn't a task", { hello: "world" }],+ ])("returns null for %s", (_, value) => {+ expect(parseProvisionPayload(value)).toBeNull();+ });+});++describe("provisionSupportAccess", () => {+ const entitlementId = "ent-1";+ const now = new Date("2026-10-23T12:00:00.000Z");+ const user = { id: "user-1", supportAccess: null };+ const grantRequest: GrantRequest = {+ action: "grant",+ taskId: "task-1",+ entitlementId: "ent-1",+ email: "[email protected]",+ orgId: "org-1",+ durationMs: 12 * 3_600_000,+ };+ const revokeRequest: RevokeRequest = {+ action: "revoke",+ taskId: "task-2",+ entitlementId: "ent-1",+ email: "[email protected]",+ };++ beforeEach(() => {+ vi.clearAllMocks();+ db.user.findUnique.mockResolvedValue(user);+ db.organization.findUnique.mockResolvedValue({ id: "org-1" });+ });++ it("grants VIEWER until now + duration", async () => {+ expect(+ await provisionSupportAccess(grantRequest, entitlementId, now),+ ).toEqual({+ ok: true,+ message: "VIEWER access granted until 2026-10-24T00:00:00.000Z",+ });+ expect(db.$executeRaw).toHaveBeenCalledOnce();+ });++ it.each([+ ["another entitlement", { entitlementId: "ent-admin" }],+ ["no duration (permanent)", { durationMs: null }],+ ["a duration above 12h", { durationMs: 24 * 3_600_000 }],+ ["a non-ClickHouse email", { email: "[email protected]" }],+ ])("rejects %s", async (_, change) => {+ const request = { ...grantRequest, ...change };+ expect(+ await provisionSupportAccess(request, entitlementId, now),+ ).toMatchObject({+ ok: false,+ });+ expect(db.$executeRaw).not.toHaveBeenCalled();+ });++ it("rejects when there is no Langfuse user", async () => {+ db.user.findUnique.mockResolvedValue(null);+ expect(+ await provisionSupportAccess(grantRequest, entitlementId, now),+ ).toMatchObject({+ ok: false,+ });+ expect(db.$executeRaw).not.toHaveBeenCalled();+ });++ it("rejects an unknown organization", async () => {+ db.organization.findUnique.mockResolvedValue(null);+ expect(+ await provisionSupportAccess(grantRequest, entitlementId, now),+ ).toMatchObject({+ ok: false,+ });+ });++ it("revokes all support access", async () => {+ expect(+ await provisionSupportAccess(revokeRequest, entitlementId),+ ).toMatchObject({+ ok: true,+ });+ expect(db.user.update).toHaveBeenCalledWith({+ where: { id: "user-1" },+ data: { supportAccess: "DbNull" },+ });+ });++ it("ignores revokes for another entitlement", async () => {+ const request = { ...revokeRequest, entitlementId: "other" };+ expect(await provisionSupportAccess(request, entitlementId)).toMatchObject({+ ok: false,+ });+ expect(db.user.update).not.toHaveBeenCalled();+ });+});++describe("support access in the session", () => {+ const now = new Date("2026-10-23T12:00:00.000Z");+ const entry = (expiresAt: string) => ({ role: "VIEWER" as const, expiresAt });+ const active = entry("2099-01-01T00:00:00.000Z");++ beforeEach(() => vi.clearAllMocks());++ it("returns only unexpired grants", () => {+ expect(+ getActiveSupportAccessGrants(+ {+ current: entry("2026-10-23T13:00:00.000Z"),+ expired: entry("2026-10-23T11:59:59.000Z"),+ },+ now,+ ),+ ).toEqual([{ orgId: "current", role: "VIEWER" }]);+ });++ it("parses malformed values or other roles to no grants", () => {+ expect(+ parseSupportAccess({+ org: { role: "OWNER", expiresAt: "2099-01-01T00:00:00.000Z" },+ }),+ ).toEqual({});+ expect(parseSupportAccess(null)).toEqual({});+ expect(parseSupportAccess("garbage")).toEqual({});+ });++ it("adds VIEWER only for orgs the user is not a member of", async () => {+ db.organization.findMany.mockResolvedValue([{ id: "org-2", projects: [] }]);+ const memberships = await getSupportAccessMemberships({+ supportAccess: { "org-1": active, "org-2": active },+ organizationMemberships: [{ organization: { id: "org-1" } }],+ });+ expect(db.organization.findMany).toHaveBeenCalledWith(+ expect.objectContaining({ where: { id: { in: ["org-2"] } } }),+ );+ expect(memberships).toEqual([+ {+ organization: { id: "org-2", projects: [] },+ role: "VIEWER",+ ProjectMemberships: [],+ supportAccess: true,+ },+ ]);+ });++ it("gives no access to an org whose grant has expired", async () => {+ db.organization.findMany.mockResolvedValue([+ { id: "active", projects: [] },+ ]);+ const memberships = await getSupportAccessMemberships({+ supportAccess: {+ active,+ expired: entry(new Date(Date.now() - 1000).toISOString()),+ },+ organizationMemberships: [],+ });+ expect(db.organization.findMany).toHaveBeenCalledWith(+ expect.objectContaining({ where: { id: { in: ["active"] } } }),+ );+ expect(memberships.map((m) => m.organization.id)).toEqual(["active"]);+ });++ it("does not query when there is no active grant", async () => {+ expect(+ await getSupportAccessMemberships({+ supportAccess: null,+ organizationMemberships: [],+ }),+ ).toEqual([]);+ expect(db.organization.findMany).not.toHaveBeenCalled();+ });+});diff --git a/web/src/ee/features/support-access/server/conductorOneAuth.ts b/web/src/ee/features/support-access/server/conductorOneAuth.tsnew file mode 100644index 0000000000..6aa2a6f575--- /dev/null+++ b/web/src/ee/features/support-access/server/conductorOneAuth.ts@@ -0,0 +1,41 @@+import { createHash } from "node:crypto";++import { createRemoteJWKSet, jwtVerify, type JWTVerifyGetKey } from "jose";++let cachedJwks: { issuer: string; jwks: JWTVerifyGetKey } | undefined;++export function getConductorOneJwks(issuer: string): JWTVerifyGetKey {+ if (cachedJwks?.issuer !== issuer) {+ const url = new URL(`https://${issuer}/auth/v1/jwks`);+ cachedJwks = { issuer, jwks: createRemoteJWKSet(url) };+ }+ return cachedJwks.jwks;+}++// https://www.c1.ai/docs/product/admin/webhooks+export async function verifyConductorOneRequest(params: {+ authorization: string | null;+ rawBody: Buffer;+ issuer: string;+ audience: string;+ jwks: JWTVerifyGetKey;+}): Promise<void> {+ const token = params.authorization?.match(/^bearer (\S+)$/i)?.[1];+ if (!token) throw new Error("Missing bearer token");++ const { payload } = await jwtVerify(token, params.jwks, {+ issuer: params.issuer,+ audience: params.audience,+ algorithms: ["RS256", "ES256", "EdDSA"],+ requiredClaims: ["exp", "htb_s256"],+ });++ const bodyHash = createHash("sha256").update(params.rawBody).digest();+ const accepted = [+ bodyHash.toString("base64"),+ bodyHash.toString("base64url"),+ ];+ if (!accepted.includes(String(payload.htb_s256))) {+ throw new Error("Body hash mismatch");+ }+}diff --git a/web/src/ee/features/support-access/server/conductorOnePayload.ts b/web/src/ee/features/support-access/server/conductorOnePayload.tsnew file mode 100644index 0000000000..b837f2b524--- /dev/null+++ b/web/src/ee/features/support-access/server/conductorOnePayload.ts@@ -0,0 +1,120 @@+import { z } from "zod/v4";++export const C1_TEST_EVENT = "c1.webhooks.v1.PayloadTest";+export const C1_PROVISION_EVENT = "c1.webhooks.v1.PayloadProvisionStep";++export type GrantRequest = {+ action: "grant";+ taskId: string;+ entitlementId: string;+ email: string;+ orgId: string;+ durationMs: number | null;+};+export type RevokeRequest = {+ action: "revoke";+ taskId: string;+ entitlementId: string;+ email: string;+};+export type SupportAccessRequest = GrantRequest | RevokeRequest;++// C1 assigns form field ids itself; this is the "Langfuse Form" field holding+// the organization id. C1 sends submitted form values in `task.data`, keyed by+// field id.+const ORG_ID_FORM_FIELD = "langfuse_organization_id_0";++// https://www.c1.ai/docs/api-reference/task/get+const ProvisionPayloadSchema = z.object({+ taskView: z.object({+ task: z.object({+ id: z.string().min(1),+ userId: z.string().min(1),+ type: z.object({+ grant: z+ .object({+ appEntitlementId: z.string(),+ grantDuration: z.string().nullish(),+ })+ .nullish(),+ revoke: z.object({ appEntitlementId: z.string() }).nullish(),+ }),+ data: z+ .object({ [ORG_ID_FORM_FIELD]: z.string().min(1).optional() })+ .nullish(),+ }),+ }),+ expanded: z+ .array(+ z.looseObject({+ "@type": z.string().optional(),+ id: z.string().optional(),+ }),+ )+ .nullish(),+});++type ProvisionPayload = z.infer<typeof ProvisionPayloadSchema>;++const EnvelopeSchema = z.discriminatedUnion("event", [+ z.object({ event: z.literal(C1_TEST_EVENT) }),+ z.object({+ event: z.literal(C1_PROVISION_EVENT),+ payload: ProvisionPayloadSchema,+ }),+]);++function findRequesterEmail(payload: ProvisionPayload): string | null {+ const userId = payload.taskView.task.userId;+ const c1User = payload.expanded?.find(+ (obj) => obj["@type"]?.endsWith("c1.api.user.v1.User") && obj.id === userId,+ );+ const email = z.email().safeParse(c1User?.email);+ return email.success ? email.data.toLowerCase() : null;+}++// protobuf Duration JSON, e.g. "43200s" or "1.5s".+function parseDurationMs(duration: string | null | undefined): number | null {+ const seconds = duration?.match(/^(\d+(?:\.\d+)?)s$/)?.[1];+ return seconds ? Math.round(Number(seconds) * 1000) : null;+}++export function parseConductorOneEnvelope(rawBody: Buffer) {+ try {+ const json: unknown = JSON.parse(rawBody.toString("utf8"));+ return EnvelopeSchema.safeParse(json).data ?? null;+ } catch {+ return null;+ }+}++export function parseProvisionPayload(+ payload: ProvisionPayload,+): SupportAccessRequest | null {+ const { task } = payload.taskView;+ const { grant, revoke } = task.type;+ const email = findRequesterEmail(payload);+ if (!email) return null;++ if (grant) {+ const orgId = task.data?.[ORG_ID_FORM_FIELD];+ if (!orgId) return null;+ return {+ action: "grant",+ taskId: task.id,+ entitlementId: grant.appEntitlementId,+ email,+ orgId,+ durationMs: parseDurationMs(grant.grantDuration),+ };+ }+ if (revoke) {+ return {+ action: "revoke",+ taskId: task.id,+ entitlementId: revoke.appEntitlementId,+ email,+ };+ }+ return null;+}diff --git a/web/src/ee/features/support-access/server/conductorOneWebhook.ts b/web/src/ee/features/support-access/server/conductorOneWebhook.tsnew file mode 100644index 0000000000..4628f876ed--- /dev/null+++ b/web/src/ee/features/support-access/server/conductorOneWebhook.ts@@ -0,0 +1,96 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import getRawBody from "raw-body";++import { env } from "@/src/env.mjs";+import { logger } from "@langfuse/shared/src/server";++import {+ getConductorOneJwks,+ verifyConductorOneRequest,+} from "./conductorOneAuth";+import {+ C1_TEST_EVENT,+ parseConductorOneEnvelope,+ parseProvisionPayload,+} from "./conductorOnePayload";+import {+ provisionSupportAccess,+ type ProvisionResult,+} from "./provisionSupportAccess";++function toC1Response(result: ProvisionResult) {+ const comment = { comment: result.message };+ return result.ok+ ? { version: "v1", complete: comment }+ : { version: "v1", errored: comment };+}++// C1 retries any non-2xx, so rejected requests answer 200 with `errored`.+export async function conductorOneWebhookHandler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ const issuer = env.LANGFUSE_CONDUCTORONE_ISSUER;+ const entitlementId = env.LANGFUSE_CONDUCTORONE_ENTITLEMENT_ID;+ const isCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);+ if (!issuer || !entitlementId || !isCloud || !env.NEXTAUTH_URL) {+ return res.status(404).json({ error: "Not found" });+ }+ if (req.method !== "POST") {+ res.setHeader("Allow", "POST");+ return res.status(405).json({ error: "Method not allowed" });+ }++ // Requires `bodyParser: false` on the route: the JWT signs the raw body's hash.+ let rawBody: Buffer;+ try {+ rawBody = await getRawBody(req, {+ length: req.headers["content-length"],+ limit: "1mb",+ });+ } catch {+ return res.status(413).json({ error: "Payload too large" });+ }++ try {+ await verifyConductorOneRequest({+ authorization: req.headers.authorization ?? null,+ rawBody,+ issuer,+ audience: new URL(env.NEXTAUTH_URL).hostname,+ jwks: getConductorOneJwks(issuer),+ });+ } catch (error) {+ logger.warn("ConductorOne webhook rejected", {+ reason: (error as Error).message,+ });+ return res.status(401).json({ error: "Unauthorized" });+ }++ const envelope = parseConductorOneEnvelope(rawBody);+ if (envelope?.event === C1_TEST_EVENT) {+ return res.status(200).json({ version: "v1" });+ }++ const request = envelope ? parseProvisionPayload(envelope.payload) : null;+ if (!request) {+ logger.warn("ConductorOne webhook unrecognized payload");+ const result = { ok: false, message: "Unrecognized webhook payload" };+ return res.status(200).json(toC1Response(result));+ }++ try {+ const result = await provisionSupportAccess(request, entitlementId);+ if (!result.ok) {+ logger.warn("ConductorOne provisioning rejected", {+ reason: result.message,+ action: request.action,+ c1TaskId: request.taskId,+ });+ }+ return res.status(200).json(toC1Response(result));+ } catch (error) {+ logger.error("ConductorOne provisioning failed", error);+ return res.status(500).json({ error: "Internal server error" });+ }+}diff --git a/web/src/ee/features/support-access/server/provisionSupportAccess.ts b/web/src/ee/features/support-access/server/provisionSupportAccess.tsnew file mode 100644index 0000000000..3bd71516ad--- /dev/null+++ b/web/src/ee/features/support-access/server/provisionSupportAccess.ts@@ -0,0 +1,104 @@+import { prisma } from "@langfuse/shared/src/db";+import { logger } from "@langfuse/shared/src/server";++import {+ type GrantRequest,+ type RevokeRequest,+ type SupportAccessRequest,+} from "./conductorOnePayload";+import {+ grantSupportAccess,+ parseSupportAccess,+ revokeAllSupportAccess,+} from "./supportAccess";++const SUPPORT_EMAIL_DOMAIN = "clickhouse.com";+const MAX_GRANT_MS = 12 * 60 * 60 * 1000;++export type ProvisionResult = { ok: boolean; message: string };++function accepted(message: string): ProvisionResult {+ return { ok: true, message };+}++function rejected(message: string): ProvisionResult {+ return { ok: false, message };+}++async function findUser(email: string) {+ const user = await prisma.user.findUnique({+ where: { email },+ select: { id: true, supportAccess: true },+ });+ if (!user) return null;+ return { id: user.id, supportAccess: parseSupportAccess(user.supportAccess) };+}++type User = NonNullable<Awaited<ReturnType<typeof findUser>>>;++async function grant(+ request: GrantRequest,+ user: User | null,+ now: Date,+): Promise<ProvisionResult> {+ if (!request.durationMs || request.durationMs > MAX_GRANT_MS) {+ return rejected("Grant must be time-bound to at most 12h");+ }+ if (!request.email.endsWith(`@${SUPPORT_EMAIL_DOMAIN}`)) {+ return rejected("Requester email domain is not allowed");+ }+ if (!user) {+ return rejected("Sign in to this Langfuse region once, then retry");+ }++ const org = await prisma.organization.findUnique({+ where: { id: request.orgId },+ select: { id: true },+ });+ if (!org) {+ return rejected("Organization not found in this region");+ }++ const expiresAt = new Date(now.getTime() + request.durationMs);+ await grantSupportAccess(user.id, org.id, expiresAt);+ logger.info("ConductorOne support access granted", {+ userId: user.id,+ orgId: org.id,+ expiresAt: expiresAt.toISOString(),+ c1TaskId: request.taskId,+ });+ return accepted(`VIEWER access granted until ${expiresAt.toISOString()}`);+}++async function revoke(+ request: RevokeRequest,+ user: User | null,+): Promise<ProvisionResult> {+ if (!user) {+ return accepted("No Langfuse user, nothing to revoke");+ }++ const orgIds = await revokeAllSupportAccess(user);+ logger.info("ConductorOne support access revoked", {+ userId: user.id,+ orgIds,+ c1TaskId: request.taskId,+ });+ return accepted("Support access revoked");+}++export async function provisionSupportAccess(+ request: SupportAccessRequest,+ entitlementId: string,+ now: Date = new Date(),+): Promise<ProvisionResult> {+ if (request.entitlementId !== entitlementId) {+ return rejected("Entitlement is not handled by this Langfuse region");+ }++ const user = await findUser(request.email);+ if (request.action === "grant") {+ return grant(request, user, now);+ }+ return revoke(request, user);+}diff --git a/web/src/ee/features/support-access/server/supportAccess.ts b/web/src/ee/features/support-access/server/supportAccess.tsnew file mode 100644index 0000000000..63507713e7--- /dev/null+++ b/web/src/ee/features/support-access/server/supportAccess.ts@@ -0,0 +1,101 @@+import { z } from "zod/v4";++import { Prisma, prisma } from "@langfuse/shared/src/db";++// users.support_access, e.g.+// { "<orgId>": { "role": "VIEWER", "expiresAt": "2026-10-27T04:15:37.316Z" } }+export type SupportAccess = {+ [orgId: string]: {+ role: "VIEWER";+ expiresAt: string;+ };+};++const SupportAccessSchema: z.ZodType<SupportAccess> = z.record(+ z.string(),+ z.object({+ role: z.literal("VIEWER"),+ expiresAt: z.iso.datetime(),+ }),+);++export function parseSupportAccess(value: Prisma.JsonValue): SupportAccess {+ return SupportAccessSchema.safeParse(value ?? {}).data ?? {};+}++export function getActiveSupportAccessGrants(+ supportAccess: SupportAccess,+ now: Date = new Date(),+): { orgId: string; role: SupportAccess[string]["role"] }[] {+ return Object.entries(supportAccess)+ .filter(([, entry]) => new Date(entry.expiresAt) > now)+ .map(([orgId, entry]) => ({ orgId, role: entry.role }));+}++export async function getSupportAccessMemberships(+ user: {+ supportAccess: Prisma.JsonValue;+ organizationMemberships: { organization: { id: string } }[];+ } | null,+) {+ if (!user) return [];+ const memberOrgIds = new Set(+ user.organizationMemberships.map((m) => m.organization.id),+ );+ const roleByOrgId = new Map(+ getActiveSupportAccessGrants(parseSupportAccess(user.supportAccess))+ .filter((grant) => !memberOrgIds.has(grant.orgId))+ .map((grant) => [grant.orgId, grant.role]),+ );+ if (roleByOrgId.size === 0) return [];++ const organizations = await prisma.organization.findMany({+ where: { id: { in: [...roleByOrgId.keys()] } },+ include: {+ projects: {+ where: { deletedAt: null },+ orderBy: { createdAt: "desc" },+ },+ },+ });+ return organizations.flatMap((organization) => {+ const role = roleByOrgId.get(organization.id);+ if (!role) return [];+ return [+ {+ organization,+ role,+ ProjectMemberships: [],+ supportAccess: true as const,+ },+ ];+ });+}++export async function grantSupportAccess(+ userId: string,+ orgId: string,+ expiresAt: Date,+) {+ const entry: SupportAccess[string] = {+ role: "VIEWER",+ expiresAt: expiresAt.toISOString(),+ };+ // Single statement so concurrent grants for different orgs don't collide.+ await prisma.$executeRaw`+ UPDATE users+ SET support_access = COALESCE(support_access, '{}'::jsonb)+ || jsonb_build_object(${orgId}::text, ${JSON.stringify(entry)}::jsonb)+ WHERE id = ${userId}`;+}++export async function revokeAllSupportAccess(user: {+ id: string;+ supportAccess: SupportAccess;+}): Promise<string[]> {+ await prisma.user.update({+ where: { id: user.id },+ data: { supportAccess: Prisma.DbNull },+ });+ return Object.keys(user.supportAccess);+}diff --git a/web/src/env.mjs b/web/src/env.mjsindex 7fcb78fb25..0d826db360 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -366,6 +366,11 @@ export const env = createEnv({"ENCRYPTION_KEY must be 256 bits, 64 string characters in hex format, generate via: openssl rand -hex 32",).optional(),+ // ConductorOne support access webhook (Langfuse Cloud only), disabled+ // unless both are set. ISSUER is the C1 tenant domain, e.g.+ // "clickhouse.conductor.one"; ENTITLEMENT_ID is this region's entitlement.+ LANGFUSE_CONDUCTORONE_ISSUER: z.string().min(1).optional(),+ LANGFUSE_CONDUCTORONE_ENTITLEMENT_ID: z.string().min(1).optional(),LANGFUSE_AI_GATEWAY_SERVICE_KEY: z.string().min(1).optional(),LANGFUSE_AI_GATEWAY_SERVICE_KEY_PREVIOUS: z.string().min(1).optional(),// Whether an AI gateway is deployed next to Web. When false, every gateway@@ -1183,6 +1188,9 @@ export const env = createEnv({LANGFUSE_EE_LICENSE_KEY: process.env.LANGFUSE_EE_LICENSE_KEY,ADMIN_API_KEY: process.env.ADMIN_API_KEY,ENCRYPTION_KEY: process.env.ENCRYPTION_KEY,+ LANGFUSE_CONDUCTORONE_ISSUER: process.env.LANGFUSE_CONDUCTORONE_ISSUER,+ LANGFUSE_CONDUCTORONE_ENTITLEMENT_ID:+ process.env.LANGFUSE_CONDUCTORONE_ENTITLEMENT_ID,LANGFUSE_AI_GATEWAY_SERVICE_KEY:process.env.LANGFUSE_AI_GATEWAY_SERVICE_KEY,LANGFUSE_AI_GATEWAY_SERVICE_KEY_PREVIOUS:diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.tsindex 867f5ba494..0dc281dd44 100644--- a/web/src/features/audit-logs/auditLog.ts+++ b/web/src/features/audit-logs/auditLog.ts@@ -65,6 +65,7 @@ type AuditableResource =| "gatewayConfig"| "gatewayAiConnection"| "topicConfig"+ | "supportAccess"// legacy resources| "membership";@@ -106,7 +107,11 @@ export type AuditLog = {// Writes made by Langfuse itself rather than by a user or an API key pass these// sentinel actor ids. The Postgres row keeps them, because its actor type// cannot be SYSTEM. The staged event records a SYSTEM actor instead.-const SYSTEM_ACTOR_USER_IDS = new Set(["stripe-webhook", "clickhouse-webhook"]);+const SYSTEM_ACTOR_USER_IDS = new Set([+ "stripe-webhook",+ "clickhouse-webhook",+ "conductorone-webhook",+]);const ADMIN_API_KEY_IDS = new Set(["ADMIN_KEY", "ADMIN_API_KEY"]);const ADMIN_API_ACTOR: StagedAuditLogActor = {type: "SYSTEM",diff --git a/web/src/features/customer-data-warning/CustomerDataWarningBannerView.tsx b/web/src/features/customer-data-warning/CustomerDataWarningBannerView.tsxindex 40ce3700a9..f036dae0e5 100644--- a/web/src/features/customer-data-warning/CustomerDataWarningBannerView.tsx+++ b/web/src/features/customer-data-warning/CustomerDataWarningBannerView.tsx@@ -5,7 +5,7 @@ import {/*** Top-of-page strip for ClickHouse and Langfuse staff viewing a customer- * project or organization through admin access. Same placement and shape as the preview+ * project or organization through admin or support access. Same placement and shape as the preview* deployment strip, in amber so the two cannot be confused. It is not* dismissible.*/diff --git a/web/src/features/customer-data-warning/getCustomerDataWarning.clienttest.ts b/web/src/features/customer-data-warning/getCustomerDataWarning.clienttest.tsindex 815d3dee55..682268cfbe 100644--- a/web/src/features/customer-data-warning/getCustomerDataWarning.clienttest.ts+++ b/web/src/features/customer-data-warning/getCustomerDataWarning.clienttest.ts@@ -53,6 +53,37 @@ describe("getCustomerDataWarning", () => {).toBeNull();});+ it("shows for a non-admin staff user viewing through support access", () => {+ expect(+ getCustomerDataWarning({+ ...viewingCustomerProject,+ isAdmin: false,+ memberships: [+ {+ id: "org_customer",+ projects: [{ id: "proj_customer" }],+ supportAccess: true,+ },+ ],+ }),+ ).toMatchObject({ scope: "project" });+ });++ it("shows an organization warning for a support access membership", () => {+ expect(+ getCustomerDataWarning({+ ...viewingCustomerProject,+ isAdmin: false,+ projectId: null,+ organizationId: "org_customer",+ projectName: null,+ memberships: [+ { id: "org_customer", projects: [], supportAccess: true },+ ],+ }),+ ).toMatchObject({ scope: "organization" });+ });+it("hides on self-hosted deployments", () => {expect(getCustomerDataWarning({diff --git a/web/src/features/customer-data-warning/getCustomerDataWarning.ts b/web/src/features/customer-data-warning/getCustomerDataWarning.tsindex bc53417e23..1bb00e7b29 100644--- a/web/src/features/customer-data-warning/getCustomerDataWarning.ts+++ b/web/src/features/customer-data-warning/getCustomerDataWarning.ts@@ -8,6 +8,7 @@ const STAFF_EMAIL_DOMAINS = ["@clickhouse.com", "@langfuse.com"] as const;type CustomerDataWarningMembership = {id: string;projects: { id: string }[];+ supportAccess?: boolean; // support access grant, not a real membership};export type CustomerDataWarning =@@ -57,11 +58,14 @@ function isOrganizationMember(export function getCustomerDataWarning(input: CustomerDataWarningInput,): CustomerDataWarning | null {- if (!input.isLangfuseCloud || !input.isAdmin) return null;+ const hasSupportAccess = input.memberships.some((m) => m.supportAccess);+ if (!input.isLangfuseCloud || !(input.isAdmin || hasSupportAccess))+ return null;if (!isStaffEmail(input.email)) return null;+ const memberships = input.memberships.filter((m) => !m.supportAccess);if (input.projectId) {- if (isProjectMember(input.memberships, input.projectId)) return null;+ if (isProjectMember(memberships, input.projectId)) return null;if (!input.organizationName || !input.projectName) return null;return {scope: "project",@@ -71,8 +75,7 @@ export function getCustomerDataWarning(}if (input.organizationId) {- if (isOrganizationMember(input.memberships, input.organizationId))- return null;+ if (isOrganizationMember(memberships, input.organizationId)) return null;if (!input.organizationName) return null;return {scope: "organization",diff --git a/web/src/pages/api/support-access/conductorone-webhook.ts b/web/src/pages/api/support-access/conductorone-webhook.tsnew file mode 100644index 0000000000..768723ad03--- /dev/null+++ b/web/src/pages/api/support-access/conductorone-webhook.ts@@ -0,0 +1,9 @@+import { conductorOneWebhookHandler } from "@/src/ee/features/support-access/server/conductorOneWebhook";++export default conductorOneWebhookHandler;++export const config = {+ api: {+ bodyParser: false,+ },+};diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 33e9f2c87c..9437a5753c 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -60,6 +60,7 @@ import {getSsoAuthProviderIdForDomain,loadSsoProviders,} from "@/src/ee/features/multi-tenant-sso/server";+import { getSupportAccessMemberships } from "@/src/ee/features/support-access/server/supportAccess";import {ENTERPRISE_SSO_REQUIRED_MESSAGE,MULTI_TENANT_SSO_DOMAIN_MISMATCH_MESSAGE,@@ -821,6 +822,7 @@ export async function getAuthOptions(featureFlags: true,admin: true,v4BetaEnabled: true,+ supportAccess: true,organizationMemberships: {// Newest first so demo project is last for the `project/~/` sentinelorderBy: {@@ -852,6 +854,12 @@ export async function getAuthOptions(});span.setAttribute("langfuse.user.id", dbUser?.id ?? "");+ // Support engineers with an unexpired ConductorOne grant see the+ // org as VIEWER.+ const organizationMemberships = [+ ...(dbUser?.organizationMemberships ?? []),+ ...(await getSupportAccessMemberships(dbUser)),+ ];// V4 preview availability is governed by the write mode:// - events_only: the legacy traces/observations tables are no longer// written, so the events-aware UI is the only correct read path —@@ -949,7 +957,7 @@ export async function getAuthOptions(canCreateOrganizations: canCreateOrganizations(dbUser.email,),- organizations: dbUser.organizationMemberships.map(+ organizations: organizationMemberships.map((orgMembership) => {const parsedCloudConfig = CloudConfigSchema.safeParse(orgMembership.organization.cloudConfig,@@ -958,6 +966,7 @@ export async function getAuthOptions(id: orgMembership.organization.id,name: orgMembership.organization.name,role: orgMembership.role,+ supportAccess: "supportAccess" in orgMembership,metadata:(orgMembership.organization.metadata as Record<string,diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.tsindex 86595cac1c..a27f229f0d 100644--- a/web/types/next-auth.d.ts+++ b/web/types/next-auth.d.ts@@ -38,6 +38,7 @@ declare module "next-auth" {id: PrismaOrganization["id"];name: PrismaOrganization["name"];role: Role;+ supportAccess?: boolean; // granted through a ConductorOne support access request, not a real membershipcloudConfig: CloudConfigSchema | undefined;plan: Plan;metadata: Record<string, unknown>;