🪢 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(admin-api): transfer projects between organizations (#19587)
Steffen Reuther1ca85793116f
diff --git a/fern/apis/organizations/definition/organizations.yml b/fern/apis/organizations/definition/organizations.ymlindex f7c53daf86..90dc27946c 100644--- a/fern/apis/organizations/definition/organizations.yml+++ b/fern/apis/organizations/definition/organizations.yml@@ -131,6 +131,29 @@ service:- commons.UnauthorizedError- commons.MethodNotAllowedError+ # Project endpoints+ transferProject:+ docs: |+ Transfer a project to another organization. The project keeps its data and its project-scoped API keys. Its project memberships and project-level user roles are removed, so members of the target organization get access through their organization role, and organization-scoped API keys of the source organization lose access.++ Transferring a project to the organization it already belongs to is a no-op.+ method: POST+ path: /projects/{projectId}/transfer+ path-parameters:+ projectId: string+ request:+ name: TransferProjectRequest+ body:+ properties:+ targetOrganizationId:+ type: string+ docs: ID of the organization to move the project into+ response: TransferProjectResponse+ errors:+ - commons.Error+ - commons.UnauthorizedError+ - commons.MethodNotAllowedError+types:Organizations:docs: List of organizations@@ -164,6 +187,14 @@ types:properties:success: boolean+ TransferProjectResponse:+ docs: Response for a project transfer+ properties:+ projectId: string+ organizationId:+ type: string+ docs: ID of the organization the project belongs to after the transfer+ApiKeyList:docs: List of API keys for an organizationproperties:diff --git a/web/public/generated/organizations-api/openapi.yml b/web/public/generated/organizations-api/openapi.ymlindex f166f48d79..30c6ca5427 100644--- a/web/public/generated/organizations-api/openapi.yml+++ b/web/public/generated/organizations-api/openapi.yml@@ -440,6 +440,71 @@ paths:schema:type: stringsecurity: *ref_0+ /api/admin/projects/{projectId}/transfer:+ post:+ description: >-+ Transfer a project to another organization. The project keeps its data+ and its project-scoped API keys. Its project memberships and+ project-level user roles are removed, so members of the target+ organization get access through their organization role, and+ organization-scoped API keys of the source organization lose access.+++ Transferring a project to the organization it already belongs to is a+ no-op.+ operationId: organizations_transferProject+ tags:+ - Organizations+ parameters:+ - name: projectId+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/TransferProjectResponse'+ '400':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '401':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '403':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '405':+ description: ''+ content:+ application/json:+ schema:+ type: string+ security: *ref_0+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ targetOrganizationId:+ type: string+ description: ID of the organization to move the project into+ required:+ - targetOrganizationIdcomponents:schemas:Organizations:@@ -513,6 +578,19 @@ components:type: booleanrequired:- success+ TransferProjectResponse:+ title: TransferProjectResponse+ type: object+ description: Response for a project transfer+ properties:+ projectId:+ type: string+ organizationId:+ type: string+ description: ID of the organization the project belongs to after the transfer+ required:+ - projectId+ - organizationIdApiKeyList:title: ApiKeyListtype: objectdiff --git a/web/src/__tests__/server/organizations-api.servertest.ts b/web/src/__tests__/server/organizations-api.servertest.tsindex 9bccb0c6ce..8283b427fe 100644--- a/web/src/__tests__/server/organizations-api.servertest.ts+++ b/web/src/__tests__/server/organizations-api.servertest.ts@@ -935,6 +935,115 @@ describe("Admin Organizations API", () => {});});+ describe("POST /api/admin/projects/[projectId]/transfer", () => {+ let sourceOrgId: string;+ let targetOrgId: string;+ let projectId: string;+ let userId: string;++ beforeEach(async () => {+ sourceOrgId = (+ await prisma.organization.create({+ data: { name: `Source Org ${randomUUID().substring(0, 8)}` },+ })+ ).id;+ targetOrgId = (+ await prisma.organization.create({+ data: { name: `Target Org ${randomUUID().substring(0, 8)}` },+ })+ ).id;+ projectId = (+ await prisma.project.create({+ data: {+ name: `Transfer Project ${randomUUID().substring(0, 8)}`,+ orgId: sourceOrgId,+ },+ })+ ).id;+ userId = (+ await prisma.user.create({+ data: { email: `transfer-member-${randomUUID()}@example.com` },+ })+ ).id;+ const orgMembership = await prisma.organizationMembership.create({+ data: { orgId: sourceOrgId, userId, role: "MEMBER" },+ });+ await prisma.projectMembership.create({+ data: {+ orgMembershipId: orgMembership.id,+ projectId,+ userId,+ role: "ADMIN",+ },+ });+ });++ afterEach(async () => {+ await prisma.organization.deleteMany({+ where: { id: { in: [sourceOrgId, targetOrgId] } },+ });+ await prisma.user.delete({ where: { id: userId } });+ });++ it("should move the project and drop its memberships", async () => {+ const response = await makeAPICall<{+ projectId: string;+ organizationId: string;+ }>(+ "POST",+ `/api/admin/projects/${projectId}/transfer`,+ { targetOrganizationId: targetOrgId },+ `Bearer ${ADMIN_API_KEY}`,+ );++ expect(response.status).toBe(200);+ expect(response.body).toEqual({+ projectId,+ organizationId: targetOrgId,+ });+ await expect(+ prisma.project.findUnique({ where: { id: projectId } }),+ ).resolves.toMatchObject({ orgId: targetOrgId });+ await expect(+ prisma.projectMembership.count({ where: { projectId } }),+ ).resolves.toBe(0);+ });++ it("should be a no-op when the project is already in the target organization", async () => {+ const response = await makeAPICall<{+ projectId: string;+ organizationId: string;+ }>(+ "POST",+ `/api/admin/projects/${projectId}/transfer`,+ { targetOrganizationId: sourceOrgId },+ `Bearer ${ADMIN_API_KEY}`,+ );++ expect(response.status).toBe(200);+ expect(response.body).toEqual({+ projectId,+ organizationId: sourceOrgId,+ });+ await expect(+ prisma.projectMembership.count({ where: { projectId } }),+ ).resolves.toBe(1);+ });++ it("should return 401 when no authorization header is provided", async () => {+ const result = await makeAPICall<{ error: string }>(+ "POST",+ `/api/admin/projects/${projectId}/transfer`,+ { targetOrganizationId: targetOrgId },+ );++ expect(result.status).toBe(401);+ await expect(+ prisma.project.findUnique({ where: { id: projectId } }),+ ).resolves.toMatchObject({ orgId: sourceOrgId });+ });+ });+it("should return 405 for non-supported methods", async () => {const result = await makeAPICall<{ error: string }>("PATCH",diff --git a/web/src/ee/features/admin-api/server/projects/transferProject.ts b/web/src/ee/features/admin-api/server/projects/transferProject.tsnew file mode 100644index 0000000000..293ffd24ad--- /dev/null+++ b/web/src/ee/features/admin-api/server/projects/transferProject.ts@@ -0,0 +1,70 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { z } from "zod";+import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";+import { ProjectService } from "@/src/features/projects/server/projectService";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";++const TransferProjectQuery = z.object({ projectId: z.string().min(1) });+const TransferProjectBody = z.object({+ targetOrganizationId: z.string().min(1),+});++/**+ * handleTransferProject moves a project into another organization on behalf of+ * the instance admin. The ADMIN_API_KEY holds authority over every+ * organization, so it stands in for `projects:transfer_org` on both sides.+ */+export async function handleTransferProject(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ const query = TransferProjectQuery.safeParse(req.query);+ if (!query.success) {+ return res.status(400).json({ error: "Invalid project ID" });+ }+ const body = TransferProjectBody.safeParse(req.body);+ if (!body.success) {+ return res.status(400).json({+ error: "Invalid request body",+ details: z.formatError(body.error),+ });+ }+ const { projectId } = query.data;+ const { targetOrganizationId } = body.data;++ const project = await prisma.project.findUnique({+ where: { id: projectId, deletedAt: null },+ select: { orgId: true },+ });+ if (!project) {+ return res.status(404).json({ error: "Project not found" });+ }+ if (project.orgId === targetOrganizationId) {+ return res.status(200).json({ projectId, organizationId: project.orgId });+ }++ const targetOrganization = await prisma.organization.findUnique({+ where: { id: targetOrganizationId },+ select: { id: true },+ });+ if (!targetOrganization) {+ return res.status(404).json({ error: "Target organization not found" });+ }++ await new ProjectService(prisma, new ApiAuthService(prisma, redis)).transfer({+ organizationId: project.orgId,+ targetOrganizationId,+ projectId,+ actor: { apiKeyId: "ADMIN_KEY", orgId: project.orgId, projectId },+ });++ logger.info(+ `Transferred project ${projectId} from organization ${project.orgId} to ${targetOrganizationId} via admin API`,+ );++ return res.status(200).json({+ projectId,+ organizationId: targetOrganizationId,+ });+}diff --git a/web/src/features/projects/server/projectService.ts b/web/src/features/projects/server/projectService.tsindex 32a020eecd..279f5393ce 100644--- a/web/src/features/projects/server/projectService.ts+++ b/web/src/features/projects/server/projectService.ts@@ -1,7 +1,13 @@import { randomUUID } from "crypto";import { ForbiddenError, InternalServerError } from "@langfuse/shared";import type { PrismaClient } from "@langfuse/shared/src/db";-import { ProjectDeleteQueue, QueueJobs } from "@langfuse/shared/src/server";+import {+ DefaultEvalModelService,+ ProjectDeleteQueue,+ QueueJobs,+} from "@langfuse/shared/src/server";+import { transferRoleAssignments } from "@langfuse/shared/rbac/server";+import { reconcileTopicsConnectionsForProject } from "@langfuse/shared/topics/server";import { GatewayConfigService } from "@/src/features/ai-gateway/server/config/gatewayConfigService";import { invalidateGatewayResolveCacheForOrganization } from "@/src/features/ai-gateway/server/resolve/gatewayResolveCache";import {@@ -19,6 +25,14 @@ type DeleteProjectParams = {canManageGateway: boolean;};+type TransferProjectParams = {+ /** The organization the project belongs to before the transfer. */+ organizationId: string;+ targetOrganizationId: string;+ projectId: string;+ actor: AuditLogActor;+};+export class ProjectService {constructor(private readonly prisma: PrismaClient,@@ -53,6 +67,67 @@ export class ProjectService {await this.queueHardDelete(params);}+ /**+ * transfer moves a project into another organization. The project keeps its+ * data and API keys, loses its memberships and user role assignments, and+ * rebinds its default eval model and topics connections to the destination+ * organization. Callers must check `projects:transfer_org` in both+ * organizations.+ */+ async transfer(params: TransferProjectParams) {+ const { organizationId, targetOrganizationId, projectId } = params;++ await auditLog({+ ...params.actor,+ resourceType: "project",+ resourceId: projectId,+ action: "transfer",+ before: { orgId: organizationId },+ after: { orgId: targetOrganizationId },+ });++ await this.prisma.$transaction(async (tx) => {+ await tx.projectMembership.deleteMany({ where: { projectId } });+ await tx.project.update({+ where: { id: projectId, orgId: organizationId },+ data: { orgId: targetOrganizationId },+ });+ // Move the project's api-key assignments to the destination org and+ // drop its user assignments, matching the membership wipe above.+ await transferRoleAssignments(tx, projectId, targetOrganizationId);+ });++ // API keys need to be deleted from cache. Otherwise, they will still be valid.+ // It has to be called after the db is done to prevent new API keys from being cached.+ await this.apiAuthService.invalidateCachedProjectApiKeys(projectId);++ // Both orgs' org-scoped keys bake a projectId set that just changed.+ await this.apiAuthService.invalidateCachedOrgApiKeys(organizationId);+ await this.apiAuthService.invalidateCachedOrgApiKeys(targetOrganizationId);++ // A transfer is a delete for the source org and a create for the+ // destination one. CHB's registry is keyed by (organizationId,+ // projectId), so emitting only one side leaves the source org billed for+ // usage it no longer owns, or the destination org unmetered. Each emit+ // no-ops unless that org is CHB-billed, so a Stripe-to-Stripe transfer+ // sends nothing.+ emitChbProjectEvent({+ type: "LANGFUSE_PROJECT_DELETED",+ orgId: organizationId,+ projectId,+ });+ emitChbProjectEvent({+ type: "LANGFUSE_PROJECT_CREATED",+ orgId: targetOrganizationId,+ projectId,+ });++ await Promise.all([+ DefaultEvalModelService.reconcileConnectionForProject(projectId),+ reconcileTopicsConnectionsForProject(projectId),+ ]);+ }+private async softDeleteAndUnlinkGateway(params: DeleteProjectParams) {const { project, clearedGateway } = await this.prisma.$transaction(async (tx) => {diff --git a/web/src/features/projects/server/projectsRouter.ts b/web/src/features/projects/server/projectsRouter.tsindex 93c85c3ebf..fee58ed113 100644--- a/web/src/features/projects/server/projectsRouter.ts+++ b/web/src/features/projects/server/projectsRouter.ts@@ -18,12 +18,9 @@ import { auditLog } from "@/src/features/audit-logs/auditLog";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import {redis,- DefaultEvalModelService,getEnvironmentsForProject,invalidateCachedOrgApiKeys,} from "@langfuse/shared/src/server";-import { transferRoleAssignments } from "@langfuse/shared/rbac/server";-import { reconcileTopicsConnectionsForProject } from "@langfuse/shared/topics/server";import { StringNoHTMLNonEmpty } from "@langfuse/shared";import { buildAdminOrgContext } from "@/src/features/organizations/server/adminOrgContext";import { emitChbProjectEvent } from "@/src/ee/features/billing/server/chb/chbProjectEvents";@@ -263,67 +260,15 @@ export const projectsRouter = createTRPCRouter({});}- await auditLog({- session: ctx.session,- resourceType: "project",- resourceId: input.projectId,- action: "transfer",- before: { orgId: ctx.session.orgId },- after: { orgId: input.targetOrgId },- });-- await ctx.prisma.$transaction(async (tx) => {- await tx.projectMembership.deleteMany({- where: {- projectId: input.projectId,- },- });- await tx.project.update({- where: {- id: input.projectId,- orgId: ctx.session.orgId,- },- data: {- orgId: input.targetOrgId,- },- });- // Move the project's api-key assignments to the destination org and- // drop its user assignments, matching the membership wipe above.- await transferRoleAssignments(tx, input.projectId, input.targetOrgId);- });-- // API keys need to be deleted from cache. Otherwise, they will still be valid.- // It has to be called after the db is done to prevent new API keys from being cached.- await new ApiAuthService(+ await new ProjectService(ctx.prisma,- redis,- ).invalidateCachedProjectApiKeys(input.projectId);-- // Both orgs' org-scoped keys bake a projectId set that just changed.- await invalidateCachedOrgApiKeys(ctx.session.orgId);- await invalidateCachedOrgApiKeys(input.targetOrgId);-- // A transfer is a delete for the source org and a create for the- // destination one. CHB's registry is keyed by (organizationId,- // projectId), so emitting only one side leaves the source org billed for- // usage it no longer owns, or the destination org unmetered. Each emit- // no-ops unless that org is CHB-billed, so a Stripe-to-Stripe transfer- // sends nothing.- emitChbProjectEvent({- type: "LANGFUSE_PROJECT_DELETED",- orgId: ctx.session.orgId,- projectId: input.projectId,- });- emitChbProjectEvent({- type: "LANGFUSE_PROJECT_CREATED",- orgId: input.targetOrgId,+ new ApiAuthService(ctx.prisma, redis),+ ).transfer({+ organizationId: ctx.session.orgId,+ targetOrganizationId: input.targetOrgId,projectId: input.projectId,+ actor: { session: ctx.session },});-- await Promise.all([- DefaultEvalModelService.reconcileConnectionForProject(input.projectId),- reconcileTopicsConnectionsForProject(input.projectId),- ]);}),environmentFilterOptions: protectedProjectProcedurediff --git a/web/src/pages/api/admin/projects/[projectId]/transfer.ts b/web/src/pages/api/admin/projects/[projectId]/transfer.tsnew file mode 100644index 0000000000..54f664857d--- /dev/null+++ b/web/src/pages/api/admin/projects/[projectId]/transfer.ts@@ -0,0 +1,39 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { logger } from "@langfuse/shared/src/server";+import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";+import { handleTransferProject } from "@/src/ee/features/admin-api/server/projects/transferProject";+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { getSelfHostedInstancePlanServerSide } from "@/src/features/entitlements/server/getPlan";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ try {+ if (req.method !== "POST") {+ res.status(405).json({ error: "Method Not Allowed" });+ return;+ }++ // Verify admin API authentication, only allow on self-hosted (not on Langfuse Cloud)+ if (!AdminApiAuthService.handleAdminAuth(req, res)) {+ return;+ }++ if (+ !hasEntitlementBasedOnPlan({+ plan: getSelfHostedInstancePlanServerSide(),+ entitlement: "admin-api",+ })+ ) {+ return res.status(403).json({+ error: "This feature is not available on your current plan.",+ });+ }++ return await handleTransferProject(req, res);+ } catch (e) {+ logger.error("Failed to transfer project", e);+ res.status(500).json({ error: "Internal server error" });+ }+}