Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

Add cert-manager migration tool

Carlos Monastyrski33dece83ac76
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index c1cb13478a..5687bf07e1 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -86,6 +86,7 @@ import { ActorAuthMethod, ActorType, MfaMethod, TProviderAuthCallback } from "@a
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TCertManagerInstanceServiceFactory } from "@app/services/cert-manager-instance/cert-manager-instance-service";
import { TCertManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";
+import { TCertManagerMigrationServiceFactory } from "@app/services/cert-manager-migration/cert-manager-migration-service";
import { TCertificateServiceFactory } from "@app/services/certificate/certificate-service";
import { TCaAutoRenewalQueueFactory } from "@app/services/certificate-authority/ca-auto-renewal-queue";
import { TCaSigningConfigServiceFactory } from "@app/services/certificate-authority/ca-signing-config/ca-signing-config-service";
@@ -337,6 +338,7 @@ declare module "fastify" {
pkiApplicationEnrollment: TPkiApplicationEnrollmentServiceFactory;
certManagerProjectResolver: TCertManagerProjectResolverFactory;
certManagerInstance: TCertManagerInstanceServiceFactory;
+ certManagerMigration: TCertManagerMigrationServiceFactory;
sshCertificateAuthority: TSshCertificateAuthorityServiceFactory;
sshCertificateTemplate: TSshCertificateTemplateServiceFactory;
sshHost: TSshHostServiceFactory;
diff --git a/backend/src/db/migrations/20260519162000_drop-internal-ca-serial-number-unique.ts b/backend/src/db/migrations/20260519162000_drop-internal-ca-serial-number-unique.ts
new file mode 100644
index 0000000000..31bac8789d
--- /dev/null
+++ b/backend/src/db/migrations/20260519162000_drop-internal-ca-serial-number-unique.ts
@@ -0,0 +1,23 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+const CONSTRAINT_NAME = "internal_certificate_authorities_serialNumber_key";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasTable = await knex.schema.hasTable(TableName.InternalCertificateAuthority);
+ if (!hasTable) return;
+
+ await knex.raw(
+ `ALTER TABLE "${TableName.InternalCertificateAuthority}" DROP CONSTRAINT IF EXISTS "${CONSTRAINT_NAME}"`
+ );
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasTable = await knex.schema.hasTable(TableName.InternalCertificateAuthority);
+ if (!hasTable) return;
+
+ await knex.raw(
+ `ALTER TABLE "${TableName.InternalCertificateAuthority}" ADD CONSTRAINT "${CONSTRAINT_NAME}" UNIQUE ("serialNumber")`
+ );
+}
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 5d458aafef..e65fa57ddd 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -366,6 +366,7 @@ export enum EventType {
UPDATE_CA = "update-certificate-authority",
DELETE_CA = "delete-certificate-authority",
RENEW_CA = "renew-certificate-authority",
+ MIGRATE_CERT_MANAGER_PROJECT = "migrate-cert-manager-project",
GET_CA_CSR = "get-certificate-authority-csr",
GET_CA_CERTS = "get-certificate-authority-certs",
GET_CA_CERT = "get-certificate-authority-cert",
@@ -3030,6 +3031,21 @@ interface RenewCa {
};
}
+interface MigrateCertManagerProject {
+ type: EventType.MIGRATE_CERT_MANAGER_PROJECT;
+ metadata: {
+ sourceProjectId: string;
+ destinationProjectId: string;
+ migratedCertificateAuthorities: number;
+ renamedCertificateAuthorities: { originalName: string; newName: string }[];
+ migratedCertificatePolicies: number;
+ renamedCertificatePolicies: { originalName: string; newName: string }[];
+ migratedCertificateProfiles: number;
+ skippedCertificateProfiles: number;
+ renamedCertificateProfiles: { originalSlug: string; newSlug: string }[];
+ };
+}
+
interface GetCaCsr {
type: EventType.GET_CA_CSR;
metadata: {
@@ -7224,6 +7240,7 @@ export type Event =
| UpdateCa
| DeleteCa
| RenewCa
+ | MigrateCertManagerProject
| GetCaCsr
| GetCaCerts
| GetCaCert
diff --git a/backend/src/server/plugins/inject-cert-manager-project-id.ts b/backend/src/server/plugins/inject-cert-manager-project-id.ts
index 98951dfd2c..93e166cbd7 100644
--- a/backend/src/server/plugins/inject-cert-manager-project-id.ts
+++ b/backend/src/server/plugins/inject-cert-manager-project-id.ts
@@ -1,8 +1,16 @@
import { FastifyPluginAsync } from "fastify";
import fp from "fastify-plugin";
+import RE2 from "re2";
const CERT_MANAGER_PREFIXES = ["/api/v1/cert-manager/", "/api/v1/pki/", "/api/v2/pki/"];
+const COOKIE_PREFIX = "infisical-cm-active-project-";
+
+const certManagerActiveProjectCookieName = (orgId: string) => `${COOKIE_PREFIX}${orgId}`;
+
+const UUID_REGEX = new RE2("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "i");
+const isUuid = (value: string) => UUID_REGEX.test(value);
+
const readProjectIdFromRequest = (req: { query?: unknown; body?: unknown; params?: unknown }): string | null => {
const fromQuery = (req.query as { projectId?: unknown } | undefined)?.projectId;
if (typeof fromQuery === "string" && fromQuery.length > 0) return fromQuery;
@@ -14,6 +22,15 @@ const readProjectIdFromRequest = (req: { query?: unknown; body?: unknown; params
return null;
};
+const readProjectIdFromCookie = (
+ cookies: Record<string, string | undefined> | undefined,
+ orgId: string
+): string | null => {
+ const value = cookies?.[certManagerActiveProjectCookieName(orgId)];
+ if (!value || !isUuid(value)) return null;
+ return value;
+};
+
export const injectCertManagerProjectId: FastifyPluginAsync = fp(async (server) => {
server.decorateRequest("internalCertManagerProjectId", "");
@@ -27,12 +44,22 @@ export const injectCertManagerProjectId: FastifyPluginAsync = fp(async (server)
return;
}
+ if (routePath === "/api/v1/cert-manager/migrate") {
+ return;
+ }
+
const explicit = readProjectIdFromRequest(req);
if (explicit) {
req.internalCertManagerProjectId = explicit;
return;
}
+ const fromCookie = readProjectIdFromCookie(req.cookies, req.permission.orgId);
+ if (fromCookie) {
+ req.internalCertManagerProjectId = fromCookie;
+ return;
+ }
+
req.internalCertManagerProjectId = await server.services.certManagerProjectResolver.resolve(req.permission.orgId);
});
});
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index ca315685f5..464f9bcf34 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -260,6 +260,7 @@ import { tokenDALFactory } from "@app/services/auth-token/auth-token-dal";
import { tokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { certManagerInstanceServiceFactory } from "@app/services/cert-manager-instance/cert-manager-instance-service";
import { certManagerProjectResolverFactory } from "@app/services/cert-manager-instance/cert-manager-project-resolver";
+import { certManagerMigrationServiceFactory } from "@app/services/cert-manager-migration/cert-manager-migration-service";
import { certificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { certificateDALFactory } from "@app/services/certificate/certificate-dal";
import { certificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
@@ -2679,6 +2680,19 @@ export const registerRoutes = async (
licenseService
});
+ const certManagerMigrationService = certManagerMigrationServiceFactory({
+ certificateAuthorityDAL,
+ internalCertificateAuthorityDAL,
+ certificateAuthorityCertDAL,
+ certificateAuthoritySecretDAL,
+ certificateAuthorityCrlDAL,
+ certificatePolicyDAL,
+ certificateProfileDAL,
+ projectDAL,
+ kmsService,
+ permissionService
+ });
+
const pkiSubscriberQueue = pkiSubscriberQueueServiceFactory({
queueService,
cronJob,
@@ -3451,6 +3465,7 @@ export const registerRoutes = async (
pkiApplicationEnrollment: pkiApplicationEnrollmentService,
certManagerProjectResolver,
certManagerInstance: certManagerInstanceService,
+ certManagerMigration: certManagerMigrationService,
certificateAuthorityCrl: certificateAuthorityCrlService,
certificateEst: certificateEstService,
pkiAcme: pkiAcmeService,
diff --git a/backend/src/server/routes/v1/cert-manager-migration-router.ts b/backend/src/server/routes/v1/cert-manager-migration-router.ts
new file mode 100644
index 0000000000..97d1b6f2fa
--- /dev/null
+++ b/backend/src/server/routes/v1/cert-manager-migration-router.ts
@@ -0,0 +1,89 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } from "@app/lib/api-docs";
+import { writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+const MigrationResultSchema = z.object({
+ sourceProjectId: z.string(),
+ destinationProjectId: z.string(),
+ migratedCertificateAuthorities: z.number().int().nonnegative(),
+ renamedCertificateAuthorities: z.array(
+ z.object({
+ originalName: z.string(),
+ newName: z.string()
+ })
+ ),
+ migratedCertificatePolicies: z.number().int().nonnegative(),
+ renamedCertificatePolicies: z.array(
+ z.object({
+ originalName: z.string(),
+ newName: z.string()
+ })
+ ),
+ migratedCertificateProfiles: z.number().int().nonnegative(),
+ skippedCertificateProfiles: z.number().int().nonnegative(),
+ renamedCertificateProfiles: z.array(
+ z.object({
+ originalSlug: z.string(),
+ newSlug: z.string()
+ })
+ )
+});
+
+export const registerCertManagerMigrationRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/migrate",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: true,
+ operationId: "migrateCertManagerProject",
+ tags: [ApiDocsTags.PkiCertificateAuthorities],
+ description:
+ "Duplicate internal certificate authorities, certificate policies, and certificate profiles from one project to another within the same organization. External CAs, certificates, and enrollment configs are not migrated.",
+ body: z.object({
+ sourceProjectId: z.string().trim().uuid(),
+ destinationProjectId: z.string().trim().uuid()
+ }),
+ response: {
+ 200: MigrationResultSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.certManagerMigration.migrateCertManagerProject({
+ sourceProjectId: req.body.sourceProjectId,
+ destinationProjectId: req.body.destinationProjectId,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: result.destinationProjectId,
+ event: {
+ type: EventType.MIGRATE_CERT_MANAGER_PROJECT,
+ metadata: {
+ sourceProjectId: result.sourceProjectId,
+ destinationProjectId: result.destinationProjectId,
+ migratedCertificateAuthorities: result.migratedCertificateAuthorities,
+ renamedCertificateAuthorities: result.renamedCertificateAuthorities,
+ migratedCertificatePolicies: result.migratedCertificatePolicies,
+ renamedCertificatePolicies: result.renamedCertificatePolicies,
+ migratedCertificateProfiles: result.migratedCertificateProfiles,
+ skippedCertificateProfiles: result.skippedCertificateProfiles,
+ renamedCertificateProfiles: result.renamedCertificateProfiles
+ }
+ }
+ });
+
+ return result;
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.ts
index 2e7f98a477..6826a37aac 100644
--- a/backend/src/server/routes/v1/index.ts
+++ b/backend/src/server/routes/v1/index.ts
@@ -15,6 +15,7 @@ import { registerAuthRoutes } from "./auth-router";
import { registerProjectBotRouter } from "./bot-router";
import { registerCertManagerAccessRouter } from "./cert-manager-access-routers";
import { registerCertManagerInstanceRouter } from "./cert-manager-instance-router";
+import { registerCertManagerMigrationRouter } from "./cert-manager-migration-router";
import { registerCaRouter } from "./certificate-authority-router";
import { CERTIFICATE_AUTHORITY_REGISTER_ROUTER_MAP } from "./certificate-authority-routers";
import { registerGeneralCertificateAuthorityRouter } from "./certificate-authority-routers/general-certificate-authority-router";
@@ -204,6 +205,7 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
await pkiRouter.register(registerPkiAlertRouter, { prefix: "/alerts" });
await pkiRouter.register(registerPkiApplicationRouter, { prefix: "/applications" });
await pkiRouter.register(registerCertManagerInstanceRouter);
+ await pkiRouter.register(registerCertManagerMigrationRouter);
await pkiRouter.register(registerSignerRouter, { prefix: "/signers" });
await pkiRouter.register(registerCertificateCleanupRouter, { prefix: "/certificate-cleanup" });
await pkiRouter.register(registerCertificateInventoryViewRouter, { prefix: "/certificate-inventory-views" });
diff --git a/backend/src/services/cert-manager-migration/cert-manager-migration-service.ts b/backend/src/services/cert-manager-migration/cert-manager-migration-service.ts
new file mode 100644
index 0000000000..f7b0b66644
--- /dev/null
+++ b/backend/src/services/cert-manager-migration/cert-manager-migration-service.ts
@@ -0,0 +1,370 @@
+/* eslint-disable no-await-in-loop */
+import { OrganizationActionScope, OrgMembershipRole, ProjectType, TableName } from "@app/db/schemas";
+import { TCertificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { BadRequestError, ForbiddenRequestError, InternalServerError, NotFoundError } from "@app/lib/errors";
+import { alphaNumericNanoId } from "@app/lib/nanoid";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";
+import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";
+import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";
+import { TInternalCertificateAuthorityDALFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-dal";
+import { TCertificatePolicyDALFactory } from "@app/services/certificate-policy/certificate-policy-dal";
+import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
+import { IssuerType } from "@app/services/certificate-profile/certificate-profile-types";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+
+import { TMigrateCertManagerProjectDTO, TMigrateCertManagerProjectResult } from "./cert-manager-migration-types";
+
+type TCertManagerMigrationServiceFactoryDep = {
+ certificateAuthorityDAL: Pick<
+ TCertificateAuthorityDALFactory,
+ "find" | "findWithAssociatedCa" | "create" | "transaction"
+ >;
+ internalCertificateAuthorityDAL: Pick<TInternalCertificateAuthorityDALFactory, "create">;
+ certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "find" | "create">;
+ certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "find" | "create">;
+ certificateAuthorityCrlDAL: Pick<TCertificateAuthorityCrlDALFactory, "findOne" | "create">;
+ certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "find">;
+ certificateProfileDAL: Pick<TCertificateProfileDALFactory, "find">;
+ projectDAL: Pick<TProjectDALFactory, "findById" | "findOne" | "updateById" | "transaction">;
+ kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "decryptWithKmsKey" | "generateKmsKey">;
+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
+};
+
+export type TCertManagerMigrationServiceFactory = ReturnType<typeof certManagerMigrationServiceFactory>;
+
+export const certManagerMigrationServiceFactory = ({
+ certificateAuthorityDAL,
+ internalCertificateAuthorityDAL,
+ certificateAuthorityCertDAL,
+ certificateAuthoritySecretDAL,
+ certificateAuthorityCrlDAL,
+ certificatePolicyDAL,
+ certificateProfileDAL,
+ projectDAL,
+ kmsService,
+ permissionService
+}: TCertManagerMigrationServiceFactoryDep) => {
+ const allocateUniqueName = (desired: string, taken: Set<string>): string => {
+ if (!taken.has(desired)) return desired;
+ let candidate: string;
+ do {
+ candidate = `${desired}-${alphaNumericNanoId(8).toLowerCase()}`;
+ } while (taken.has(candidate));
+ return candidate;
+ };
+
+ // knex auto-stringifies plain objects for jsonb columns, but treats JS arrays as Postgres
+ // arrays — which corrupts jsonb columns whose value happens to be an array (e.g. policy
+ // `subject` / `sans`). Pre-stringifying every jsonb-bound value sidesteps the heuristic.
+ const toJsonbValue = (value: unknown): string | null => {
+ if (value === null || value === undefined) return null;
+ if (typeof value === "string") return value;
+ return JSON.stringify(value);
+ };
+
+ const migrateCertManagerProject = async ({
+ sourceProjectId,
+ destinationProjectId,
+ actor,
+ actorId,
+ actorOrgId,
+ actorAuthMethod
+ }: TMigrateCertManagerProjectDTO): Promise<TMigrateCertManagerProjectResult> => {
+ if (actor !== ActorType.USER && actor !== ActorType.IDENTITY) {
+ throw new BadRequestError({ message: "Invalid actor for cert manager migration" });
+ }
+
+ if (sourceProjectId === destinationProjectId) {
+ throw new BadRequestError({ message: "Source and destination projects must be different" });
+ }
+
+ const { hasRole } = await permissionService.getOrgPermission({
+ actor,
+ actorId,
+ orgId: actorOrgId,
+ actorAuthMethod,
+ actorOrgId,
+ scope: OrganizationActionScope.Any
+ });
+ if (!hasRole(OrgMembershipRole.Admin)) {
+ throw new ForbiddenRequestError({
+ message: "Only organization admins can migrate cert manager entities between projects"
+ });
+ }
+
+ const sourceProject = await projectDAL.findById(sourceProjectId);
+ if (!sourceProject) {
+ throw new NotFoundError({ message: `Source project with ID '${sourceProjectId}' not found` });
+ }
+ const destinationProject = await projectDAL.findById(destinationProjectId);
+ if (!destinationProject) {
+ throw new NotFoundError({ message: `Destination project with ID '${destinationProjectId}' not found` });
+ }
+ if (sourceProject.orgId !== actorOrgId || destinationProject.orgId !== actorOrgId) {
+ throw new ForbiddenRequestError({
+ message: "Both projects must belong to your organization"
+ });
+ }
+ if (
+ sourceProject.type !== ProjectType.CertificateManager ||
+ destinationProject.type !== ProjectType.CertificateManager
+ ) {
+ throw new BadRequestError({
+ message: "Both source and destination must be Certificate Manager projects"
+ });
+ }
+
+ const sourceKmsKeyId = await getProjectKmsCertificateKeyId({
+ projectId: sourceProjectId,
+ projectDAL,
+ kmsService
+ });
+ const destinationKmsKeyId = await getProjectKmsCertificateKeyId({
+ projectId: destinationProjectId,
+ projectDAL,
+ kmsService
+ });
+
+ const sourceDecryptor = await kmsService.decryptWithKmsKey({ kmsId: sourceKmsKeyId });
+ const destinationEncryptor = await kmsService.encryptWithKmsKey({ kmsId: destinationKmsKeyId });
+
+ const reencrypt = async (cipherTextBlob: Buffer): Promise<Buffer> => {
+ const plainText = await sourceDecryptor({ cipherTextBlob });
+ const { cipherTextBlob: encrypted } = await destinationEncryptor({ plainText });
+ return encrypted;
+ };
+
+ return certificateAuthorityDAL.transaction(async (tx) => {
+ const existingDestCAs = await certificateAuthorityDAL.find({ projectId: destinationProjectId }, { tx });
+ const destCaNames = new Set(existingDestCAs.map((ca) => ca.name));
+
+ const existingDestPolicies = await certificatePolicyDAL.find({ projectId: destinationProjectId }, { tx });
+ const destPolicyNames = new Set(existingDestPolicies.map((policy) => policy.name));
+
+ const existingDestProfiles = await certificateProfileDAL.find({ projectId: destinationProjectId }, { tx });
+ const destProfileSlugs = new Set(existingDestProfiles.map((profile) => profile.slug));
+
+ const sourceCAsRaw = await certificateAuthorityDAL.findWithAssociatedCa(
+ { projectId: sourceProjectId },
+ undefined,
+ undefined,
+ tx
+ );
+ const sourceInternalCAs = sourceCAsRaw.filter((ca) => Boolean(ca.internalCa?.id));
+
+ const caIndexById = new Map(sourceInternalCAs.map((ca) => [ca.id, ca]));
+ const visited = new Set<string>();
+ const sortedCAs: typeof sourceInternalCAs = [];
+ const visit = (ca: (typeof sourceInternalCAs)[number]) => {
+ if (visited.has(ca.id)) return;
+ const parentId = ca.internalCa?.parentCaId;
+ if (parentId) {
+ const parent = caIndexById.get(parentId);
+ if (parent) visit(parent);
+ }
+ visited.add(ca.id);
+ sortedCAs.push(ca);
+ };
+ for (const ca of sourceInternalCAs) visit(ca);
+
+ const caIdMap = new Map<string, string>();
+ const caSecretIdMap = new Map<string, string>();
+ const caCertIdMap = new Map<string, string>();
+ const renamedCertificateAuthorities: { originalName: string; newName: string }[] = [];
+
+ for (const sourceCa of sortedCAs) {
+ const newName = allocateUniqueName(sourceCa.name, destCaNames);
+ if (newName !== sourceCa.name) {
+ renamedCertificateAuthorities.push({ originalName: sourceCa.name, newName });
+ }
+ destCaNames.add(newName);
+
+ const newCa = await certificateAuthorityDAL.create(
+ {
+ projectId: destinationProjectId,
+ name: newName,
+ status: sourceCa.status,
+ enableDirectIssuance: sourceCa.enableDirectIssuance
+ },
+ tx
+ );
+ caIdMap.set(sourceCa.id, newCa.id);
+
+ const sourceSecrets = await certificateAuthoritySecretDAL.find({ caId: sourceCa.id }, { tx });
+ for (const sourceSecret of sourceSecrets) {
+ const newSecret = await certificateAuthoritySecretDAL.create(
+ {
+ caId: newCa.id,
+ encryptedPrivateKey: await reencrypt(sourceSecret.encryptedPrivateKey)
+ },
+ tx
+ );
+ caSecretIdMap.set(sourceSecret.id, newSecret.id);
+ }
+
+ const sourceCaCerts = await certificateAuthorityCertDAL.find({ caId: sourceCa.id }, { tx });
+ for (const sourceCaCert of sourceCaCerts) {
+ const newSecretId = caSecretIdMap.get(sourceCaCert.caSecretId);
+ if (!newSecretId) {
+ throw new InternalServerError({
+ message: `CA secret referenced by certificate authority cert '${sourceCaCert.id}' was not migrated`
+ });
+ }
+ const newCaCert = await certificateAuthorityCertDAL.create(
+ {
+ caId: newCa.id,
+ caSecretId: newSecretId,
+ version: sourceCaCert.version,
+ encryptedCertificate: await reencrypt(sourceCaCert.encryptedCertificate),
+ encryptedCertificateChain: await reencrypt(sourceCaCert.encryptedCertificateChain)
+ },
+ tx
+ );
+ caCertIdMap.set(sourceCaCert.id, newCaCert.id);
+ }
+
+ const internalCa = sourceCa.internalCa!;
+ const newActiveCaCertId = internalCa.activeCaCertId
+ ? (caCertIdMap.get(internalCa.activeCaCertId) ?? null)
+ : null;
+ const newParentCaId = internalCa.parentCaId ? (caIdMap.get(internalCa.parentCaId) ?? null) : null;
+
+ await internalCertificateAuthorityDAL.create(
+ {
+ caId: newCa.id,
+ parentCaId: newParentCaId,
+ type: internalCa.type,
+ friendlyName: internalCa.friendlyName,
+ organization: internalCa.organization,
+ ou: internalCa.ou,
+ country: internalCa.country,
+ province: internalCa.province,
+ locality: internalCa.locality,
+ commonName: internalCa.commonName,
+ dn: internalCa.dn,
+ serialNumber: internalCa.serialNumber ?? null,
+ maxPathLength: internalCa.maxPathLength ?? null,
+ keyAlgorithm: internalCa.keyAlgorithm,
+ notBefore: internalCa.notBefore ? new Date(internalCa.notBefore) : null,
+ notAfter: internalCa.notAfter ? new Date(internalCa.notAfter) : null,
+ activeCaCertId: newActiveCaCertId,
+ crlDistributionPointUrls: internalCa.crlDistributionPointUrls ?? []
+ },
+ tx
+ );
+
+ const sourceCrl = await certificateAuthorityCrlDAL.findOne({ caId: sourceCa.id }, tx);
+ if (sourceCrl) {
+ const newCrlSecretId = caSecretIdMap.get(sourceCrl.caSecretId);
+ if (!newCrlSecretId) {
+ throw new InternalServerError({
+ message: `CA secret referenced by CRL '${sourceCrl.id}' was not migrated`
+ });
+ }
+ await certificateAuthorityCrlDAL.create(
+ {
+ caId: newCa.id,
+ caSecretId: newCrlSecretId,
+ encryptedCrl: await reencrypt(sourceCrl.encryptedCrl)
+ },
+ tx
+ );
+ }
+ }
+
+ const sourcePolicies = await certificatePolicyDAL.find({ projectId: sourceProjectId }, { tx });
+ const policyIdMap = new Map<string, string>();
+ const renamedCertificatePolicies: { originalName: string; newName: string }[] = [];
+
+ for (const sourcePolicy of sourcePolicies) {
+ const newName = allocateUniqueName(sourcePolicy.name, destPolicyNames);
+ if (newName !== sourcePolicy.name) {
+ renamedCertificatePolicies.push({ originalName: sourcePolicy.name, newName });
+ }
+ destPolicyNames.add(newName);
+
+ const [insertedPolicy] = await tx(TableName.PkiCertificatePolicy)
+ .insert({
+ projectId: destinationProjectId,
+ name: newName,
+ description: sourcePolicy.description ?? null,
+ subject: toJsonbValue(sourcePolicy.subject),
+ sans: toJsonbValue(sourcePolicy.sans),
+ keyUsages: toJsonbValue(sourcePolicy.keyUsages),
+ extendedKeyUsages: toJsonbValue(sourcePolicy.extendedKeyUsages),
+ algorithms: toJsonbValue(sourcePolicy.algorithms),
+ validity: toJsonbValue(sourcePolicy.validity),
+ basicConstraints: toJsonbValue(sourcePolicy.basicConstraints)
+ })
+ .returning("id");
+ policyIdMap.set(sourcePolicy.id, insertedPolicy.id);
+ }
+
+ const sourceProfiles = await certificateProfileDAL.find({ projectId: sourceProjectId }, { tx });
+ const renamedCertificateProfiles: { originalSlug: string; newSlug: string }[] = [];
+ let migratedCertificateProfiles = 0;
+ let skippedCertificateProfiles = 0;
+
+ for (const sourceProfile of sourceProfiles) {
+ let newCaId: string | null = null;
+ if (sourceProfile.issuerType === IssuerType.SELF_SIGNED) {
+ newCaId = null;
+ } else if (sourceProfile.caId && caIdMap.has(sourceProfile.caId)) {
+ newCaId = caIdMap.get(sourceProfile.caId) ?? null;
+ } else {
+ skippedCertificateProfiles += 1;
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
+ const newPolicyId = policyIdMap.get(sourceProfile.certificatePolicyId);
+ if (!newPolicyId) {
+ skippedCertificateProfiles += 1;
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
+ const newSlug = allocateUniqueName(sourceProfile.slug, destProfileSlugs);
+ if (newSlug !== sourceProfile.slug) {
+ renamedCertificateProfiles.push({ originalSlug: sourceProfile.slug, newSlug });
+ }
+ destProfileSlugs.add(newSlug);
+
+ await tx(TableName.PkiCertificateProfile).insert({
+ projectId: destinationProjectId,
+ caId: newCaId,
+ certificatePolicyId: newPolicyId,
+ slug: newSlug,
+ description: sourceProfile.description ?? null,
+ enrollmentType: sourceProfile.enrollmentType,
+ issuerType: sourceProfile.issuerType,
+ defaults: toJsonbValue(sourceProfile.defaults),
+ externalConfigs: sourceProfile.externalConfigs ?? null,
+ estConfigId: null,
+ apiConfigId: null,
+ acmeConfigId: null,
+ scepConfigId: null
+ });
+ migratedCertificateProfiles += 1;
+ }
+
+ return {
+ sourceProjectId,
+ destinationProjectId,
+ migratedCertificateAuthorities: sortedCAs.length,
+ renamedCertificateAuthorities,
+ migratedCertificatePolicies: sourcePolicies.length,
+ renamedCertificatePolicies,
+ migratedCertificateProfiles,
+ skippedCertificateProfiles,
+ renamedCertificateProfiles
+ };
+ });
+ };
+
+ return { migrateCertManagerProject };
+};
diff --git a/backend/src/services/cert-manager-migration/cert-manager-migration-types.ts b/backend/src/services/cert-manager-migration/cert-manager-migration-types.ts
new file mode 100644
index 0000000000..38c1141166
--- /dev/null
+++ b/backend/src/services/cert-manager-migration/cert-manager-migration-types.ts
@@ -0,0 +1,22 @@
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
+
+export type TMigrateCertManagerProjectDTO = {
+ sourceProjectId: string;
+ destinationProjectId: string;
+ actor: ActorType;
+ actorId: string;
+ actorOrgId: string;
+ actorAuthMethod: ActorAuthMethod;
+};
+
+export type TMigrateCertManagerProjectResult = {
+ sourceProjectId: string;
+ destinationProjectId: string;
+ migratedCertificateAuthorities: number;
+ renamedCertificateAuthorities: { originalName: string; newName: string }[];
+ migratedCertificatePolicies: number;
+ renamedCertificatePolicies: { originalName: string; newName: string }[];
+ migratedCertificateProfiles: number;
+ skippedCertificateProfiles: number;
+ renamedCertificateProfiles: { originalSlug: string; newSlug: string }[];
+};
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 860668396b..257843dfad 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -18,7 +18,7 @@ services:
ports:
- "5432:5432"
volumes:
- - postgres-data:/var/lib/postgresql/data
+ - postgres-data-2:/var/lib/postgresql/data
environment:
POSTGRES_PASSWORD: infisical
POSTGRES_USER: infisical
@@ -231,7 +231,7 @@ services:
profiles: [sso]
volumes:
- postgres-data:
+ postgres-data-2:
driver: local
redis_data:
driver: local
diff --git a/frontend/src/components/projects/CertManagerSelectInstanceModal.tsx b/frontend/src/components/projects/CertManagerSelectInstanceModal.tsx
new file mode 100644
index 0000000000..25c9d69562
--- /dev/null
+++ b/frontend/src/components/projects/CertManagerSelectInstanceModal.tsx
@@ -0,0 +1,95 @@
+import { useEffect, useState } from "react";
+
+import {
+ Badge,
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+
+type Instance = {
+ id: string;
+ name: string;
+ slug: string;
+};
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+ instances: Instance[];
+ orgDefaultProjectId: string | null;
+ onSelect: (projectId: string) => void;
+};
+
+export const CertManagerSelectInstanceModal = ({
+ isOpen,
+ onOpenChange,
+ instances,
+ orgDefaultProjectId,
+ onSelect
+}: Props) => {
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (isOpen) setSelectedId(orgDefaultProjectId);
+ }, [isOpen, orgDefaultProjectId]);
+
+ const handleContinue = () => {
+ if (selectedId) onSelect(selectedId);
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-lg">
+ <DialogHeader className="gap-4">
+ <DialogTitle>Select a Certificate Manager instance</DialogTitle>
+ <DialogDescription>
+ Support for multiple Certificate Manager projects per organization is being deprecated.
+ Migrate your certificate authorities, policies, and profiles into the
+ organization&apos;s default instance, secondary projects remain accessible during the
+ transition period.
+ </DialogDescription>
+ </DialogHeader>
+
+ <Select value={selectedId ?? undefined} onValueChange={setSelectedId}>
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select a project" />
+ </SelectTrigger>
+ <SelectContent className="max-h-[60vh]">
+ {instances.map((instance) => (
+ <SelectItem key={instance.id} value={instance.id}>
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <span className="truncate font-medium">{instance.name}</span>
+ <span className="truncate font-mono text-xs text-accent">{instance.slug}</span>
+ {instance.id === orgDefaultProjectId && (
+ <Badge variant="org" className="shrink-0">
+ Organization default
+ </Badge>
+ )}
+ </div>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button variant="project" isDisabled={!selectedId} onClick={handleContinue}>
+ Continue
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/helpers/certManagerActiveProject.ts b/frontend/src/helpers/certManagerActiveProject.ts
new file mode 100644
index 0000000000..91aef090a0
--- /dev/null
+++ b/frontend/src/helpers/certManagerActiveProject.ts
@@ -0,0 +1,18 @@
+const COOKIE_PREFIX = "infisical-cm-active-project-";
+const COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
+
+const cookieName = (orgId: string) => `${COOKIE_PREFIX}${orgId}`;
+
+export const getCertManagerActiveProjectCookie = (orgId: string): string | null => {
+ if (typeof document === "undefined") return null;
+ const name = cookieName(orgId);
+ const entry = document.cookie.split("; ").find((row) => row.startsWith(`${name}=`));
+ if (!entry) return null;
+ const value = entry.slice(name.length + 1);
+ return value || null;
+};
+
+export const setCertManagerActiveProjectCookie = (orgId: string, projectId: string): void => {
+ if (typeof document === "undefined") return;
+ document.cookie = `${cookieName(orgId)}=${projectId}; path=/; max-age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`;
+};
diff --git a/frontend/src/hooks/api/certManagerInstance/index.ts b/frontend/src/hooks/api/certManagerInstance/index.ts
index f1fc080a85..13b9983a53 100644
--- a/frontend/src/hooks/api/certManagerInstance/index.ts
+++ b/frontend/src/hooks/api/certManagerInstance/index.ts
@@ -78,3 +78,35 @@ export const useSetCertManagerActiveProject = () => {
onSuccess: () => qc.invalidateQueries()
});
};
+
+export type TMigrateCertManagerProjectResult = {
+ sourceProjectId: string;
+ destinationProjectId: string;
+ migratedCertificateAuthorities: number;
+ renamedCertificateAuthorities: { originalName: string; newName: string }[];
+ migratedCertificatePolicies: number;
+ renamedCertificatePolicies: { originalName: string; newName: string }[];
+ migratedCertificateProfiles: number;
+ skippedCertificateProfiles: number;
+ renamedCertificateProfiles: { originalSlug: string; newSlug: string }[];
+};
+
+export const useMigrateCertManagerProject = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({
+ sourceProjectId,
+ destinationProjectId
+ }: {
+ sourceProjectId: string;
+ destinationProjectId: string;
+ }) => {
+ const { data } = await apiRequest.post<TMigrateCertManagerProjectResult>(
+ "/api/v1/cert-manager/migrate",
+ { sourceProjectId, destinationProjectId }
+ );
+ return data;
+ },
+ onSuccess: () => qc.invalidateQueries()
+ });
+};
diff --git a/frontend/src/layouts/PkiManagerLayout/components/CertManagerInstanceBanner.tsx b/frontend/src/layouts/PkiManagerLayout/components/CertManagerInstanceBanner.tsx
index f00a7fc8ab..103cfe6f8f 100644
--- a/frontend/src/layouts/PkiManagerLayout/components/CertManagerInstanceBanner.tsx
+++ b/frontend/src/layouts/PkiManagerLayout/components/CertManagerInstanceBanner.tsx
@@ -17,21 +17,23 @@ export const CertManagerInstanceBanner = () => {
const isViewingActive = activeProject?.id === projectId;
const message = isViewingActive
- ? "Certificate Manager now supports one project per organization. Select the project you want to keep and migrate the rest."
- : `This project is being retired. The active Certificate Manager project is "${activeProject?.name ?? "not set"}".`;
+ ? "Support for multiple Certificate Manager projects per organization is being deprecated. This is the active instance, migrate certificate authorities, policies, and profiles from secondary projects here."
+ : `This Certificate Manager project is scheduled for retirement. The active instance is "${activeProject?.name ?? "not set"}", migrate your certificate authorities, policies, and profiles there to preserve them.`;
return (
- <div className="flex w-full flex-wrap items-center gap-x-2 border-b border-yellow/50 bg-yellow/30 px-4 py-2 text-sm text-yellow-200">
- <FontAwesomeIcon icon={faWarning} className="text-base text-yellow" />
- <span>{message}</span>
- <Link
- to="/organizations/$orgId/settings"
- params={{ orgId: currentOrg.id }}
- search={{ selectedTab: "product-settings" }}
- className="underline underline-offset-2 hover:text-yellow"
- >
- Click here.
- </Link>
+ <div className="flex w-full items-start gap-x-2 border-b border-yellow/50 bg-yellow/30 px-4 py-2 text-sm text-yellow-200">
+ <FontAwesomeIcon icon={faWarning} className="mt-0.5 shrink-0 text-base text-yellow" />
+ <p>
+ {message}{" "}
+ <Link
+ to="/organizations/$orgId/settings"
+ params={{ orgId: currentOrg.id }}
+ search={{ selectedTab: "product-settings" }}
+ className="underline underline-offset-2 hover:text-yellow"
+ >
+ Manage instances.
+ </Link>
+ </p>
</div>
);
};
diff --git a/frontend/src/pages/organization/ProjectsPage/components/ProjectCategoryOverview.tsx b/frontend/src/pages/organization/ProjectsPage/components/ProjectCategoryOverview.tsx
index dc9573fe82..c443b39fb0 100644
--- a/frontend/src/pages/organization/ProjectsPage/components/ProjectCategoryOverview.tsx
+++ b/frontend/src/pages/organization/ProjectsPage/components/ProjectCategoryOverview.tsx
@@ -4,6 +4,7 @@ import { FileKeyIcon, LockIcon, ScanSearchIcon, UsersIcon, VaultIcon } from "luc
import { createNotification } from "@app/components/notifications";
import { CertManagerNotConfiguredModal } from "@app/components/projects/CertManagerNotConfiguredModal";
+import { CertManagerSelectInstanceModal } from "@app/components/projects/CertManagerSelectInstanceModal";
import { RequestProjectAccessModal } from "@app/components/projects/RequestProjectAccessModal";
import { Card, CardContent, CardDescription, CardHeader, Skeleton } from "@app/components/v3";
import { useOrganization, useOrgPermission } from "@app/context";
@@ -11,6 +12,10 @@ import {
OrgPermissionAdminConsoleAction,
OrgPermissionSubjects
} from "@app/context/OrgPermissionContext/types";
+import {
+ getCertManagerActiveProjectCookie,
+ setCertManagerActiveProjectCookie
+} from "@app/helpers/certManagerActiveProject";
import { getProjectDescription, getProjectTitle, projectTypeToUrlSlug } from "@app/helpers/project";
import { useGetOrgProductStats, useGetUserProjects } from "@app/hooks/api";
import { useCertManagerInstanceState } from "@app/hooks/api/certManagerInstance";
@@ -99,21 +104,29 @@ export const ProjectCategoryOverview = () => {
const [isRequestAccessOpen, setIsRequestAccessOpen] = useState(false);
const [isCertManagerSetupOpen, setIsCertManagerSetupOpen] = useState(false);
+ const [isCertManagerPickerOpen, setIsCertManagerPickerOpen] = useState(false);
+ const [pendingCertManagerProjectId, setPendingCertManagerProjectId] = useState<string | null>(
+ null
+ );
+
+ const orgDefaultCertManagerProjectId = certManagerInstance?.activeProjectId ?? null;
+ const cmInstances = useMemo(
+ () => certManagerInstance?.projects ?? [],
+ [certManagerInstance?.projects]
+ );
+
+ const certManagerActiveProjectId = useMemo(() => {
+ const cookieValue = currentOrg?.id ? getCertManagerActiveProjectCookie(currentOrg.id) : null;
+ if (cookieValue && cmInstances.some((p) => p.id === cookieValue)) return cookieValue;
+ return orgDefaultCertManagerProjectId;
+ }, [currentOrg?.id, cmInstances, orgDefaultCertManagerProjectId]);
- const certManagerActiveProjectId = certManagerInstance?.activeProjectId ?? null;
const certManagerActiveProject = useMemo(
() =>
certManagerActiveProjectId
- ? certManagerInstance?.projects.find((p) => p.id === certManagerActiveProjectId)
+ ? cmInstances.find((p) => p.id === certManagerActiveProjectId)
: undefined,
- [certManagerInstance, certManagerActiveProjectId]
- );
- const isMemberOfCertManagerProject = useMemo(
- () =>
- certManagerActiveProjectId
- ? projects.some((p) => p.id === certManagerActiveProjectId)
- : false,
- [projects, certManagerActiveProjectId]
+ [cmInstances, certManagerActiveProjectId]
);
const getStatsForType = (type: ProjectType): ProductStat[] => {
@@ -162,36 +175,53 @@ export const ProjectCategoryOverview = () => {
});
};
+ const enterCertManagerProject = async (projectId: string) => {
+ setPendingCertManagerProjectId(projectId);
+ const isMember = projects.some((p) => p.id === projectId);
+ if (isMember) {
+ navigateToCertManager(projectId);
+ return;
+ }
+ const isOrgAdmin = permission.can(
+ OrgPermissionAdminConsoleAction.AccessAllProjects,
+ OrgPermissionSubjects.AdminConsole
+ );
+ if (isOrgAdmin) {
+ try {
+ await orgAdminAccessProject.mutateAsync({ projectId });
+ navigateToCertManager(projectId);
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text:
+ err instanceof Error ? err.message : "Failed to join the Certificate Manager project."
+ });
+ }
+ } else {
+ setIsRequestAccessOpen(true);
+ }
+ };
+
+ const handleCertManagerInstanceSelect = async (projectId: string) => {
+ if (currentOrg?.id) setCertManagerActiveProjectCookie(currentOrg.id, projectId);
+ setIsCertManagerPickerOpen(false);
+ await enterCertManagerProject(projectId);
+ };
+
const handleTileClick = async (type: ProjectType) => {
const orgId = currentOrg?.id || "";
if (type === ProjectType.CertificateManager) {
- if (!certManagerActiveProjectId) {
+ if (cmInstances.length === 0) {
setIsCertManagerSetupOpen(true);
return;
}
- if (isMemberOfCertManagerProject) {
- navigateToCertManager(certManagerActiveProjectId);
+ if (cmInstances.length > 1) {
+ setIsCertManagerPickerOpen(true);
return;
}
- const isOrgAdmin = permission.can(
- OrgPermissionAdminConsoleAction.AccessAllProjects,
- OrgPermissionSubjects.AdminConsole
- );
- if (isOrgAdmin) {
- try {
- await orgAdminAccessProject.mutateAsync({ projectId: certManagerActiveProjectId });
- navigateToCertManager(certManagerActiveProjectId);
- } catch (err) {
- createNotification({
- type: "error",
- text:
- err instanceof Error ? err.message : "Failed to join the Certificate Manager project."
- });
- }
- } else {
- setIsRequestAccessOpen(true);
- }
+ const onlyId = cmInstances[0].id;
+ await enterCertManagerProject(onlyId);
return;
}
@@ -224,10 +254,14 @@ export const ProjectCategoryOverview = () => {
);
}
- const requestAccessProject: Project | undefined = certManagerActiveProject
+ const requestAccessTarget =
+ (pendingCertManagerProjectId
+ ? cmInstances.find((p) => p.id === pendingCertManagerProjectId)
+ : undefined) ?? certManagerActiveProject;
+ const requestAccessProject: Project | undefined = requestAccessTarget
? ({
- id: certManagerActiveProject.id,
- name: certManagerActiveProject.name
+ id: requestAccessTarget.id,
+ name: requestAccessTarget.name
} as Project)
: undefined;
@@ -309,6 +343,14 @@ export const ProjectCategoryOverview = () => {
isOpen={isCertManagerSetupOpen}
onOpenChange={setIsCertManagerSetupOpen}
/>
+
+ <CertManagerSelectInstanceModal
+ isOpen={isCertManagerPickerOpen}
+ onOpenChange={setIsCertManagerPickerOpen}
+ instances={cmInstances}
+ orgDefaultProjectId={orgDefaultCertManagerProjectId}
+ onSelect={handleCertManagerInstanceSelect}
+ />
</>
);
};
diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/CertManagerMigrateProjectModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/CertManagerMigrateProjectModal.tsx
new file mode 100644
index 0000000000..af075b8411
--- /dev/null
+++ b/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/CertManagerMigrateProjectModal.tsx
@@ -0,0 +1,253 @@
+import { useEffect, useState } from "react";
+import { CheckCircle2Icon, InfoIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Alert,
+ AlertDescription,
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from "@app/components/v3";
+import { cn } from "@app/components/v3/utils";
+import {
+ TCertManagerLegacyInstance,
+ TMigrateCertManagerProjectResult,
+ useMigrateCertManagerProject
+} from "@app/hooks/api/certManagerInstance";
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+ source: TCertManagerLegacyInstance | null;
+ candidates: TCertManagerLegacyInstance[];
+};
+
+const SummaryRow = ({ label, value, muted }: { label: string; value: number; muted?: boolean }) => (
+ <div
+ className={cn(
+ "flex items-center justify-between rounded-sm border border-border px-3 py-2",
+ muted && "opacity-70"
+ )}
+ >
+ <span className="text-foreground">{label}</span>
+ <span className="font-mono text-sm font-medium">{value}</span>
+ </div>
+);
+
+const RenameList = ({ title, items }: { title: string; items: { from: string; to: string }[] }) => {
+ if (items.length === 0) return null;
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="text-xs font-medium tracking-wide text-accent uppercase">{title}</div>
+ <ul className="flex flex-col gap-1 text-sm">
+ {items.map((item) => (
+ <li
+ key={`${item.from}->${item.to}`}
+ className="flex items-center gap-2 rounded-sm border border-border bg-mineshaft-800/30 px-3 py-1.5 font-mono text-xs"
+ >
+ <span className="text-foreground">{item.from}</span>
+ <span className="text-accent">→</span>
+ <span className="text-foreground">{item.to}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+};
+
+export const CertManagerMigrateProjectModal = ({
+ isOpen,
+ onOpenChange,
+ source,
+ candidates
+}: Props) => {
+ const [destinationId, setDestinationId] = useState<string | null>(null);
+ const [result, setResult] = useState<TMigrateCertManagerProjectResult | null>(null);
+ const migrate = useMigrateCertManagerProject();
+
+ useEffect(() => {
+ if (isOpen) {
+ setDestinationId(null);
+ setResult(null);
+ }
+ }, [isOpen]);
+
+ const availableDestinations = candidates.filter((c) => c.id !== source?.id);
+
+ const handleMigrate = async () => {
+ if (!source || !destinationId) return;
+ try {
+ const res = await migrate.mutateAsync({
+ sourceProjectId: source.id,
+ destinationProjectId: destinationId
+ });
+ setResult(res);
+ createNotification({
+ type: "success",
+ text: `Migrated ${res.migratedCertificateAuthorities} CA(s), ${res.migratedCertificatePolicies} policy(ies), and ${res.migratedCertificateProfiles} profile(s).`
+ });
+ } catch (err) {
+ const detail = err instanceof Error ? err.message : "Failed to migrate project.";
+ createNotification({ type: "error", text: detail });
+ }
+ };
+
+ const destination = destinationId
+ ? availableDestinations.find((c) => c.id === destinationId)
+ : null;
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-lg">
+ {result ? (
+ <>
+ <DialogHeader className="gap-4">
+ <DialogTitle className="flex items-center gap-2">
+ <CheckCircle2Icon className="h-5 w-5 text-success" />
+ Migration complete
+ </DialogTitle>
+ <DialogDescription>
+ {source?.name} was duplicated into{" "}
+ <span className="font-medium text-foreground">
+ {destination?.name ?? "the destination project"}
+ </span>
+ . The source project was not modified.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex max-h-[60vh] flex-col gap-3 overflow-y-auto pr-1 text-sm">
+ <div className="flex flex-col gap-2">
+ <SummaryRow
+ label="Certificate authorities migrated"
+ value={result.migratedCertificateAuthorities}
+ />
+ <SummaryRow
+ label="Certificate policies migrated"
+ value={result.migratedCertificatePolicies}
+ />
+ <SummaryRow
+ label="Certificate profiles migrated"
+ value={result.migratedCertificateProfiles}
+ />
+ {result.skippedCertificateProfiles > 0 && (
+ <SummaryRow
+ label="Certificate profiles skipped (external CA)"
+ value={result.skippedCertificateProfiles}
+ muted
+ />
+ )}
+ </div>
+
+ <RenameList
+ title="Certificate authorities renamed (name conflicts)"
+ items={result.renamedCertificateAuthorities.map((r) => ({
+ from: r.originalName,
+ to: r.newName
+ }))}
+ />
+ <RenameList
+ title="Policies renamed (name conflicts)"
+ items={result.renamedCertificatePolicies.map((r) => ({
+ from: r.originalName,
+ to: r.newName
+ }))}
+ />
+ <RenameList
+ title="Profiles renamed (slug conflicts)"
+ items={result.renamedCertificateProfiles.map((r) => ({
+ from: r.originalSlug,
+ to: r.newSlug
+ }))}
+ />
+ </div>
+
+ <DialogFooter>
+ <Button variant="project" onClick={() => onOpenChange(false)}>
+ Close
+ </Button>
+ </DialogFooter>
+ </>
+ ) : (
+ <>
+ <DialogHeader className="gap-4">
+ <DialogTitle>Migrate Certificate Manager project</DialogTitle>
+ <DialogDescription>
+ Duplicate all internal CAs, certificate policies, and certificate profiles from{" "}
+ <span className="font-medium text-foreground">
+ {source?.name ?? "this project"}
+ </span>{" "}
+ into another Certificate Manager project. The source project is not modified.
+ </DialogDescription>
+ </DialogHeader>
+
+ <Alert variant="info">
+ <InfoIcon />
+ <AlertDescription>
+ External CAs and certificates are not migrated. Profiles using an external CA are
+ skipped.
+ </AlertDescription>
+ </Alert>
+
+ <div className="flex flex-col gap-2">
+ <div className="text-xs font-medium tracking-wide text-accent uppercase">
+ Destination project
+ </div>
+ <div className="flex max-h-[40vh] flex-col gap-1 overflow-y-auto rounded-sm border border-border bg-mineshaft-800/30 p-1">
+ {availableDestinations.length === 0 ? (
+ <div className="px-3 py-4 text-center text-sm text-accent">
+ No other Certificate Manager projects in this organization.
+ </div>
+ ) : (
+ availableDestinations.map((c) => {
+ const isPicked = c.id === destinationId;
+ return (
+ <button
+ key={c.id}
+ type="button"
+ onClick={() => setDestinationId(c.id)}
+ className={cn(
+ "flex w-full items-center justify-between gap-3 rounded-sm border border-transparent px-3 py-2 text-left transition-colors",
+ "hover:border-product-pki/30 hover:bg-product-pki/[0.06]",
+ isPicked && "border-product-pki/40 bg-product-pki/[0.08]"
+ )}
+ >
+ <div className="min-w-0">
+ <div className="truncate text-sm font-medium text-foreground">
+ {c.name}
+ </div>
+ <div className="truncate font-mono text-xs text-accent">{c.slug}</div>
+ </div>
+ {isPicked && (
+ <CheckCircle2Icon className="h-4 w-4 shrink-0 text-product-pki" />
+ )}
+ </button>
+ );
+ })
+ )}
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button
+ variant="project"
+ isPending={migrate.isPending}
+ isDisabled={!destinationId || availableDestinations.length === 0}
+ onClick={handleMigrate}
+ >
+ Migrate
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/OrgCertManagerTab.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/OrgCertManagerTab.tsx
index ae2f913c43..df402c7eaf 100644
--- a/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/OrgCertManagerTab.tsx
+++ b/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/OrgCertManagerTab.tsx
@@ -1,6 +1,13 @@
import { useEffect, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
-import { BoxIcon, MoreHorizontalIcon, StarIcon, Trash2Icon, TriangleAlertIcon } from "lucide-react";
+import {
+ ArrowRightLeftIcon,
+ BoxIcon,
+ MoreHorizontalIcon,
+ StarIcon,
+ Trash2Icon,
+ TriangleAlertIcon
+} from "lucide-react";
import { createNotification } from "@app/components/notifications";
import { DeleteActionModal } from "@app/components/v2";
@@ -43,6 +50,8 @@ import {
} from "@app/hooks/api/certManagerInstance";
import { useDeleteWorkspace } from "@app/hooks/api/projects";
+import { CertManagerMigrateProjectModal } from "./CertManagerMigrateProjectModal";
+
export const OrgCertManagerTab = () => {
const queryClient = useQueryClient();
const { permission } = useOrgPermission();
@@ -61,6 +70,7 @@ export const OrgCertManagerTab = () => {
const [pendingActive, setPendingActive] = useState<TCertManagerLegacyInstance | null>(null);
const [pendingDelete, setPendingDelete] = useState<TCertManagerLegacyInstance | null>(null);
+ const [pendingMigrate, setPendingMigrate] = useState<TCertManagerLegacyInstance | null>(null);
useEffect(() => {
if (pendingDelete && !instances.find((i) => i.id === pendingDelete.id)) {
@@ -69,7 +79,10 @@ export const OrgCertManagerTab = () => {
if (pendingActive && !instances.find((i) => i.id === pendingActive.id)) {
setPendingActive(null);
}
- }, [instances, pendingDelete, pendingActive]);
+ if (pendingMigrate && !instances.find((i) => i.id === pendingMigrate.id)) {
+ setPendingMigrate(null);
+ }
+ }, [instances, pendingDelete, pendingActive, pendingMigrate]);
if (isPending) {
return (
@@ -155,22 +168,33 @@ export const OrgCertManagerTab = () => {
{instance.isActive ? <Badge variant="success">Active</Badge> : null}
</TableCell>
<TableCell>
- {canManage && !instance.isActive ? (
+ {canManage ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<IconButton variant="ghost" size="xs" aria-label={`Manage ${instance.name}`}>
<MoreHorizontalIcon />
</IconButton>
</DropdownMenuTrigger>
- <DropdownMenuContent className="min-w-40" align="end" sideOffset={2}>
- <DropdownMenuItem onClick={() => setPendingActive(instance)}>
- <StarIcon />
- Set as active
- </DropdownMenuItem>
- <DropdownMenuItem variant="danger" onClick={() => setPendingDelete(instance)}>
- <Trash2Icon />
- Delete project
+ <DropdownMenuContent className="min-w-56" align="end" sideOffset={2}>
+ <DropdownMenuItem onClick={() => setPendingMigrate(instance)}>
+ <ArrowRightLeftIcon />
+ Migrate entities
</DropdownMenuItem>
+ {!instance.isActive && (
+ <DropdownMenuItem onClick={() => setPendingActive(instance)}>
+ <StarIcon />
+ Set as active
+ </DropdownMenuItem>
+ )}
+ {!instance.isActive && (
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() => setPendingDelete(instance)}
+ >
+ <Trash2Icon />
+ Delete project
+ </DropdownMenuItem>
+ )}
</DropdownMenuContent>
</DropdownMenu>
) : null}
@@ -227,6 +251,15 @@ export const OrgCertManagerTab = () => {
onDeleteApproved={handleConfirmDelete}
buttonText="Delete project"
/>
+
+ <CertManagerMigrateProjectModal
+ isOpen={Boolean(pendingMigrate)}
+ onOpenChange={(open) => {
+ if (!open) setPendingMigrate(null);
+ }}
+ source={pendingMigrate}
+ candidates={instances}
+ />
</div>
);
};