Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(pki-sync): add GCP Certificate Manager Sync
Carlos Monastyrskiba6bc13adfbc
diff --git a/backend/src/server/routes/v1/app-connection-routers/gcp-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/gcp-connection-router.tsindex 993566cbc4..563410da11 100644--- a/backend/src/server/routes/v1/app-connection-routers/gcp-connection-router.ts+++ b/backend/src/server/routes/v1/app-connection-routers/gcp-connection-router.ts@@ -8,6 +8,7 @@ import {SanitizedGcpConnectionSchema,UpdateGcpConnectionSchema} from "@app/services/app-connection/gcp";+import { GCP_PROJECT_ID_PATTERN } from "@app/services/app-connection/gcp/gcp-connection-constants";import { AuthMode } from "@app/services/auth/auth-type";import { registerAppConnectionEndpoints } from "./app-connection-endpoints";@@ -80,4 +81,109 @@ export const registerGcpConnectionRouter = async (server: FastifyZodProvider) =>return locations;}});+ server.route({+ method: "GET",+ url: `/:connectionId/certificate-manager-projects`,+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "listGcpCertificateManagerProjects",+ params: z.object({+ connectionId: z.string().uuid()+ }),+ response: {+ 200: z.object({ id: z.string(), name: z.string() }).array()+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const { connectionId } = req.params;++ const projects = await server.services.appConnection.gcp.listCertificateManagerProjects(+ connectionId,+ req.permission+ );++ return projects;+ }+ });++ server.route({+ method: "GET",+ url: `/:connectionId/certificate-manager-locations`,+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "listGcpCertificateManagerLocations",+ params: z.object({+ connectionId: z.string().uuid()+ }),+ querystring: z.object({+ gcpProjectId: z+ .string()+ .trim()+ .min(6)+ .max(30)+ .refine((value) => GCP_PROJECT_ID_PATTERN.test(value), { message: "Invalid GCP project ID" })+ }),+ response: {+ 200: z.object({ locationId: z.string(), displayName: z.string() }).array()+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const {+ params: { connectionId },+ query: { gcpProjectId }+ } = req;++ const locations = await server.services.appConnection.gcp.listCertificateManagerLocations(+ { connectionId, gcpProjectId },+ req.permission+ );++ return locations;+ }+ });++ server.route({+ method: "GET",+ url: `/:connectionId/certificate-maps`,+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "listGcpCertificateMaps",+ params: z.object({+ connectionId: z.string().uuid()+ }),+ querystring: z.object({+ gcpProjectId: z+ .string()+ .trim()+ .min(6)+ .max(30)+ .refine((value) => GCP_PROJECT_ID_PATTERN.test(value), { message: "Invalid GCP project ID" })+ }),+ response: {+ 200: z.object({ name: z.string(), description: z.string().optional() }).array()+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const {+ params: { connectionId },+ query: { gcpProjectId }+ } = req;++ const certificateMaps = await server.services.appConnection.gcp.listCertificateMaps(+ { connectionId, gcpProjectId },+ req.permission+ );++ return certificateMaps;+ }+ });};diff --git a/backend/src/server/routes/v1/pki-sync-routers/gcp-certificate-manager-pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/gcp-certificate-manager-pki-sync-router.tsnew file mode 100644index 0000000000..41c3fa5185--- /dev/null+++ b/backend/src/server/routes/v1/pki-sync-routers/gcp-certificate-manager-pki-sync-router.ts@@ -0,0 +1,26 @@+import {+ CreateGcpCertificateManagerPkiSyncSchema,+ GCP_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION,+ GcpCertificateManagerPkiSyncSchema,+ UpdateGcpCertificateManagerPkiSyncSchema+} from "@app/services/pki-sync/gcp-certificate-manager";+import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";++import { registerSyncPkiEndpoints } from "./pki-sync-endpoints";++export const registerGcpCertificateManagerPkiSyncRouter = async (+ server: FastifyZodProvider,+ enableOperationId: boolean = true+) =>+ registerSyncPkiEndpoints({+ destination: PkiSync.GcpCertificateManager,+ server,+ responseSchema: GcpCertificateManagerPkiSyncSchema,+ createSchema: CreateGcpCertificateManagerPkiSyncSchema,+ updateSchema: UpdateGcpCertificateManagerPkiSyncSchema,+ syncOptions: {+ canImportCertificates: GCP_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION.canImportCertificates,+ canRemoveCertificates: GCP_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION.canRemoveCertificates+ },+ enableOperationId+ });diff --git a/backend/src/server/routes/v1/pki-sync-routers/index.ts b/backend/src/server/routes/v1/pki-sync-routers/index.tsindex 58a88a2931..8ba0bc0f15 100644--- a/backend/src/server/routes/v1/pki-sync-routers/index.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/index.ts@@ -7,6 +7,7 @@ import { registerAzureKeyVaultPkiSyncRouter } from "./azure-key-vault-pki-sync-rimport { registerChefPkiSyncRouter } from "./chef-pki-sync-router";import { registerCloudflareCustomCertificatePkiSyncRouter } from "./cloudflare-custom-certificate-pki-sync-router";import { registerF5BigIpPkiSyncRouter } from "./f5-big-ip-pki-sync-router";+import { registerGcpCertificateManagerPkiSyncRouter } from "./gcp-certificate-manager-pki-sync-router";import { registerKempLoadMasterPkiSyncRouter } from "./kemp-loadmaster-pki-sync-router";import { registerLinuxServerPkiSyncRouter } from "./linux-server-pki-sync-router";import { registerNetScalerPkiSyncRouter } from "./netscaler-pki-sync-router";@@ -24,6 +25,7 @@ export const PKI_SYNC_REGISTER_ROUTER_MAP: Record<[PkiSync.AwsSecretsManager]: registerAwsSecretsManagerPkiSyncRouter,[PkiSync.AwsElasticLoadBalancer]: registerAwsElasticLoadBalancerPkiSyncRouter,[PkiSync.Chef]: registerChefPkiSyncRouter,+ [PkiSync.GcpCertificateManager]: registerGcpCertificateManagerPkiSyncRouter,[PkiSync.CloudflareCustomCertificate]: registerCloudflareCustomCertificatePkiSyncRouter,[PkiSync.NetScaler]: registerNetScalerPkiSyncRouter,[PkiSync.F5BigIp]: registerF5BigIpPkiSyncRouter,diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.tsindex ce8a617c3c..a59dc9df73 100644--- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts@@ -78,7 +78,10 @@ export const registerSyncPkiEndpoints = ({handler: async (req) => {const projectId = req.internalCertManagerProjectId;- const pkiSyncs = await server.services.pkiSync.listPkiSyncsByProjectId({ projectId }, req.permission);+ const pkiSyncs = await server.services.pkiSync.listPkiSyncsByProjectId(+ { projectId, destination },+ req.permission+ );await server.services.auditLog.createAuditLog({...req.auditLogInfo,diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.tsindex b815b83412..0e08c20cea 100644--- a/backend/src/services/app-connection/app-connection-fns.ts+++ b/backend/src/services/app-connection/app-connection-fns.ts@@ -319,6 +319,7 @@ const SECRET_SCANNING_APP_CONNECTION_MAP = Object.fromEntries(// scott: ideally this would be derived from a utilized map like the aboveconst PKI_APP_CONNECTIONS = [AppConnection.AWS,+ AppConnection.GCP,AppConnection.Cloudflare,AppConnection.AzureADCS,AppConnection.ADCS,diff --git a/backend/src/services/app-connection/gcp/gcp-connection-constants.ts b/backend/src/services/app-connection/gcp/gcp-connection-constants.tsnew file mode 100644index 0000000000..92d80f25b3--- /dev/null+++ b/backend/src/services/app-connection/gcp/gcp-connection-constants.ts@@ -0,0 +1,5 @@+import RE2 from "re2";++export const GCP_PROJECT_ID_PATTERN = new RE2("^[a-z][a-z0-9-]{4,28}[a-z0-9]$");++export const GCP_GLOBAL_LOCATION = "global";diff --git a/backend/src/services/app-connection/gcp/gcp-connection-fns.ts b/backend/src/services/app-connection/gcp/gcp-connection-fns.tsindex 2454bec65a..6d8bc3b79f 100644--- a/backend/src/services/app-connection/gcp/gcp-connection-fns.ts+++ b/backend/src/services/app-connection/gcp/gcp-connection-fns.ts@@ -1,4 +1,5 @@import { STSClient } from "@aws-sdk/client-sts";+import { AxiosError } from "axios";import { AwsClient, ExternalAccountClient, gaxios, Impersonated, JWT } from "google-auth-library";import { GetAccessTokenResponse } from "google-auth-library/build/src/auth/oauth2client";import RE2 from "re2";@@ -11,9 +12,11 @@ import { getAppConnectionMethodName } from "@app/services/app-connection/app-conimport { IntegrationUrls } from "@app/services/integration-auth/integration-list";import { AppConnection } from "../app-connection-enums";+import { GCP_GLOBAL_LOCATION } from "./gcp-connection-constants";import { GcpConnectionMethod } from "./gcp-connection-enums";import {GCPApp,+ GCPGetCertificateMapsRes,GCPGetProjectLocationsRes,GCPGetProjectsRes,GCPGetServiceRes,@@ -292,3 +295,188 @@ export const validateGcpConnectionCredentials = async (appConnection: TGcpConnecreturn appConnection.credentials;};++type TGoogleApiError = {+ error?: { status?: string; message?: string };+};++const toGcpDiscoveryError = (error: unknown, context: { api: string; gcpProjectId?: string }) => {+ if (!(error instanceof AxiosError)) return error;++ const body = error.response?.data as TGoogleApiError | undefined;+ const message = body?.error?.message ?? error.message;+ const scope = context.gcpProjectId ? `GCP project "${context.gcpProjectId}"` : "your GCP project";++ if (error.response?.status === 403) {+ if (message.includes("has not been used in project") || message.includes("is disabled")) {+ return new BadRequestError({+ message: `The ${context.api} API is not enabled on ${scope}. Enable it in the Google Cloud console and try again.`+ });+ }++ return new BadRequestError({+ message: `The connection's service account does not have access to ${scope} via the ${context.api} API. Grant it the required roles on that project and try again.`+ });+ }++ if (error.response?.status === 404) {+ return new BadRequestError({ message: `${scope} was not found. Verify the project ID.` });+ }++ return new BadRequestError({ message: `${context.api} request failed: ${message}` });+};++const GCP_MAX_PAGES = 10;+const GCP_PAGE_SIZE = 100;+const GCP_SERVICE_CHECK_CONCURRENCY = 10;++const fetchGcpPages = async <TResponse extends { nextPageToken?: string }, TItem>({+ url,+ accessToken,+ pick,+ api,+ gcpProjectId,+ resourceLabel+}: {+ url: string;+ accessToken: string;+ pick: (response: TResponse) => TItem[] | undefined;+ api: string;+ gcpProjectId?: string;+ resourceLabel: string;+}) => {+ const items: TItem[] = [];+ let pageToken: string | undefined;+ let page = 0;++ do {+ const currentPageToken = pageToken;+ let data: TResponse;++ try {+ // eslint-disable-next-line no-await-in-loop+ ({ data } = await request.get<TResponse>(url, {+ params: new URLSearchParams({+ pageSize: String(GCP_PAGE_SIZE),+ ...(currentPageToken ? { pageToken: currentPageToken } : {})+ }),+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Accept-Encoding": "application/json"+ }+ }));+ } catch (error) {+ throw toGcpDiscoveryError(error, { api, gcpProjectId });+ }++ items.push(...(pick(data) ?? []));+ pageToken = data.nextPageToken;+ page += 1;+ } while (pageToken && page < GCP_MAX_PAGES);++ if (pageToken) {+ logger.warn(+ { gcpProjectId, pagesFetched: page, itemsFetched: items.length },+ `Stopped listing ${resourceLabel} after ${GCP_MAX_PAGES} pages; some results were not returned`+ );+ }++ return items;+};++const isGcpServiceEnabled = async (accessToken: string, projectId: string, serviceName: string) => {+ try {+ const { data } = await request.get<GCPGetServiceRes>(+ `${IntegrationUrls.GCP_SERVICE_USAGE_URL}/v1/projects/${projectId}/services/${serviceName}`,+ {+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Accept-Encoding": "application/json"+ }+ }+ );++ return data.state === "ENABLED";+ } catch (error) {+ logger.warn(+ { projectId, serviceName, error: error instanceof Error ? error.message : "Unknown error" },+ "Could not determine whether a GCP service is enabled; treating the project as unavailable"+ );+ return false;+ }+};++export const getGcpCertificateManagerProjects = async (appConnection: TGcpConnection) => {+ const accessToken = await getGcpConnectionAuthToken(appConnection);++ const apps = await fetchGcpPages<GCPGetProjectsRes, GCPApp>({+ url: `${IntegrationUrls.GCP_API_URL}/v1/projects`,+ accessToken,+ pick: (data) => data.projects,+ api: "Cloud Resource Manager",+ resourceLabel: "GCP projects"+ });++ const projects: { id: string; name: string }[] = [];++ for (let i = 0; i < apps.length; i += GCP_SERVICE_CHECK_CONCURRENCY) {+ const batch = apps.slice(i, i + GCP_SERVICE_CHECK_CONCURRENCY);+ // eslint-disable-next-line no-await-in-loop+ const enabled = await Promise.all(+ batch.map((app) =>+ isGcpServiceEnabled(accessToken, app.projectId, IntegrationUrls.GCP_CERTIFICATE_MANAGER_SERVICE_NAME)+ )+ );++ batch.forEach((app, index) => {+ if (enabled[index]) projects.push({ id: app.projectId, name: app.name });+ });+ }++ return projects.sort((a, b) => a.name.localeCompare(b.name));+};++export const getGcpCertificateManagerLocations = async (projectId: string, appConnection: TGcpConnection) => {+ const accessToken = await getGcpConnectionAuthToken(appConnection);++ const locations = await fetchGcpPages<GCPGetProjectLocationsRes, GCPLocation>({+ url: `${IntegrationUrls.GCP_CERTIFICATE_MANAGER_URL}/v1/projects/${projectId}/locations`,+ accessToken,+ pick: (data) => data.locations,+ api: "Certificate Manager",+ gcpProjectId: projectId,+ resourceLabel: "GCP Certificate Manager locations"+ });++ const sorted = locations+ .filter((location) => Boolean(location.locationId))+ .sort((a, b) => a.locationId.localeCompare(b.locationId));++ return [+ ...sorted.filter((location) => location.locationId === GCP_GLOBAL_LOCATION),+ ...sorted.filter((location) => location.locationId !== GCP_GLOBAL_LOCATION)+ ].map((location) => ({+ locationId: location.locationId,+ displayName: location.displayName || location.locationId+ }));+};++export const getGcpCertificateMaps = async (projectId: string, appConnection: TGcpConnection) => {+ const accessToken = await getGcpConnectionAuthToken(appConnection);++ const certificateMaps = await fetchGcpPages<GCPGetCertificateMapsRes, { name: string; description?: string }>({+ url: `${IntegrationUrls.GCP_CERTIFICATE_MANAGER_URL}/v1/projects/${projectId}/locations/${GCP_GLOBAL_LOCATION}/certificateMaps`,+ accessToken,+ pick: (data) => data.certificateMaps,+ api: "Certificate Manager",+ gcpProjectId: projectId,+ resourceLabel: "GCP certificate maps"+ });++ return certificateMaps+ .flatMap((certificateMap) => {+ const name = certificateMap.name.split("/").pop();+ return name ? [{ name, description: certificateMap.description }] : [];+ })+ .sort((a, b) => a.name.localeCompare(b.name));+};diff --git a/backend/src/services/app-connection/gcp/gcp-connection-service.ts b/backend/src/services/app-connection/gcp/gcp-connection-service.tsindex 4f23373021..f28e0cf5e8 100644--- a/backend/src/services/app-connection/gcp/gcp-connection-service.ts+++ b/backend/src/services/app-connection/gcp/gcp-connection-service.ts@@ -2,8 +2,19 @@ import { logger } from "@app/lib/logger";import { OrgServiceActor } from "@app/lib/types";import { AppConnection } from "../app-connection-enums";-import { getGcpSecretManagerProjectLocations, getGcpSecretManagerProjects } from "./gcp-connection-fns";-import { TGcpConnection, TGetGCPProjectLocationsDTO } from "./gcp-connection-types";+import {+ getGcpCertificateManagerLocations,+ getGcpCertificateManagerProjects,+ getGcpCertificateMaps,+ getGcpSecretManagerProjectLocations,+ getGcpSecretManagerProjects+} from "./gcp-connection-fns";+import {+ TGcpConnection,+ TGetGcpCertificateManagerLocationsDTO,+ TGetGcpCertificateMapsDTO,+ TGetGCPProjectLocationsDTO+} from "./gcp-connection-types";type TGetAppConnectionFunc = (app: AppConnection,@@ -40,8 +51,50 @@ export const gcpConnectionService = (getAppConnection: TGetAppConnectionFunc) =>}};+ const listCertificateManagerProjects = async (connectionId: string, actor: OrgServiceActor) => {+ const appConnection = await getAppConnection(AppConnection.GCP, connectionId, actor);++ try {+ return await getGcpCertificateManagerProjects(appConnection);+ } catch (error) {+ logger.error(error, "Error listing GCP Certificate Manager projects");+ throw error;+ }+ };++ const listCertificateManagerLocations = async (+ { connectionId, gcpProjectId }: TGetGcpCertificateManagerLocationsDTO,+ actor: OrgServiceActor+ ) => {+ const appConnection = await getAppConnection(AppConnection.GCP, connectionId, actor);++ try {+ return await getGcpCertificateManagerLocations(gcpProjectId, appConnection);+ } catch (error) {+ logger.error(error, "Error listing GCP Certificate Manager locations");+ throw error;+ }+ };++ const listCertificateMaps = async (+ { connectionId, gcpProjectId }: TGetGcpCertificateMapsDTO,+ actor: OrgServiceActor+ ) => {+ const appConnection = await getAppConnection(AppConnection.GCP, connectionId, actor);++ try {+ return await getGcpCertificateMaps(gcpProjectId, appConnection);+ } catch (error) {+ logger.error(error, "Error listing GCP certificate maps");+ throw error;+ }+ };+return {listSecretManagerProjects,- listSecretManagerProjectLocations+ listSecretManagerProjectLocations,+ listCertificateManagerProjects,+ listCertificateManagerLocations,+ listCertificateMaps};};diff --git a/backend/src/services/app-connection/gcp/gcp-connection-types.ts b/backend/src/services/app-connection/gcp/gcp-connection-types.tsindex 4dc4bd131f..8d6a8ec19c 100644--- a/backend/src/services/app-connection/gcp/gcp-connection-types.ts+++ b/backend/src/services/app-connection/gcp/gcp-connection-types.ts@@ -59,3 +59,23 @@ export type GCPGetServiceRes = {parent: string;state: "ENABLED" | "DISABLED" | "STATE_UNSPECIFIED";};++export type GCPCertificateMap = {+ name: string;+ description?: string;+};++export type GCPGetCertificateMapsRes = {+ certificateMaps?: GCPCertificateMap[];+ nextPageToken?: string;+};++export type TGetGcpCertificateManagerLocationsDTO = {+ connectionId: string;+ gcpProjectId: string;+};++export type TGetGcpCertificateMapsDTO = {+ connectionId: string;+ gcpProjectId: string;+};diff --git a/backend/src/services/certificate-sync/certificate-sync-dal.ts b/backend/src/services/certificate-sync/certificate-sync-dal.tsindex 88cd236309..af37f7ac88 100644--- a/backend/src/services/certificate-sync/certificate-sync-dal.ts+++ b/backend/src/services/certificate-sync/certificate-sync-dal.ts@@ -121,15 +121,6 @@ export const certificateSyncDALFactory = (db: TDbClient) => {}};- const removeAllCertificatesFromSync = async (pkiSyncId: string, tx?: Knex): Promise<number> => {- try {- const deletedCount = await (tx || db)(TableName.CertificateSync).where({ pkiSyncId }).del();- return deletedCount;- } catch (error) {- throw new DatabaseError({ error, name: "RemoveAllCertificatesFromSync" });- }- };-const updateSyncStatus = async (pkiSyncId: string,certificateId: string,@@ -332,7 +323,6 @@ export const certificateSyncDALFactory = (db: TDbClient) => {findExternalIdentifiersInUse,addCertificates,removeCertificates,- removeAllCertificatesFromSync,updateSyncStatus,bulkUpdateSyncStatus,updateSyncMetadata,diff --git a/backend/src/services/integration-auth/integration-list.ts b/backend/src/services/integration-auth/integration-list.tsindex b229229148..164925cf1e 100644--- a/backend/src/services/integration-auth/integration-list.ts+++ b/backend/src/services/integration-auth/integration-list.ts@@ -108,6 +108,8 @@ export enum IntegrationUrls {GCP_SECRET_MANAGER_SERVICE_NAME = "secretmanager.googleapis.com",GCP_SECRET_MANAGER_URL = `https://${GCP_SECRET_MANAGER_SERVICE_NAME}`,+ GCP_CERTIFICATE_MANAGER_SERVICE_NAME = "certificatemanager.googleapis.com",+ GCP_CERTIFICATE_MANAGER_URL = `https://${GCP_CERTIFICATE_MANAGER_SERVICE_NAME}`,GCP_SERVICE_USAGE_URL = "https://serviceusage.googleapis.com",GCP_CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform",diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-auth-fns.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-auth-fns.tsnew file mode 100644index 0000000000..5e3f5876e9--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-auth-fns.ts@@ -0,0 +1,24 @@+import { getGcpConnectionAuthToken } from "@app/services/app-connection/gcp/gcp-connection-fns";+import { TGcpConnectionConfig } from "@app/services/app-connection/gcp/gcp-connection-types";++import { PkiSyncError } from "../pki-sync-errors";+import { TPkiSyncWithCredentials } from "../pki-sync-types";++export const getGcpAccessToken = async (pkiSync: TPkiSyncWithCredentials) => {+ const { connection } = pkiSync;+ const credentials = connection.credentials as { serviceAccountEmail?: string } | undefined;++ if (!credentials?.serviceAccountEmail) {+ throw new PkiSyncError({+ shouldRetry: false,+ message: "The GCP app connection is missing a service account email."+ });+ }++ return getGcpConnectionAuthToken({+ app: connection.app,+ method: connection.method,+ credentials: { serviceAccountEmail: credentials.serviceAccountEmail },+ orgId: connection.orgId+ } as TGcpConnectionConfig);+};diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-client.test.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-client.test.tsnew file mode 100644index 0000000000..16b763f9e6--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-client.test.ts@@ -0,0 +1,140 @@+import { AxiosError, AxiosHeaders } from "axios";++import {+ getGcpErrorStatus,+ getGcpHttpStatus,+ isCertificateInUseError,+ mapGcpError+} from "./gcp-certificate-manager-pki-sync-client";++const googleError = (httpStatus: number, status: string, message: string) => {+ const error = new AxiosError(message);+ error.response = {+ status: httpStatus,+ statusText: status,+ headers: new AxiosHeaders(),+ config: { headers: new AxiosHeaders() },+ data: { error: { code: httpStatus, status, message } }+ };+ return error;+};++const context = { operation: "certificate upload", gcpProjectId: "my-prod-project" };++describe("mapGcpError", () => {+ test("names the missing permission and does not retry", () => {+ const mapped = mapGcpError(googleError(403, "PERMISSION_DENIED", "caller lacks permission"), {+ ...context,+ permission: "certificatemanager.certificates.create"+ });++ expect(mapped.shouldRetry).toBe(false);+ expect(mapped.message).toContain("certificatemanager.certificates.create");+ expect(mapped.message).toContain("my-prod-project");+ expect(mapped.message).toContain("roles/certificatemanager.editor");+ });++ test("detects a disabled Certificate Manager API", () => {+ const mapped = mapGcpError(+ googleError(+ 403,+ "PERMISSION_DENIED",+ "Certificate Manager API has not been used in project 12345 before or it is disabled"+ ),+ context+ );++ expect(mapped.shouldRetry).toBe(false);+ expect(mapped.message).toContain("certificatemanager.googleapis.com");+ });++ test("keeps rate limits retryable", () => {+ const mapped = mapGcpError(googleError(429, "RESOURCE_EXHAUSTED", "quota exceeded"), context);+ expect(mapped.shouldRetry).toBe(true);+ });++ test("passes through Google's message for invalid arguments and does not retry", () => {+ const mapped = mapGcpError(googleError(400, "INVALID_ARGUMENT", "pem_certificate is malformed"), {+ ...context,+ resource: 'certificate "infisical-abc"'+ });++ expect(mapped.shouldRetry).toBe(false);+ expect(mapped.message).toContain("pem_certificate is malformed");+ expect(mapped.message).toContain('certificate "infisical-abc"');+ });++ test("tells the user which knobs to check on a 404", () => {+ const mapped = mapGcpError(googleError(404, "NOT_FOUND", "not found"), context);+ expect(mapped.shouldRetry).toBe(false);+ expect(mapped.message).toContain("project, location and certificate map");+ });++ test("wraps non-HTTP failures without losing the cause", () => {+ const mapped = mapGcpError(new Error("socket hang up"), context);+ expect(mapped.message).toContain("socket hang up");+ });+});++describe("GCP error inspectors", () => {+ test("reads the Google status and HTTP status", () => {+ const error = googleError(409, "ALREADY_EXISTS", "already exists");+ expect(getGcpErrorStatus(error)).toBe("ALREADY_EXISTS");+ expect(getGcpHttpStatus(error)).toBe(409);+ });++ test("returns undefined for non-Axios errors", () => {+ expect(getGcpErrorStatus(new Error("boom"))).toBeUndefined();+ expect(getGcpHttpStatus(new Error("boom"))).toBeUndefined();+ });++ test("recognizes a delete blocked by a certificate map entry", () => {+ expect(+ isCertificateInUseError(+ googleError(400, "FAILED_PRECONDITION", "The certificate is in use by a certificate map entry")+ )+ ).toBe(true);+ expect(isCertificateInUseError(googleError(400, "INVALID_ARGUMENT", "pem_certificate is malformed"))).toBe(false);+ });+});++describe("isCertificateInUseError classification", () => {+ test("treats a precondition failure naming a map entry as in-use", () => {+ expect(+ isCertificateInUseError(+ googleError(400, "FAILED_PRECONDITION", "The certificate is in use by a certificate map entry")+ )+ ).toBe(true);+ });++ test("does not mistake an IAM failure that mentions certificate maps for an in-use conflict", () => {+ expect(+ isCertificateInUseError(+ googleError(403, "PERMISSION_DENIED", "Permission certificatemanager.certmaps.get denied on certificate map")+ )+ ).toBe(false);+ });+});++// pki_syncs.lastSyncMessage is varchar(255); an over-long message makes the queue's status write+// fail, which leaves the sync reporting "running" forever with no error shown to the user.+describe("mapped messages fit the lastSyncMessage column", () => {+ const longGoogleMessage =+ 'certificate "projects/202604160721/locations/global/certificates/infisical-69c59d616e214cf59eff4837efd3b179" does not cover map entry hostname "live.example.com"';++ test.each([+ ["INVALID_ARGUMENT with a long Google message", googleError(400, "INVALID_ARGUMENT", longGoogleMessage)],+ ["PERMISSION_DENIED", googleError(403, "PERMISSION_DENIED", longGoogleMessage)],+ ["NOT_FOUND", googleError(404, "NOT_FOUND", longGoogleMessage)],+ ["unmapped status", googleError(500, "INTERNAL", longGoogleMessage)]+ ])("%s stays within 255 characters", (_label, error) => {+ const mapped = mapGcpError(error, {+ operation: "certificate map entry creation",+ gcpProjectId: "crested-trilogy-457818-q2",+ resource: 'certificate map entry "infisical-3b223ee0-917a-40fa-a6b9-e59e995b1b28"',+ permission: "certificatemanager.certificatemapentries.create"+ });++ expect(mapped.message.length).toBeLessThanOrEqual(255);+ });+});diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-client.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-client.tsnew file mode 100644index 0000000000..8e1565a787--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-client.ts@@ -0,0 +1,432 @@+/* eslint-disable no-await-in-loop */+import { AxiosError } from "axios";++import { request } from "@app/lib/config/request";+import { logger } from "@app/lib/logger";+import { GCP_GLOBAL_LOCATION } from "@app/services/app-connection/gcp/gcp-connection-constants";+import { createConnectionQueue } from "@app/services/connection-queue";+import { IntegrationUrls } from "@app/services/integration-auth/integration-list";++import { PkiSyncError } from "../pki-sync-errors";+import {+ GCP_MAX_LIST_PAGES,+ GCP_OPERATION_POLL_BASE_DELAY_MS,+ GCP_OPERATION_POLL_MAX_DELAY_MS,+ GCP_OPERATION_POLL_TIMEOUT_MS,+ GCP_PRIMARY_MATCHER,+ GCP_RATE_LIMIT_CONFIG,+ GCP_SCOPE_API_VALUES+} from "./gcp-certificate-manager-pki-sync-constants";+import { GcpCertificateManagerScope } from "./gcp-certificate-manager-pki-sync-enums";+import {+ TGcpCertificate,+ TGcpCertificateMapEntry,+ TGcpListCertificateMapEntriesResponse,+ TGcpListCertificatesResponse,+ TGcpOperation+} from "./gcp-certificate-manager-pki-sync-types";++const gcpConnectionQueue = createConnectionQueue(GCP_RATE_LIMIT_CONFIG);++export const { withRateLimitRetry, executeWithConcurrencyLimit } = gcpConnectionQueue;++const { sleep } = gcpConnectionQueue;++const PAGE_SIZE = 100;++const MAX_MESSAGE_LENGTH = 255;++const cap = (message: string) =>+ message.length > MAX_MESSAGE_LENGTH ? `${message.slice(0, MAX_MESSAGE_LENGTH - 3)}...` : message;++type TGoogleErrorBody = {+ error?: {+ code?: number;+ message?: string;+ status?: string;+ };+};++const getGoogleError = (error: unknown) => {+ if (!(error instanceof AxiosError)) return undefined;+ const body = error.response?.data as TGoogleErrorBody | undefined;+ return {+ httpStatus: error.response?.status,+ status: body?.error?.status,+ message: body?.error?.message ?? error.message+ };+};++export const getGcpErrorStatus = (error: unknown) => getGoogleError(error)?.status;++export const getGcpHttpStatus = (error: unknown) => getGoogleError(error)?.httpStatus;++export const mapGcpError = (+ error: unknown,+ context: { operation: string; gcpProjectId: string; resource?: string; permission?: string }+): PkiSyncError => {+ const details = getGoogleError(error);++ if (!details) {+ return new PkiSyncError({+ message: cap(+ `GCP Certificate Manager ${context.operation} failed: ${error instanceof Error ? error.message : String(error)}`+ ),+ cause: error instanceof Error ? error : undefined,+ context+ });+ }++ const { httpStatus, status, message } = details;+ const resourceSuffix = context.resource ? ` for ${context.resource}` : "";++ if (status === "PERMISSION_DENIED" || httpStatus === 403) {+ if (message.includes("has not been used in project") || message.includes("is disabled")) {+ return new PkiSyncError({+ shouldRetry: false,+ message: cap(+ `The Certificate Manager API is not enabled on GCP project "${context.gcpProjectId}". Enable certificatemanager.googleapis.com and try again.`+ ),+ context+ });+ }++ return new PkiSyncError({+ shouldRetry: false,+ message: cap(+ `The app connection's service account is missing the "${context.permission ?? "certificatemanager.certificates.get"}" permission on GCP project "${context.gcpProjectId}". Grant roles/certificatemanager.editor and try again.`+ ),+ context+ });+ }++ if (status === "NOT_FOUND" || httpStatus === 404) {+ return new PkiSyncError({+ shouldRetry: false,+ message: cap(+ `GCP Certificate Manager could not find the requested resource${resourceSuffix} in project "${context.gcpProjectId}". Verify the project, location and certificate map are correct.`+ ),+ context+ });+ }++ if (status === "RESOURCE_EXHAUSTED" || httpStatus === 429 || httpStatus === 503) {+ return new PkiSyncError({+ message: cap(`GCP Certificate Manager rate limited the ${context.operation} request. Infisical will retry.`),+ context+ });+ }++ if (status === "FAILED_PRECONDITION" || status === "INVALID_ARGUMENT" || httpStatus === 400 || httpStatus === 409) {+ return new PkiSyncError({+ shouldRetry: false,+ message: cap(`GCP rejected the ${context.operation}: ${message}${resourceSuffix}`),+ context: { ...context, googleMessage: message }+ });+ }++ return new PkiSyncError({+ message: cap(`GCP Certificate Manager ${context.operation} failed${resourceSuffix}: ${message}`),+ context+ });+};++export const isCertificateInUseError = (error: unknown) => {+ const details = getGoogleError(error);+ if (!details) return false;+ if (details.status !== "FAILED_PRECONDITION" && details.httpStatus !== 400 && details.httpStatus !== 409) {+ return false;+ }++ const message = details.message.toLowerCase();+ return message.includes("in use") || message.includes("still referenced") || message.includes("map entry");+};++export const createGcpCertificateManagerClient = ({+ accessToken,+ gcpProjectId,+ location,+ syncId+}: {+ accessToken: string;+ gcpProjectId: string;+ location: string;+ syncId: string;+}) => {+ const baseUrl = `${IntegrationUrls.GCP_CERTIFICATE_MANAGER_URL}/v1`;+ const locationPath = `${baseUrl}/projects/${gcpProjectId}/locations/${location}`;+ const globalPath = `${baseUrl}/projects/${gcpProjectId}/locations/${GCP_GLOBAL_LOCATION}`;++ const headers = {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json"+ };++ const awaitOperation = async (operation: TGcpOperation, operationLabel: string) => {+ const assertSucceeded = ({ error }: TGcpOperation) => {+ if (!error) return;+ throw new PkiSyncError({+ shouldRetry: false,+ message: `GCP Certificate Manager ${operationLabel} failed: ${error.message ?? "unknown error"}`,+ context: { syncId, operation: operationLabel }+ });+ };++ if (operation.done) {+ assertSucceeded(operation);+ return;+ }++ const deadline = Date.now() + GCP_OPERATION_POLL_TIMEOUT_MS;+ let delay = GCP_OPERATION_POLL_BASE_DELAY_MS;++ while (Date.now() < deadline) {+ await sleep(delay);+ delay = Math.min(delay * 2, GCP_OPERATION_POLL_MAX_DELAY_MS);++ const { data } = await request.get<TGcpOperation>(`${baseUrl}/${operation.name}`, { headers });++ if (data.done) {+ assertSucceeded(data);+ return;+ }+ }++ throw new PkiSyncError({+ message: `GCP Certificate Manager ${operationLabel} did not complete within ${+ GCP_OPERATION_POLL_TIMEOUT_MS / 1000+ }s. Infisical will retry.`,+ context: { syncId, operation: operationLabel }+ });+ };++ const listPaged = async <TResponse, TItem>({+ url,+ operation,+ pick,+ keyBy,+ truncationMessage,+ logContext+ }: {+ url: string;+ operation: string;+ pick: (response: TResponse) => TItem[] | undefined;+ keyBy: (item: TItem) => string;+ truncationMessage: string;+ logContext?: Record<string, string>;+ }) => {+ const items = new Map<string, TItem>();+ let pageToken: string | undefined;+ let page = 0;++ do {+ page += 1;+ const currentPageToken = pageToken;+ const { data } = await withRateLimitRetry(+ () =>+ request.get<TResponse & { nextPageToken?: string }>(url, {+ headers,+ params: { pageSize: PAGE_SIZE, ...(currentPageToken ? { pageToken: currentPageToken } : {}) }+ }),+ { operation, syncId }+ );++ for (const item of pick(data) ?? []) {+ items.set(keyBy(item), item);+ }++ pageToken = data.nextPageToken;+ } while (pageToken && page < GCP_MAX_LIST_PAGES);++ if (pageToken) {+ logger.warn({ syncId, gcpProjectId, pages: page, ...logContext }, truncationMessage);+ }++ return items;+ };++ const listCertificates = async () =>+ listPaged<TGcpListCertificatesResponse, TGcpCertificate>({+ url: `${locationPath}/certificates`,+ operation: "list-certificates",+ pick: (data) => data.certificates,+ keyBy: (certificate) => certificate.name,+ truncationMessage: `Stopped listing GCP certificates after ${GCP_MAX_LIST_PAGES} pages; some certificates were not returned`+ });++ const upsertCertificate = async ({+ certificateId,+ pemCertificate,+ pemPrivateKey,+ labels,+ scope,+ shouldPatch+ }: {+ certificateId: string;+ pemCertificate: string;+ pemPrivateKey: string;+ labels: Record<string, string>;+ scope: GcpCertificateManagerScope;+ shouldPatch: boolean;+ }) => {+ const body = {+ description: "Managed by Infisical",+ labels,+ selfManaged: { pemCertificate, pemPrivateKey }+ };++ const patchCertificate = async () => {+ const { data } = await withRateLimitRetry(+ () =>+ request.patch<TGcpOperation>(`${locationPath}/certificates/${certificateId}`, body, {+ headers,+ params: { updateMask: "self_managed,labels,description" }+ }),+ { operation: "patch-certificate", syncId, identifier: certificateId }+ );+ await awaitOperation(data, `certificate update (${certificateId})`);+ };++ if (shouldPatch) {+ try {+ await patchCertificate();+ return;+ } catch (error) {+ // The certificate was deleted outside Infisical; fall through and recreate it.+ if (getGcpHttpStatus(error) !== 404) throw error;+ }+ }++ try {+ const { data } = await withRateLimitRetry(+ () =>+ request.post<TGcpOperation>(+ `${locationPath}/certificates`,+ { ...body, scope: GCP_SCOPE_API_VALUES[scope] },+ { headers, params: { certificateId } }+ ),+ { operation: "create-certificate", syncId, identifier: certificateId }+ );+ await awaitOperation(data, `certificate creation (${certificateId})`);+ } catch (error) {+ if (getGcpErrorStatus(error) !== "ALREADY_EXISTS" && getGcpHttpStatus(error) !== 409) throw error;+ await patchCertificate();+ }+ };++ const deleteCertificate = async (certificateId: string) => {+ const { data } = await withRateLimitRetry(+ () => request.delete<TGcpOperation>(`${locationPath}/certificates/${certificateId}`, { headers }),+ { operation: "delete-certificate", syncId, identifier: certificateId }+ );+ await awaitOperation(data, `certificate deletion (${certificateId})`);+ };++ const listCertificateMapEntries = async (certificateMap: string) =>+ listPaged<TGcpListCertificateMapEntriesResponse, TGcpCertificateMapEntry>({+ url: `${globalPath}/certificateMaps/${certificateMap}/certificateMapEntries`,+ operation: "list-certificate-map-entries",+ pick: (data) => data.certificateMapEntries,+ keyBy: (entry) => entry.name,+ truncationMessage: `Stopped listing GCP certificate map entries after ${GCP_MAX_LIST_PAGES} pages; some entries were not returned`,+ logContext: { certificateMap }+ });++ const createCertificateMapEntry = async ({+ certificateMap,+ entryId,+ certificateResourceNames,+ hostname,+ labels+ }: {+ certificateMap: string;+ entryId: string;+ certificateResourceNames: string[];+ hostname?: string;+ labels: Record<string, string>;+ }) => {+ const { data } = await withRateLimitRetry(+ () =>+ request.post<TGcpOperation>(+ `${globalPath}/certificateMaps/${certificateMap}/certificateMapEntries`,+ {+ description: "Managed by Infisical",+ labels,+ certificates: certificateResourceNames,+ ...(hostname ? { hostname } : { matcher: GCP_PRIMARY_MATCHER })+ },+ { headers, params: { certificateMapEntryId: entryId } }+ ),+ { operation: "create-certificate-map-entry", syncId, identifier: entryId }+ );+ await awaitOperation(data, `certificate map entry creation (${entryId})`);+ };++ const updateCertificateMapEntryCertificates = async ({+ certificateMap,+ entryId,+ certificateResourceNames,+ labels+ }: {+ certificateMap: string;+ entryId: string;+ certificateResourceNames: string[];+ labels: Record<string, string>;+ }) => {+ const { data } = await withRateLimitRetry(+ () =>+ request.patch<TGcpOperation>(+ `${globalPath}/certificateMaps/${certificateMap}/certificateMapEntries/${entryId}`,+ { labels, certificates: certificateResourceNames },+ { headers, params: { updateMask: "certificates,labels" } }+ ),+ { operation: "patch-certificate-map-entry", syncId, identifier: entryId }+ );+ await awaitOperation(data, `certificate map entry update (${entryId})`);+ };++ const deleteCertificateMapEntry = async ({+ certificateMap,+ entryId+ }: {+ certificateMap: string;+ entryId: string;+ }) => {+ try {+ const { data } = await withRateLimitRetry(+ () =>+ request.delete<TGcpOperation>(+ `${globalPath}/certificateMaps/${certificateMap}/certificateMapEntries/${entryId}`,+ { headers }+ ),+ { operation: "delete-certificate-map-entry", syncId, identifier: entryId }+ );+ await awaitOperation(data, `certificate map entry deletion (${entryId})`);+ } catch (error) {+ if (getGcpHttpStatus(error) === 404) {+ logger.info({ syncId, entryId }, "GCP certificate map entry already absent");+ return;+ }+ throw error;+ }+ };++ const assertCertificateMapExists = async (certificateMap: string) => {+ await withRateLimitRetry(() => request.get(`${globalPath}/certificateMaps/${certificateMap}`, { headers }), {+ operation: "get-certificate-map",+ syncId,+ identifier: certificateMap+ });+ };++ return {+ listCertificates,+ upsertCertificate,+ deleteCertificate,+ listCertificateMapEntries,+ createCertificateMapEntry,+ updateCertificateMapEntryCertificates,+ deleteCertificateMapEntry,+ assertCertificateMapExists+ };+};diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-constants.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-constants.tsnew file mode 100644index 0000000000..c2926d396f--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-constants.ts@@ -0,0 +1,87 @@+import RE2 from "re2";++import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { RateLimitConfig } from "@app/services/connection-queue";+import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";++import { GcpCertificateManagerScope } from "./gcp-certificate-manager-pki-sync-enums";++const GCP_CERTIFICATE_MANAGER_NAME_REGEX_SOURCE = "^[a-z][a-z0-9-]{0,62}$";++export const GCP_CERTIFICATE_MANAGER_NAMING = {+ NAME_PATTERN: new RE2(GCP_CERTIFICATE_MANAGER_NAME_REGEX_SOURCE),+ FORBIDDEN_CHARACTERS: "!@#$%^&*()+=[]{}|\\:;\"'<>,.?/~`_ ",+ MAX_NAME_LENGTH: 63,+ MIN_NAME_LENGTH: 1,+ ALLOWED_CHARACTER_PATTERN: GCP_CERTIFICATE_MANAGER_NAME_REGEX_SOURCE+} as const;++export const GCP_SCOPE_API_VALUES: Record<GcpCertificateManagerScope, string> = {+ [GcpCertificateManagerScope.Default]: "DEFAULT",+ [GcpCertificateManagerScope.EdgeCache]: "EDGE_CACHE",+ [GcpCertificateManagerScope.AllRegions]: "ALL_REGIONS",+ [GcpCertificateManagerScope.ClientAuth]: "CLIENT_AUTH"+};++export const GCP_PRIMARY_MATCHER = "PRIMARY";++export const GCP_MAX_CERTIFICATES_PER_MAP_ENTRY = 4;++export const GCP_NAME_HASH_LENGTH = 8;++export const GCP_MAX_LIST_PAGES = 20;++export const GCP_NAME_LEADING_LETTER_PATTERN = new RE2("^[a-z]");++export const GCP_LOCATION_PATTERN = new RE2("^[a-z0-9-]{1,32}$");++export const GCP_CERTIFICATE_MAP_NAME_PATTERN = new RE2(GCP_CERTIFICATE_MANAGER_NAME_REGEX_SOURCE);++export const GCP_HOSTNAME_PATTERN = new RE2("^(\\*\\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$", "i");++export const GCP_CERTIFICATE_MANAGER_SUPPORTED_KEY_ALGORITHMS = [+ "RSA-2048",+ "RSA-3072",+ "RSA-4096",+ "ECDSA-P256",+ "ECDSA-P384"+] as const;++// GCP allows 64 labels per resource and the sync writes two of its own.+export const GCP_MAX_USER_LABELS = 62;++export const GCP_LABEL_KEY_PATTERN = new RE2("^[a-z][a-z0-9_-]{0,62}$");+export const GCP_LABEL_VALUE_PATTERN = new RE2("^[a-z0-9_-]{0,63}$");++export const GCP_MANAGED_BY_LABEL_KEY = "managed-by";+export const GCP_MANAGED_BY_LABEL_VALUE = "infisical";+export const GCP_CERTIFICATE_ID_LABEL_KEY = "infisical-certificate-id";++export const GCP_RESERVED_LABEL_KEYS = [GCP_MANAGED_BY_LABEL_KEY, GCP_CERTIFICATE_ID_LABEL_KEY] as const;++// Certificate Manager allows 300 write requests per minute per project.+export const GCP_RATE_LIMIT_CONFIG: RateLimitConfig = {+ MAX_CONCURRENT_REQUESTS: 5,+ BASE_DELAY: 1000,+ MAX_DELAY: 30000,+ MAX_RETRIES: 3,+ RATE_LIMIT_STATUS_CODES: [429, 503]+};++export const GCP_OPERATION_POLL_TIMEOUT_MS = 120_000;+export const GCP_OPERATION_POLL_BASE_DELAY_MS = 1000;+export const GCP_OPERATION_POLL_MAX_DELAY_MS = 5000;++export const GCP_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION = {+ name: "GCP Certificate Manager" as const,+ connection: AppConnection.GCP,+ destination: PkiSync.GcpCertificateManager,+ canImportCertificates: false,+ canRemoveCertificates: true,+ canRunPostSyncCommand: false,+ defaultCertificateNameSchema: "infisical-{{certificateId}}",+ forbiddenCharacters: GCP_CERTIFICATE_MANAGER_NAMING.FORBIDDEN_CHARACTERS,+ allowedCharacterPattern: GCP_CERTIFICATE_MANAGER_NAMING.ALLOWED_CHARACTER_PATTERN,+ maxCertificateNameLength: GCP_CERTIFICATE_MANAGER_NAMING.MAX_NAME_LENGTH,+ minCertificateNameLength: GCP_CERTIFICATE_MANAGER_NAMING.MIN_NAME_LENGTH+} as const;diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-enums.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-enums.tsnew file mode 100644index 0000000000..e69e0acde7--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-enums.ts@@ -0,0 +1,6 @@+export enum GcpCertificateManagerScope {+ Default = "default",+ EdgeCache = "edge-cache",+ AllRegions = "all-regions",+ ClientAuth = "client-auth"+}diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-fns.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-fns.tsnew file mode 100644index 0000000000..9b3f80cd93--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-fns.ts@@ -0,0 +1,800 @@+/* eslint-disable no-await-in-loop */+import RE2 from "re2";++import { TCertificateSyncs } from "@app/db/schemas";+import { logger } from "@app/lib/logger";+import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";+import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";+import { CertificateSyncStatus } from "@app/services/certificate-sync/certificate-sync-enums";++import { PkiSyncError } from "../pki-sync-errors";+import { TCertificateMap, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "../pki-sync-types";+import { getGcpAccessToken } from "./gcp-certificate-manager-pki-sync-auth-fns";+import {+ createGcpCertificateManagerClient,+ executeWithConcurrencyLimit,+ isCertificateInUseError,+ mapGcpError+} from "./gcp-certificate-manager-pki-sync-client";+import {+ GCP_CERTIFICATE_ID_LABEL_KEY,+ GCP_MANAGED_BY_LABEL_KEY,+ GCP_MANAGED_BY_LABEL_VALUE,+ GCP_MAX_CERTIFICATES_PER_MAP_ENTRY,+ GCP_PRIMARY_MATCHER+} from "./gcp-certificate-manager-pki-sync-constants";+import { GcpCertificateManagerScope } from "./gcp-certificate-manager-pki-sync-enums";+import { assertKeyAlgorithmSupported } from "./gcp-certificate-manager-pki-sync-key-fns";+import {+ buildGcpCertificateMapEntryResourceName,+ buildGcpCertificateResourceName,+ toGcpCertificateId,+ toGcpCertificateMapEntryId+} from "./gcp-certificate-manager-pki-sync-name-fns";+import {+ TGcpCertificate,+ TGcpCertificateManagerPkiSyncConfig,+ TGcpCertificateManagerPkiSyncOptions,+ TGcpCertificateMapEntry+} from "./gcp-certificate-manager-pki-sync-types";+import { buildGcpTooManyCertificatesMessage } from "./gcp-certificate-manager-pki-sync-update-fns";++type TGcpCertificateManagerPkiSyncFactoryDeps = {+ certificateSyncDAL: Pick<+ TCertificateSyncDALFactory,+ | "removeCertificates"+ | "addCertificates"+ | "findByPkiSyncAndCertificate"+ | "updateById"+ | "findByPkiSyncId"+ | "updateSyncStatus"+ >;+ certificateDAL: Pick<TCertificateDALFactory, "findById">;+};++type TPlannedCertificate = { skipReason: string } | { target: TUploadTarget };++type TUploadTarget = {+ key: string;+ certificateId: string;+ resourceName: string;+ pemCertificate: string;+ pemPrivateKey: string;+ infisicalCertificateId?: string;+ renewedFromCertificateId?: string;+ shouldPatch: boolean;+};++const getConfig = (pkiSync: TPkiSyncWithCredentials) => {+ const config = pkiSync.destinationConfig as TGcpCertificateManagerPkiSyncConfig;++ if (!config?.gcpProjectId || !config?.location) {+ throw new PkiSyncError({+ shouldRetry: false,+ message: "GCP Certificate Manager sync is missing its project or location configuration."+ });+ }++ return config;+};++const DASH_REGEX = new RE2("-", "g");++const ENTRY_RESOURCE_NAME_REGEX = new RE2("/certificateMaps/([^/]+)/certificateMapEntries/([^/]+)$");++const buildLabels = (userLabels: TGcpCertificateManagerPkiSyncOptions["labels"], infisicalCertificateId?: string) => ({+ ...Object.fromEntries((userLabels ?? []).map(({ key, value }) => [key, value])),+ [GCP_MANAGED_BY_LABEL_KEY]: GCP_MANAGED_BY_LABEL_VALUE,+ ...(infisicalCertificateId ? { [GCP_CERTIFICATE_ID_LABEL_KEY]: infisicalCertificateId.replace(DASH_REGEX, "") } : {})+});++const isInfisicalManaged = (labels?: Record<string, string>) =>+ labels?.[GCP_MANAGED_BY_LABEL_KEY] === GCP_MANAGED_BY_LABEL_VALUE;++// GCP expects the leaf certificate first, followed by any intermediates. The root is already stripped+// upstream when includeRootCa is disabled.+const buildPemChain = (cert: string, certificateChain?: string) => {+ const leaf = cert.trim();+ const chain = certificateChain?.trim();+ return chain ? `${leaf}\n${chain}` : leaf;+};++export const gcpCertificateManagerPkiSyncFactory = ({+ certificateSyncDAL,+ certificateDAL+}: TGcpCertificateManagerPkiSyncFactoryDeps) => {+ const sameCertificateSet = (current: string[] | undefined, desired: string[]) => {+ if ((current?.length ?? 0) !== desired.length) return false;+ const have = new Set(current ?? []);+ return desired.every((name) => have.has(name));+ };++ const $reconcileCertificateMapEntry = async ({+ client,+ pkiSync,+ gcpProjectId,+ certificateMapBinding,+ certificateResourceNames,+ userLabels+ }: {+ client: ReturnType<typeof createGcpCertificateManagerClient>;+ pkiSync: TPkiSyncWithCredentials;+ gcpProjectId: string;+ certificateMapBinding: NonNullable<TGcpCertificateManagerPkiSyncConfig["certificateMapBinding"]>;+ certificateResourceNames: string[];+ userLabels: TGcpCertificateManagerPkiSyncOptions["labels"];+ }) => {+ const { certificateMap, hostname } = certificateMapBinding;+ const entryId = toGcpCertificateMapEntryId(pkiSync.id);+ const entryResourceName = buildGcpCertificateMapEntryResourceName({ gcpProjectId, certificateMap, entryId });++ let entries: Map<string, TGcpCertificateMapEntry>;+ try {+ entries = await client.listCertificateMapEntries(certificateMap);+ } catch (error) {+ throw mapGcpError(error, {+ operation: "certificate map entry list",+ gcpProjectId,+ resource: `certificate map "${certificateMap}"`,+ permission: "certificatemanager.certificatemapentries.list"+ });+ }++ const existingEntry = entries.get(entryResourceName);++ if (existingEntry && !isInfisicalManaged(existingEntry.labels)) {+ throw new PkiSyncError({+ shouldRetry: false,+ message: `Certificate map entry "${entryId}" already exists in map "${certificateMap}" and is not managed by Infisical. Remove or rename it before enabling certificate map binding.`+ });+ }++ if (!existingEntry && !hostname) {+ const conflictingPrimary = Array.from(entries.values()).find((entry) => entry.matcher === GCP_PRIMARY_MATCHER);+ if (conflictingPrimary) {+ throw new PkiSyncError({+ shouldRetry: false,+ message: `Certificate map "${certificateMap}" already has a primary entry ("${conflictingPrimary.name+ .split("/")+ .pop()}"). Set a hostname on this sync instead.`+ });+ }+ }++ try {+ if (!existingEntry) {+ await client.createCertificateMapEntry({+ certificateMap,+ entryId,+ certificateResourceNames,+ hostname,+ labels: buildLabels(userLabels)+ });+ return;+ }++ // hostname and matcher are immutable on a certificate map entry, so a change to either+ // means deleting and recreating rather than patching+ const desiredMatcher = hostname ? undefined : GCP_PRIMARY_MATCHER;+ if (existingEntry.hostname !== hostname || existingEntry.matcher !== desiredMatcher) {+ await client.deleteCertificateMapEntry({ certificateMap, entryId });+ await client.createCertificateMapEntry({+ certificateMap,+ entryId,+ certificateResourceNames,+ hostname,+ labels: buildLabels(userLabels)+ });+ return;+ }++ if (sameCertificateSet(existingEntry.certificates, certificateResourceNames)) return;++ await client.updateCertificateMapEntryCertificates({+ certificateMap,+ entryId,+ certificateResourceNames,+ labels: buildLabels(userLabels)+ });+ } catch (error) {+ if (error instanceof PkiSyncError) throw error;+ throw mapGcpError(error, {+ operation: existingEntry ? "certificate map entry update" : "certificate map entry creation",+ gcpProjectId,+ resource: `certificate map entry "${entryId}"`,+ permission: existingEntry+ ? "certificatemanager.certificatemapentries.update"+ : "certificatemanager.certificatemapentries.create"+ });+ }+ };++ // A certificate cannot be deleted while a certificate map entry references it, so our entry is+ // removed first when it still points at the certificate being deleted.+ const $detachAndDeleteCertificate = async ({+ client,+ pkiSync,+ gcpProjectId,+ certificateMapBinding,+ certificateId,+ resourceName+ }: {+ client: ReturnType<typeof createGcpCertificateManagerClient>;+ pkiSync: TPkiSyncWithCredentials;+ gcpProjectId: string;+ certificateMapBinding?: TGcpCertificateManagerPkiSyncConfig["certificateMapBinding"];+ certificateId: string;+ resourceName: string;+ }) => {+ if (certificateMapBinding) {+ const entryId = toGcpCertificateMapEntryId(pkiSync.id);+ const entryResourceName = buildGcpCertificateMapEntryResourceName({+ gcpProjectId,+ certificateMap: certificateMapBinding.certificateMap,+ entryId+ });++ try {+ const entries = await client.listCertificateMapEntries(certificateMapBinding.certificateMap);+ const entry = entries.get(entryResourceName);++ if (entry && isInfisicalManaged(entry.labels) && entry.certificates?.includes(resourceName)) {+ const remaining = entry.certificates.filter((name) => name !== resourceName);++ if (remaining.length) {+ await client.updateCertificateMapEntryCertificates({+ certificateMap: certificateMapBinding.certificateMap,+ entryId,+ certificateResourceNames: remaining,+ labels: entry.labels ?? {}+ });+ } else {+ await client.deleteCertificateMapEntry({+ certificateMap: certificateMapBinding.certificateMap,+ entryId+ });+ }+ }+ } catch (error) {+ if (error instanceof PkiSyncError) throw error;+ throw mapGcpError(error, {+ operation: "certificate map entry detach",+ gcpProjectId,+ resource: `certificate map entry "${entryId}" in map "${certificateMapBinding.certificateMap}"`,+ permission: "certificatemanager.certificatemapentries.update"+ });+ }+ }++ try {+ await client.deleteCertificate(certificateId);+ } catch (error) {+ if (error instanceof PkiSyncError) throw error;++ if (isCertificateInUseError(error)) {+ throw new PkiSyncError({+ shouldRetry: false,+ message: `Certificate "${certificateId}" is still referenced by a certificate map entry in GCP project "${gcpProjectId}". Detach it from the certificate map before removing it from this sync.`+ });+ }++ throw mapGcpError(error, {+ operation: "certificate deletion",+ gcpProjectId,+ resource: `certificate "${certificateId}"`,+ permission: "certificatemanager.certificates.delete"+ });+ }+ };++ const $reapOrphanedMapEntries = async ({+ client,+ pkiSync,+ certificates,+ currentCertificateMap+ }: {+ client: ReturnType<typeof createGcpCertificateManagerClient>;+ pkiSync: TPkiSyncWithCredentials;+ certificates: Map<string, TGcpCertificate>;+ currentCertificateMap?: string;+ }) => {+ const entryId = toGcpCertificateMapEntryId(pkiSync.id);+ const orphans = new Map<string, string>();++ certificates.forEach((certificate) => {+ if (!isInfisicalManaged(certificate.labels)) return;+ (certificate.usedBy ?? []).forEach(({ name }) => {+ const match = ENTRY_RESOURCE_NAME_REGEX.exec(name);+ if (!match) return;+ const [, certificateMap, usedEntryId] = match;+ if (usedEntryId !== entryId) return;+ if (certificateMap === currentCertificateMap) return;+ orphans.set(name, certificateMap);+ });+ });++ for (const [name, certificateMap] of orphans) {+ try {+ await client.deleteCertificateMapEntry({ certificateMap, entryId });+ logger.info({ syncId: pkiSync.id, entry: name }, "Removed orphaned GCP certificate map entry");+ } catch (error) {+ logger.warn({ syncId: pkiSync.id, entry: name, error }, "Failed to remove orphaned GCP certificate map entry");+ }+ }+ };++ const $planCertificate = async ({+ certName,+ entry,+ syncRecordsByCertId,+ existingCertificates,+ gcpProjectId,+ location,+ preserveItemOnRenewal+ }: {+ certName: string;+ entry: TCertificateMap[string];+ syncRecordsByCertId: Map<string, TCertificateSyncs>;+ existingCertificates: Map<string, TGcpCertificate>;+ gcpProjectId: string;+ location: string;+ preserveItemOnRenewal: boolean;+ }): Promise<TPlannedCertificate> => {+ const { cert, privateKey, certificateChain, certificateId } = entry;++ const certificate = typeof certificateId === "string" ? await certificateDAL.findById(certificateId) : undefined;+ if (certificate?.renewedByCertificateId) {+ return { skipReason: "Certificate has been renewed and replaced by a newer certificate" };+ }+ const { renewedFromCertificateId } = certificate ?? {};++ if (!cert || !cert.includes("-----BEGIN CERTIFICATE-----")) {+ return { skipReason: "Certificate is missing or not in valid PEM format" };+ }++ if (!privateKey || !privateKey.includes("-----BEGIN")) {+ return { skipReason: "Private key is missing or not in valid PEM format" };+ }++ try {+ assertKeyAlgorithmSupported(cert);+ } catch (error) {+ return { skipReason: error instanceof Error ? error.message : "Unsupported key algorithm" };+ }++ const syncRecordLookupId = renewedFromCertificateId || certificateId;+ const existingSyncRecord =+ typeof syncRecordLookupId === "string" ? syncRecordsByCertId.get(syncRecordLookupId) : undefined;+ const reusableResourceName =+ preserveItemOnRenewal &&+ existingSyncRecord?.externalIdentifier &&+ existingCertificates.has(existingSyncRecord.externalIdentifier)+ ? existingSyncRecord.externalIdentifier+ : undefined;++ const gcpCertificateId = reusableResourceName+ ? (reusableResourceName.split("/").pop() as string)+ : toGcpCertificateId(certName);+ const resourceName = buildGcpCertificateResourceName({ gcpProjectId, location, certificateId: gcpCertificateId });+ const existing = existingCertificates.get(resourceName);++ if (existing && !isInfisicalManaged(existing.labels)) {+ return {+ skipReason: `A certificate named "${gcpCertificateId}" already exists in GCP and is not managed by Infisical. Rename the certificate name schema or remove the existing certificate.`+ };+ }++ return {+ target: {+ key: certName,+ certificateId: gcpCertificateId,+ resourceName,+ pemCertificate: buildPemChain(cert, certificateChain),+ pemPrivateKey: privateKey.trim(),+ infisicalCertificateId: certificateId,+ renewedFromCertificateId: renewedFromCertificateId ?? undefined,+ shouldPatch: Boolean(existing)+ }+ };+ };++ const $planUploads = async ({+ certificateMap,+ syncRecordsByCertId,+ existingCertificates,+ gcpProjectId,+ location,+ preserveItemOnRenewal+ }: {+ certificateMap: TCertificateMap;+ syncRecordsByCertId: Map<string, TCertificateSyncs>;+ existingCertificates: Map<string, TGcpCertificate>;+ gcpProjectId: string;+ location: string;+ preserveItemOnRenewal: boolean;+ }) => {+ const skippedCertificates: Array<{ name: string; reason: string }> = [];+ const uploadTargets: TUploadTarget[] = [];+ const activeResourceNames = new Set<string>();+ const trackedCertificateIds = new Set<string>();++ for (const [certName, entry] of Object.entries(certificateMap)) {+ if (entry.certificateId) trackedCertificateIds.add(entry.certificateId);++ const planned = await $planCertificate({+ certName,+ entry,+ syncRecordsByCertId,+ existingCertificates,+ gcpProjectId,+ location,+ preserveItemOnRenewal+ });++ if ("skipReason" in planned) {+ skippedCertificates.push({ name: certName, reason: planned.skipReason });+ } else {+ activeResourceNames.add(planned.target.resourceName);+ uploadTargets.push(planned.target);+ }+ }++ return { uploadTargets, skippedCertificates, activeResourceNames, trackedCertificateIds };+ };++ const $uploadCertificate = async ({+ client,+ pkiSync,+ target,+ gcpProjectId,+ scope,+ userLabels+ }: {+ client: ReturnType<typeof createGcpCertificateManagerClient>;+ pkiSync: TPkiSyncWithCredentials;+ target: TUploadTarget;+ gcpProjectId: string;+ scope: GcpCertificateManagerScope;+ userLabels: TGcpCertificateManagerPkiSyncOptions["labels"];+ }) => {+ try {+ await client.upsertCertificate({+ certificateId: target.certificateId,+ pemCertificate: target.pemCertificate,+ pemPrivateKey: target.pemPrivateKey,+ labels: buildLabels(userLabels, target.infisicalCertificateId),+ scope,+ shouldPatch: target.shouldPatch+ });+ } catch (error) {+ if (error instanceof PkiSyncError) throw error;+ throw mapGcpError(error, {+ operation: target.shouldPatch ? "certificate update" : "certificate upload",+ gcpProjectId,+ resource: `certificate "${target.certificateId}"`,+ permission: target.shouldPatch+ ? "certificatemanager.certificates.update"+ : "certificatemanager.certificates.create"+ });+ }++ if (!target.infisicalCertificateId) return target;++ const existingCertSync = await certificateSyncDAL.findByPkiSyncAndCertificate(+ pkiSync.id,+ target.infisicalCertificateId+ );++ if (existingCertSync) {+ await certificateSyncDAL.updateById(existingCertSync.id, {+ externalIdentifier: target.resourceName,+ syncStatus: CertificateSyncStatus.Succeeded,+ lastSyncedAt: new Date()+ });+ } else {+ await certificateSyncDAL.addCertificates(pkiSync.id, [+ { certificateId: target.infisicalCertificateId, externalIdentifier: target.resourceName }+ ]);+ }++ if (target.renewedFromCertificateId) {+ await certificateSyncDAL.removeCertificates(pkiSync.id, [target.renewedFromCertificateId]);+ }++ return target;+ };++ const $removeStaleCertificates = async ({+ client,+ pkiSync,+ gcpProjectId,+ certificateMapBinding,+ existingSyncRecords,+ existingCertificates,+ activeResourceNames,+ uploadedCertificateIds,+ trackedCertificateIds+ }: {+ client: ReturnType<typeof createGcpCertificateManagerClient>;+ pkiSync: TPkiSyncWithCredentials;+ gcpProjectId: string;+ certificateMapBinding?: TGcpCertificateManagerPkiSyncConfig["certificateMapBinding"];+ existingSyncRecords: TCertificateSyncs[];+ existingCertificates: Map<string, TGcpCertificate>;+ activeResourceNames: Set<string>;+ uploadedCertificateIds: Set<string>;+ trackedCertificateIds: Set<string>;+ }) => {+ const candidates = existingSyncRecords.flatMap((record) => {+ const { externalIdentifier, certificateId } = record;+ if (!externalIdentifier || !certificateId) return [];+ if (activeResourceNames.has(externalIdentifier) || !existingCertificates.has(externalIdentifier)) return [];+ if (trackedCertificateIds.has(certificateId) && !uploadedCertificateIds.has(certificateId)) return [];++ return [+ {+ certificateId: externalIdentifier.split("/").pop() as string,+ resourceName: externalIdentifier,+ infisicalCertificateId: certificateId,+ keepSyncRecord: uploadedCertificateIds.has(certificateId)+ }+ ];+ });++ let removed = 0;+ const failedRemovals: Array<{ name: string; error: string }> = [];++ for (const candidate of candidates) {+ try {+ await $detachAndDeleteCertificate({+ client,+ pkiSync,+ gcpProjectId,+ certificateMapBinding,+ certificateId: candidate.certificateId,+ resourceName: candidate.resourceName+ });+ if (!candidate.keepSyncRecord) {+ await certificateSyncDAL.removeCertificates(pkiSync.id, [candidate.infisicalCertificateId]);+ }+ removed += 1;+ } catch (error) {+ const message = error instanceof Error ? error.message : "Unknown error";+ failedRemovals.push({ name: candidate.certificateId, error: message });+ await certificateSyncDAL.updateSyncStatus(+ pkiSync.id,+ candidate.infisicalCertificateId,+ CertificateSyncStatus.Failed,+ message+ );+ logger.warn(+ { syncId: pkiSync.id, certificateId: candidate.certificateId, error },+ "Failed to remove certificate from GCP Certificate Manager"+ );+ }+ }++ return { removed, failedRemovals };+ };++ const syncCertificates = async (+ pkiSync: TPkiSyncWithCredentials,+ certificateMap: TCertificateMap+ ): Promise<TPkiSyncSyncResult> => {+ const { gcpProjectId, location, scope, certificateMapBinding } = getConfig(pkiSync);+ const syncOptions = pkiSync.syncOptions as TGcpCertificateManagerPkiSyncOptions | undefined;+ const canRemoveCertificates = syncOptions?.canRemoveCertificates ?? true;+ const userLabels = syncOptions?.labels;++ const accessToken = await getGcpAccessToken(pkiSync);+ const client = createGcpCertificateManagerClient({ accessToken, gcpProjectId, location, syncId: pkiSync.id });++ if (certificateMapBinding) {+ try {+ await client.assertCertificateMapExists(certificateMapBinding.certificateMap);+ } catch (error) {+ throw mapGcpError(error, {+ operation: "certificate map lookup",+ gcpProjectId,+ resource: `certificate map "${certificateMapBinding.certificateMap}"`,+ permission: "certificatemanager.certificatemaps.get"+ });+ }+ }++ let existingCertificates: Map<string, TGcpCertificate>;+ try {+ existingCertificates = await client.listCertificates();+ } catch (error) {+ throw mapGcpError(error, {+ operation: "certificate list",+ gcpProjectId,+ permission: "certificatemanager.certificates.list"+ });+ }++ const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id);+ const syncRecordsByCertId = new Map<string, TCertificateSyncs>();+ existingSyncRecords.forEach((record) => {+ if (record.certificateId) syncRecordsByCertId.set(record.certificateId, record);+ });++ const { uploadTargets, skippedCertificates, activeResourceNames, trackedCertificateIds } = await $planUploads({+ certificateMap,+ syncRecordsByCertId,+ existingCertificates,+ gcpProjectId,+ location,+ preserveItemOnRenewal: syncOptions?.preserveItemOnRenewal ?? true+ });++ if (certificateMapBinding && uploadTargets.length > GCP_MAX_CERTIFICATES_PER_MAP_ENTRY) {+ throw new PkiSyncError({+ shouldRetry: false,+ message: buildGcpTooManyCertificatesMessage(certificateMapBinding.certificateMap, uploadTargets.length)+ });+ }++ const uploadResults = await executeWithConcurrencyLimit(+ uploadTargets,+ (target) => $uploadCertificate({ client, pkiSync, target, gcpProjectId, scope, userLabels }),+ { operation: "upload-certificates", syncId: pkiSync.id }+ );++ const successfulUploads = uploadResults.filter(+ (result): result is PromiseFulfilledResult<TUploadTarget> => result.status === "fulfilled"+ );++ await $reapOrphanedMapEntries({+ client,+ pkiSync,+ certificates: existingCertificates,+ currentCertificateMap: certificateMapBinding?.certificateMap+ });++ let failedMapEntry: string | undefined;+ if (certificateMapBinding && successfulUploads.length) {+ try {+ await $reconcileCertificateMapEntry({+ client,+ pkiSync,+ gcpProjectId,+ certificateMapBinding,+ certificateResourceNames: successfulUploads.map(({ value }) => value.resourceName),+ userLabels+ });+ } catch (error) {+ failedMapEntry = error instanceof Error ? error.message : "Unknown error";+ logger.error(+ { syncId: pkiSync.id, certificateMap: certificateMapBinding.certificateMap, error },+ "Certificates synced to GCP Certificate Manager but the certificate map entry could not be reconciled"+ );+ }+ }++ const { removed, failedRemovals } = canRemoveCertificates+ ? await $removeStaleCertificates({+ client,+ pkiSync,+ gcpProjectId,+ certificateMapBinding,+ existingSyncRecords,+ existingCertificates,+ activeResourceNames,+ trackedCertificateIds,+ uploadedCertificateIds: new Set(+ successfulUploads.map(({ value }) => value.infisicalCertificateId).filter((id): id is string => Boolean(id))+ )+ })+ : { removed: 0, failedRemovals: [] };++ const failedUploads = uploadResults+ .map((result, index) => ({ result, target: uploadTargets[index] }))+ .filter(({ result }) => result.status === "rejected")+ .map(({ result, target }) => ({+ name: target?.key ?? "unknown",+ error:+ (result as PromiseRejectedResult).reason instanceof Error+ ? ((result as PromiseRejectedResult).reason as Error).message+ : "Unknown error"+ }));++ if (failedUploads.length) {+ logger.error(+ { syncId: pkiSync.id, failedUploads },+ "Some certificates failed to sync to GCP Certificate Manager"+ );+ }++ const details: TPkiSyncSyncResult["details"] = {};+ if (skippedCertificates.length) details.skippedCertificates = skippedCertificates;+ if (failedUploads.length) details.failedUploads = failedUploads;+ if (failedRemovals.length) details.failedRemovals = failedRemovals;+ const partialFailureMessage = failedMapEntry+ ? `${successfulUploads.length} certificate(s) reached GCP Certificate Manager, but the certificate map entry could not be updated: ${failedMapEntry}`+ : undefined;++ return {+ uploaded: successfulUploads.length,+ removed,+ failedRemovals: failedRemovals.length,+ skipped: skippedCertificates.length,+ details: Object.keys(details).length ? details : undefined,+ partialFailureMessage+ };+ };++ const removeCertificates = async (+ pkiSync: TPkiSyncWithCredentials,+ certificateNames: string[],+ deps?: { certificateSyncDAL?: TCertificateSyncDALFactory; certificateMap?: TCertificateMap }+ ) => {+ const { gcpProjectId, location, certificateMapBinding } = getConfig(pkiSync);++ const accessToken = await getGcpAccessToken(pkiSync);+ const client = createGcpCertificateManagerClient({ accessToken, gcpProjectId, location, syncId: pkiSync.id });++ const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id);+ const targets = certificateNames.flatMap((certName) => {+ const infisicalCertificateId = deps?.certificateMap?.[certName]?.certificateId;+ if (!infisicalCertificateId) return [];++ const record = existingSyncRecords.find((row) => row.certificateId === infisicalCertificateId);+ if (!record?.externalIdentifier) return [];++ return [+ {+ certificateId: record.externalIdentifier.split("/").pop() as string,+ resourceName: record.externalIdentifier,+ infisicalCertificateId+ }+ ];+ });++ if (!targets.length) {+ return { removed: 0, failed: 0, skipped: certificateNames.length };+ }++ const failures: string[] = [];+ let removed = 0;++ for (const target of targets) {+ try {+ await $detachAndDeleteCertificate({+ client,+ pkiSync,+ gcpProjectId,+ certificateMapBinding,+ certificateId: target.certificateId,+ resourceName: target.resourceName+ });+ await certificateSyncDAL.removeCertificates(pkiSync.id, [target.infisicalCertificateId]);+ removed += 1;+ } catch (error) {+ const message = error instanceof Error ? error.message : "Unknown error";+ failures.push(message);+ await certificateSyncDAL.updateSyncStatus(+ pkiSync.id,+ target.infisicalCertificateId,+ CertificateSyncStatus.Failed,+ message+ );+ }+ }++ if (failures.length) {+ throw new PkiSyncError({+ shouldRetry: false,+ message: `Failed to remove ${failures.length} certificate(s) from GCP Certificate Manager: ${failures.join("; ")}`,+ context: { totalCertificates: targets.length, failedCount: failures.length }+ });+ }++ return { removed, failed: 0, skipped: certificateNames.length - targets.length };+ };++ return {+ syncCertificates,+ removeCertificates+ };+};diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-key-fns.test.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-key-fns.test.tsnew file mode 100644index 0000000000..5b76e56fdb--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-key-fns.test.ts@@ -0,0 +1,98 @@+import { assertKeyAlgorithmSupported, inferCertificateKeyAlgorithm } from "./gcp-certificate-manager-pki-sync-key-fns";++const RSA_2048_CERT = `-----BEGIN CERTIFICATE-----+MIIDFTCCAf2gAwIBAgIUJqWVlfyyxPiEcQqsN6CMBKNWvFkwDQYJKoZIhvcNAQEL+BQAwGjEYMBYGA1UEAwwPYXBwLmV4YW1wbGUuY29tMB4XDTI2MDgxOTIxMDkzMFoX+DTI2MDkxODIxMDkzMFowGjEYMBYGA1UEAwwPYXBwLmV4YW1wbGUuY29tMIIBIjAN+BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApx5fKx1zkfTXI2lzmA5Q16Eyyzer+3E2AjAM2wX2jWuOeirz1OBck+mn63L5DY3KRk9K2euIUPJ/Hb6Ut1BNx6YSAjbOv+erBLh/o5t6PHepwHpzC7yukJ5XJ2uBrnKecG00gBlIQPf8CphvIXZWxzspBQm450+DOVGz179upQ8UMqnT7stH2djCWQNxZCc1lq1nosJg2uHY14wq/i0juhEuMZ9XY8x+KF9Whiyv2eay+0iEwgnocL1gC1gmdZiUzKIV70yojv2rxCbLvYhj67s1rF7MiU43+2s1+dn+l5TcJMVbSYuWOZUMiByuB+V1ZAdYhyYzyiSzwhXNdZIvRkcSYiQIDAQAB+o1MwUTAdBgNVHQ4EFgQU8L4kxs8JOxBd3wf+GiPRxqoS/m0wHwYDVR0jBBgwFoAU+8L4kxs8JOxBd3wf+GiPRxqoS/m0wDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B+AQsFAAOCAQEAMw7POguziKBKm7MBY8em/eqcUWYyeE0Jre4KNgW7vvdMNHO0zszM+xousk3Q7VbW5we1y1hqsotPQMX6+uEa4G7/gcIf5oLwGQ7mJrBOjm6uO9HGY3mQT+2bCZVexVyL6ppzb9jJKu73RG3oTcRjGVmw06rtp0XPnJj8h1ZkEP/6KTvotHLcwp+Nc30Pm6PmxmWtBsI0JVUymdYw0JXbF0MORfEVE+JAXCQh3HDAWdLO5DZkJqmmpkQ+OijGpKXxCp9CWvV0ptE3JCyyCV3OEFsXj6k+Ql5PziBfQNA43pKQZSWg7J6xI8kA+OP27G8QX3t28F89ffBsqe00/AFjzU4vk3Q==+-----END CERTIFICATE-----`;++const RSA_1024_CERT = `-----BEGIN CERTIFICATE-----+MIICEDCCAXmgAwIBAgIUCMdc7dQODzTg4eO3EIXbBEnYRCcwDQYJKoZIhvcNAQEL+BQAwGjEYMBYGA1UEAwwPYXBwLmV4YW1wbGUuY29tMB4XDTI2MDgxOTIxMDkzMFoX+DTI2MDkxODIxMDkzMFowGjEYMBYGA1UEAwwPYXBwLmV4YW1wbGUuY29tMIGfMA0G+CSqGSIb3DQEBAQUAA4GNADCBiQKBgQCdKs/mFgsCf7qDlTFs9pvs1JiUZPW8Pmn/+KP0F20m8q1bA4GXBJ++xMFJisSnANNMC/3jRRpexzGJ+LlFrQutPO309WxgdN4f3+M3dhLiuR/QypNG5bAfICvnGbFwBLa4FGlJmGQv4MmukKqKHjXBOBQnDdJIlEBQW5+tw34d9LdQwIDAQABo1MwUTAdBgNVHQ4EFgQUgf7LGmbFbVGWaBqVaAo8ABLifSQw+HwYDVR0jBBgwFoAUgf7LGmbFbVGWaBqVaAo8ABLifSQwDwYDVR0TAQH/BAUwAwEB+/zANBgkqhkiG9w0BAQsFAAOBgQBX1MziwLqzbI1C1+mgGzhHGO0PeBAtftfrojkH+oVy3AcSy30E5PmaQQsAk4HGeUnxIxyMI3TJmauMDCl9uILlhrlNt4alwnKWIQcGV+zebhQWRSu9GclFNjldAvRmeqo0hZ4c3Y22VPZ3yHIEI24I5c0QUS4ciuSNTJknoJ+BVImGA==+-----END CERTIFICATE-----`;++const ECDSA_P256_CERT = `-----BEGIN CERTIFICATE-----+MIIBiTCCAS+gAwIBAgIUb/Z7lZlhOtDpxdhj7+ByYLgZQ1EwCgYIKoZIzj0EAwIw+GjEYMBYGA1UEAwwPYXBwLmV4YW1wbGUuY29tMB4XDTI2MDgxOTIxMDkzMFoXDTI2+MDkxODIxMDkzMFowGjEYMBYGA1UEAwwPYXBwLmV4YW1wbGUuY29tMFkwEwYHKoZI+zj0CAQYIKoZIzj0DAQcDQgAE78s8M/B3WI+0rglc906+7mRKqoPrmHOZakyddBCt+6N5pHMa0aI0kUTxx+iHHw9NElF2iW/YMRN9lr8rFKMN5MaNTMFEwHQYDVR0OBBYE+FLuXPx/ibq4KFjCMTDkByVf1/IEMMB8GA1UdIwQYMBaAFLuXPx/ibq4KFjCMTDkB+yVf1/IEMMA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDSAAwRQIgEuAZ6u5z+oP9tH3btx4VJbf6fF6x0fwtFbDcIxxS0zYcCIQD0mZaLpZSaMjVPwlamXYIy2Vr5+umvT1jJgK+Vpvos3QA==+-----END CERTIFICATE-----`;++const ECDSA_P521_CERT = `-----BEGIN CERTIFICATE-----+MIICETCCAXKgAwIBAgIUPP8yLJ6x8OaEuuBDjUxxN1xqqgcwCgYIKoZIzj0EAwIw+GjEYMBYGA1UEAwwPYXBwLmV4YW1wbGUuY29tMB4XDTI2MDgxOTIxMDkzMFoXDTI2+MDkxODIxMDkzMFowGjEYMBYGA1UEAwwPYXBwLmV4YW1wbGUuY29tMIGbMBAGByqG+SM49AgEGBSuBBAAjA4GGAAQAEQG8mk84TDwPROcnznOeZude0p9Jlc0vH/Rq1xIB+w/chtYqrWQ0I30bL25KF5ETuG97l9Cjwp7p1iEj1k7sKBIMBA+VBbzHlrLQpU3qh+naAPXf9xZblqvhUagkEoNgPH9/iAX8zDxy1V4L9Roh6ahrwo7JWwEW2sPHTHft8y+EitQ3ACjUzBRMB0GA1UdDgQWBBREAkoPMHA3BaKWE7IyOzNP6MKgHjAfBgNVHSME+GDAWgBREAkoPMHA3BaKWE7IyOzNP6MKgHjAPBgNVHRMBAf8EBTADAQH/MAoGCCqG+SM49BAMCA4GMADCBiAJCATJl67KUY4uBhIFtlrppMybgMZ1FLDtQ+2tDzs7k6MRq+3vh2imbCs0ablJZVZKFaZCpGW7gBl7dE7zOHnQbrkBdIAkIBwWMFuhUhdaItL41l+h8KMgJqNGHYFhbuBda68F7pyBvnAgp1QwJuj7z28Vb5bVZr7fqIJq+LVIGAAC3IE+Qu7EAZo=+-----END CERTIFICATE-----`;++describe("inferCertificateKeyAlgorithm", () => {+ test("reads the RSA modulus length", () => {+ expect(inferCertificateKeyAlgorithm(RSA_2048_CERT)).toBe("RSA-2048");+ expect(inferCertificateKeyAlgorithm(RSA_1024_CERT)).toBe("RSA-1024");+ });++ test("reads the ECDSA curve", () => {+ expect(inferCertificateKeyAlgorithm(ECDSA_P256_CERT)).toBe("ECDSA-P256");+ expect(inferCertificateKeyAlgorithm(ECDSA_P521_CERT)).toBe("ECDSA-P521");+ });++ test("fails with an actionable message on unparseable input", () => {+ expect(() => inferCertificateKeyAlgorithm("not a certificate")).toThrow(+ /Failed to parse certificate to determine its key algorithm/+ );+ });+});++describe("assertKeyAlgorithmSupported", () => {+ test("accepts the algorithms GCP Certificate Manager supports", () => {+ expect(assertKeyAlgorithmSupported(RSA_2048_CERT)).toBe("RSA-2048");+ expect(assertKeyAlgorithmSupported(ECDSA_P256_CERT)).toBe("ECDSA-P256");+ });++ test("rejects RSA keys below 2048 bits before the API sees them", () => {+ expect(() => assertKeyAlgorithmSupported(RSA_1024_CERT)).toThrow(+ /key algorithm "RSA-1024", which GCP Certificate Manager does not support/+ );+ });++ test("rejects ECDSA P-521, which GCP does not accept", () => {+ expect(() => assertKeyAlgorithmSupported(ECDSA_P521_CERT)).toThrow(/ECDSA-P521/);+ });+});diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-key-fns.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-key-fns.tsnew file mode 100644index 0000000000..2a350ddf77--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-key-fns.ts@@ -0,0 +1,44 @@+import * as x509 from "@peculiar/x509";++import { PkiSyncError } from "../pki-sync-errors";+import { GCP_CERTIFICATE_MANAGER_SUPPORTED_KEY_ALGORITHMS } from "./gcp-certificate-manager-pki-sync-constants";++const RSA_ALGORITHM_NAMES = ["RSASSA-PKCS1-v1_5", "RSA-PSS", "RSAES-PKCS1-v1_5"];++export const inferCertificateKeyAlgorithm = (certPem: string): string => {+ try {+ const { algorithm } = new x509.X509Certificate(certPem).publicKey;++ if (RSA_ALGORITHM_NAMES.includes(algorithm.name)) {+ const { modulusLength } = algorithm as { modulusLength?: number };+ return `RSA-${modulusLength ?? "unknown"}`;+ }++ if (algorithm.name === "ECDSA" || algorithm.name === "EC") {+ const { namedCurve } = algorithm as { namedCurve?: string };+ return `ECDSA-${(namedCurve ?? "unknown").replace("P-", "P")}`;+ }++ return algorithm.name;+ } catch (error) {+ throw new PkiSyncError({+ shouldRetry: false,+ message: `Failed to parse certificate to determine its key algorithm: ${+ error instanceof Error ? error.message : String(error)+ }`+ });+ }+};++export const assertKeyAlgorithmSupported = (certPem: string) => {+ const algorithm = inferCertificateKeyAlgorithm(certPem);++ if (!(GCP_CERTIFICATE_MANAGER_SUPPORTED_KEY_ALGORITHMS as readonly string[]).includes(algorithm)) {+ throw new PkiSyncError({+ shouldRetry: false,+ message: `Certificate uses key algorithm "${algorithm}", which GCP Certificate Manager does not support. Supported algorithms: ${GCP_CERTIFICATE_MANAGER_SUPPORTED_KEY_ALGORITHMS.join(", ")}.`+ });+ }++ return algorithm;+};diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-name-fns.test.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-name-fns.test.tsnew file mode 100644index 0000000000..20d3b1a853--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-name-fns.test.ts@@ -0,0 +1,98 @@+import {+ buildGcpCertificateMapEntryResourceName,+ buildGcpCertificateResourceName,+ toGcpCertificateId,+ toGcpCertificateMapEntryId+} from "./gcp-certificate-manager-pki-sync-name-fns";++describe("toGcpCertificateId", () => {+ test("lowercases names the shared compiler leaves in mixed case", () => {+ expect(toGcpCertificateId("Infisical-Web.Example.COM")).toBe("infisical-web-example-com");+ });++ test("normalizes the legacy Infisical-<id> fallback name", () => {+ const hex = "550e8400e29b41d4a716446655440000";+ expect(toGcpCertificateId(`Infisical-${hex}`)).toBe(`infisical-${hex}`);+ });++ test("replaces disallowed characters and collapses the result", () => {+ expect(toGcpCertificateId("infisical_web..example")).toBe("infisical-web-example");+ expect(toGcpCertificateId("infisical/prod cert")).toBe("infisical-prod-cert");+ });++ test("trims leading and trailing hyphens", () => {+ expect(toGcpCertificateId("--infisical-cert--")).toBe("infisical-cert");+ expect(toGcpCertificateId(".infisical.")).toBe("infisical");+ });++ test("truncates to 63 characters", () => {+ expect(toGcpCertificateId("a".repeat(80))).toHaveLength(63);+ });++ test("keeps the leading letter and stays unique when the compiled name is too long", () => {+ const commonName = "a".repeat(58);+ const first = toGcpCertificateId(`infisical-${commonName}-${"1".repeat(32)}`);+ const second = toGcpCertificateId(`infisical-${commonName}-${"2".repeat(32)}`);++ // Two certificates must not collide on one GCP resource, which is what the digest suffix buys.+ expect(first).not.toBe(second);+ expect(first.length).toBeLessThanOrEqual(63);+ expect(second.length).toBeLessThanOrEqual(63);+ // GCP rejects an ID that does not start with a letter, so the schema's prefix has to survive.+ expect(first.startsWith("infisical-")).toBe(true);+ expect(second.startsWith("infisical-")).toBe(true);+ });++ test("resolves a long name to the same ID every time, so re-syncs are idempotent", () => {+ const name = `infisical-${"a".repeat(58)}-${"1".repeat(32)}`;+ expect(toGcpCertificateId(name)).toBe(toGcpCertificateId(name));+ });++ test("refuses a name that would produce an ID GCP rejects", () => {+ // A bare hex certificate ID starts with a digit most of the time; GCP requires a letter.+ expect(() => toGcpCertificateId("3f2a9c1d4e5b6a7c8d9e0f1a2b3c4d5e")).toThrow(/start with a letter/);+ });++ test("leaves an already valid ID untouched", () => {+ expect(toGcpCertificateId("infisical-abc-123")).toBe("infisical-abc-123");+ });++ test("throws when nothing usable survives normalization", () => {+ expect(() => toGcpCertificateId("!!!")).toThrow(/cannot be converted into a GCP Certificate Manager resource ID/);+ expect(() => toGcpCertificateId("")).toThrow();+ });+});++describe("toGcpCertificateMapEntryId", () => {+ test("derives a stable entry ID from the sync so renewals repoint one entry", () => {+ const syncId = "550e8400-e29b-41d4-a716-446655440000";+ expect(toGcpCertificateMapEntryId(syncId)).toBe("infisical-550e8400-e29b-41d4-a716-446655440000");+ expect(toGcpCertificateMapEntryId(syncId)).toBe(toGcpCertificateMapEntryId(syncId));+ });++ test("stays inside GCP's 63 character limit", () => {+ expect(toGcpCertificateMapEntryId("550e8400-e29b-41d4-a716-446655440000").length).toBeLessThanOrEqual(63);+ });+});++describe("resource name builders", () => {+ test("builds a fully qualified certificate name", () => {+ expect(+ buildGcpCertificateResourceName({+ gcpProjectId: "my-prod-project",+ location: "global",+ certificateId: "infisical-abc"+ })+ ).toBe("projects/my-prod-project/locations/global/certificates/infisical-abc");+ });++ test("always builds certificate map entry names under the global location", () => {+ expect(+ buildGcpCertificateMapEntryResourceName({+ gcpProjectId: "my-prod-project",+ certificateMap: "prod-map",+ entryId: "infisical-entry"+ })+ ).toBe("projects/my-prod-project/locations/global/certificateMaps/prod-map/certificateMapEntries/infisical-entry");+ });+});diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-name-fns.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-name-fns.tsnew file mode 100644index 0000000000..a7b28660ed--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-name-fns.ts@@ -0,0 +1,75 @@+import crypto from "node:crypto";++import RE2 from "re2";++import { GCP_GLOBAL_LOCATION } from "@app/services/app-connection/gcp/gcp-connection-constants";++import { PkiSyncError } from "../pki-sync-errors";+import {+ GCP_CERTIFICATE_MANAGER_NAMING,+ GCP_NAME_HASH_LENGTH,+ GCP_NAME_LEADING_LETTER_PATTERN+} from "./gcp-certificate-manager-pki-sync-constants";++const DISALLOWED_CHARS = new RE2("[^a-z0-9-]", "g");+const REPEATED_HYPHENS = new RE2("-{2,}", "g");+const SURROUNDING_HYPHENS = new RE2("^-+|-+$", "g");++const truncateToLimit = (cleaned: string): string => {+ const { MAX_NAME_LENGTH } = GCP_CERTIFICATE_MANAGER_NAMING;+ if (cleaned.length <= MAX_NAME_LENGTH) return cleaned;++ const digest = crypto.createHash("sha256").update(cleaned).digest("hex").slice(0, GCP_NAME_HASH_LENGTH);+ const head = cleaned.slice(0, MAX_NAME_LENGTH - GCP_NAME_HASH_LENGTH - 1).replace(SURROUNDING_HYPHENS, "");++ return `${head}-${digest}`;+};++export const toGcpCertificateId = (name: string): string => {+ const cleaned = name+ .toLowerCase()+ .replace(DISALLOWED_CHARS, "-")+ .replace(REPEATED_HYPHENS, "-")+ .replace(SURROUNDING_HYPHENS, "");++ const normalized = truncateToLimit(cleaned).replace(SURROUNDING_HYPHENS, "");++ if (!normalized) {+ throw new PkiSyncError({+ shouldRetry: false,+ message: `Certificate name "${name}" cannot be converted into a GCP Certificate Manager resource ID. Use a certificate name schema that produces lowercase letters, digits or hyphens.`+ });+ }++ if (!GCP_NAME_LEADING_LETTER_PATTERN.test(normalized)) {+ throw new PkiSyncError({+ shouldRetry: false,+ message: `Certificate name "${name}" resolves to the GCP resource ID "${normalized}", which starts with "${normalized[0]}". GCP Certificate Manager requires an ID to start with a letter, so begin the certificate name schema with a letter instead of a placeholder.`+ });+ }++ return normalized;+};++export const buildGcpCertificateResourceName = ({+ gcpProjectId,+ location,+ certificateId+}: {+ gcpProjectId: string;+ location: string;+ certificateId: string;+}) => `projects/${gcpProjectId}/locations/${location}/certificates/${certificateId}`;++export const buildGcpCertificateMapEntryResourceName = ({+ gcpProjectId,+ certificateMap,+ entryId+}: {+ gcpProjectId: string;+ certificateMap: string;+ entryId: string;+}) =>+ `projects/${gcpProjectId}/locations/${GCP_GLOBAL_LOCATION}/certificateMaps/${certificateMap}/certificateMapEntries/${entryId}`;++export const toGcpCertificateMapEntryId = (pkiSyncId: string) => toGcpCertificateId(`infisical-${pkiSyncId}`);diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-payload.test.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-payload.test.tsnew file mode 100644index 0000000000..08655d850b--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-payload.test.ts@@ -0,0 +1,130 @@+import { beforeEach, vi } from "vitest";++import { createGcpCertificateManagerClient } from "./gcp-certificate-manager-pki-sync-client";+import { GcpCertificateManagerScope } from "./gcp-certificate-manager-pki-sync-enums";++type TCapturedCall = [string, Record<string, unknown>, { params: Record<string, string> }];++const { requestMock } = vi.hoisted(() => ({+ requestMock: {+ get: vi.fn(),+ post: vi.fn(),+ patch: vi.fn(),+ delete: vi.fn()+ }+}));++vi.mock("@app/lib/config/request", () => ({ request: requestMock }));++const lastCall = (mock: { mock: { calls: unknown[][] } }): TCapturedCall =>+ mock.mock.calls[0] as unknown as TCapturedCall;++const done = { data: { name: "projects/p/locations/global/operations/op-1", done: true } };++const buildClient = () =>+ createGcpCertificateManagerClient({+ accessToken: "token",+ gcpProjectId: "my-prod-project",+ location: "global",+ syncId: "sync-1"+ });++const upsertArgs = {+ certificateId: "infisical-abc",+ pemCertificate: "-----BEGIN CERTIFICATE-----\nx\n-----END CERTIFICATE-----",+ pemPrivateKey: "-----BEGIN PRIVATE KEY-----\nx\n-----END PRIVATE KEY-----",+ labels: { "managed-by": "infisical" },+ scope: GcpCertificateManagerScope.EdgeCache+};++beforeEach(() => {+ requestMock.get.mockReset();+ requestMock.post.mockReset().mockResolvedValue(done);+ requestMock.patch.mockReset().mockResolvedValue(done);+ requestMock.delete.mockReset().mockResolvedValue(done);+});++describe("GCP certificate create payload", () => {+ test("translates the configured scope into the value GCP expects on create", async () => {+ await buildClient().upsertCertificate({ ...upsertArgs, shouldPatch: false });++ expect(requestMock.post).toHaveBeenCalledTimes(1);+ const [, body, config] = lastCall(requestMock.post);+ expect(body.scope).toBe("EDGE_CACHE");+ expect((body.selfManaged as { pemCertificate: string }).pemCertificate).toContain("BEGIN CERTIFICATE");+ expect(config.params.certificateId).toBe("infisical-abc");+ });++ test("never sends scope on update, because GCP treats it as immutable", async () => {+ await buildClient().upsertCertificate({ ...upsertArgs, shouldPatch: true });++ expect(requestMock.patch).toHaveBeenCalledTimes(1);+ const [, body, config] = lastCall(requestMock.patch);+ expect(body.scope).toBeUndefined();+ expect(config.params.updateMask).toBe("self_managed,labels,description");+ expect(config.params.updateMask).not.toContain("scope");+ });+});++describe("GCP certificate map entry payload", () => {+ test("uses the PRIMARY matcher when no hostname is configured", async () => {+ await buildClient().createCertificateMapEntry({+ certificateMap: "prod-map",+ entryId: "infisical-sync-1",+ certificateResourceNames: ["projects/my-prod-project/locations/global/certificates/infisical-abc"],+ labels: {}+ });++ const [, body] = lastCall(requestMock.post);+ expect(body.matcher).toBe("PRIMARY");+ expect(body.hostname).toBeUndefined();+ });++ test("sends every certificate the entry should reference", async () => {+ // GCP allows up to four per entry, which is how one hostname serves an RSA and an ECDSA cert.+ const certificates = [+ "projects/my-prod-project/locations/global/certificates/infisical-rsa",+ "projects/my-prod-project/locations/global/certificates/infisical-ecdsa"+ ];++ await buildClient().createCertificateMapEntry({+ certificateMap: "prod-map",+ entryId: "infisical-sync-1",+ certificateResourceNames: certificates,+ hostname: "app.example.com",+ labels: {}+ });++ const [, body] = lastCall(requestMock.post);+ expect(body.certificates).toEqual(certificates);+ });++ test("patches the full certificate list, so removing one keeps the others", async () => {+ const remaining = ["projects/my-prod-project/locations/global/certificates/infisical-ecdsa"];++ await buildClient().updateCertificateMapEntryCertificates({+ certificateMap: "prod-map",+ entryId: "infisical-sync-1",+ certificateResourceNames: remaining,+ labels: {}+ });++ const [, body, config] = lastCall(requestMock.patch);+ expect(body.certificates).toEqual(remaining);+ expect(config.params.updateMask).toBe("certificates,labels");+ });++ test("uses the hostname when one is configured", async () => {+ await buildClient().createCertificateMapEntry({+ certificateMap: "prod-map",+ entryId: "infisical-sync-1",+ certificateResourceNames: ["projects/my-prod-project/locations/global/certificates/infisical-abc"],+ hostname: "app.example.com",+ labels: {}+ });++ const [, body] = lastCall(requestMock.post);+ expect(body.hostname).toBe("app.example.com");+ expect(body.matcher).toBeUndefined();+ });+});diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-schemas.test.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-schemas.test.tsnew file mode 100644index 0000000000..e9414a441e--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-schemas.test.ts@@ -0,0 +1,278 @@+import { GcpCertificateManagerScope } from "./gcp-certificate-manager-pki-sync-enums";+import {+ CreateGcpCertificateManagerPkiSyncSchema,+ GcpCertificateManagerPkiSyncConfigSchema,+ GcpCertificateManagerPkiSyncOptionsSchema+} from "./gcp-certificate-manager-pki-sync-schemas";+import { assertGcpCertificateManagerConfigUpdate } from "./gcp-certificate-manager-pki-sync-update-fns";++const parseConfig = (overrides: Record<string, unknown> = {}) =>+ GcpCertificateManagerPkiSyncConfigSchema.safeParse({+ gcpProjectId: "my-prod-project",+ location: "global",+ ...overrides+ });++describe("GCP Certificate Manager certificateNameSchema validation", () => {+ const accepts = (certificateNameSchema: string) =>+ GcpCertificateManagerPkiSyncOptionsSchema.safeParse({ certificateNameSchema }).success;++ test("accepts the destination default and other lowercase schemas", () => {+ expect(accepts("infisical-{{certificateId}}")).toBe(true);+ expect(accepts("cert-{{shortCertificateId}}")).toBe(true);+ expect(accepts("infisical-{{commonName}}-{{certificateId}}")).toBe(true);+ });++ test("rejects a schema that opens with a placeholder, since GCP IDs must start with a letter", () => {+ // A hex or base62 identifier can start with a digit, which GCP rejects outright.+ expect(accepts("{{certificateId}}")).toBe(false);+ expect(accepts("{{shortCertificateId}}")).toBe(false);+ expect(accepts("{{commonName}}-{{certificateId}}")).toBe(false);+ });++ test("rejects uppercase, which GCP resource IDs do not allow", () => {+ expect(accepts("Infisical-{{certificateId}}")).toBe(false);+ expect(accepts("infisical-PROD-{{certificateId}}")).toBe(false);+ });++ test("rejects underscores, dots and spaces", () => {+ expect(accepts("infisical_{{certificateId}}")).toBe(false);+ expect(accepts("infisical.{{certificateId}}")).toBe(false);+ expect(accepts("infisical {{certificateId}}")).toBe(false);+ });++ test("requires a per-certificate identifier so names cannot collide", () => {+ expect(accepts("static-name")).toBe(false);+ expect(accepts("infisical-{{commonName}}")).toBe(false);+ });++ test("rejects schemas that compile past 63 characters", () => {+ expect(accepts(`${"a".repeat(31)}{{certificateId}}`)).toBe(true); // 31 + 32 = 63+ expect(accepts(`${"a".repeat(32)}{{certificateId}}`)).toBe(false); // 32 + 32 = 64+ });++ test("omits postSyncCommand, which has no meaning for a cloud API destination", () => {+ const parsed = GcpCertificateManagerPkiSyncOptionsSchema.safeParse({+ certificateNameSchema: "infisical-{{certificateId}}",+ postSyncCommand: "echo hi"+ });++ expect(parsed.success).toBe(true);+ expect(parsed.success && "postSyncCommand" in parsed.data).toBe(false);+ });++ test("defaults preserveItemOnRenewal to true so rotation happens in place", () => {+ const parsed = GcpCertificateManagerPkiSyncOptionsSchema.safeParse({+ certificateNameSchema: "infisical-{{certificateId}}"+ });++ expect(parsed.success && parsed.data.preserveItemOnRenewal).toBe(true);+ expect(parsed.success && parsed.data.includeRootCa).toBe(false);+ });+});++describe("GCP Certificate Manager destinationConfig validation", () => {+ test("accepts a valid global configuration and defaults the scope", () => {+ const parsed = parseConfig();+ expect(parsed.success).toBe(true);+ expect(parsed.success && parsed.data.scope).toBe(GcpCertificateManagerScope.Default);+ });++ test("rejects malformed GCP project IDs", () => {+ expect(parseConfig({ gcpProjectId: "My-Project" }).success).toBe(false);+ expect(parseConfig({ gcpProjectId: "1project" }).success).toBe(false);+ expect(parseConfig({ gcpProjectId: "proj" }).success).toBe(false);+ expect(parseConfig({ gcpProjectId: "project-" }).success).toBe(false);+ });++ test("accepts regional locations", () => {+ expect(parseConfig({ location: "us-central1" }).success).toBe(true);+ expect(parseConfig({ location: "US-CENTRAL1" }).success).toBe(false);+ });++ test("allows ALL_REGIONS only on global certificates", () => {+ expect(parseConfig({ scope: GcpCertificateManagerScope.AllRegions }).success).toBe(true);+ expect(parseConfig({ scope: GcpCertificateManagerScope.AllRegions, location: "us-central1" }).success).toBe(false);+ });++ test("allows certificate map binding only on global certificates", () => {+ expect(parseConfig({ certificateMapBinding: { certificateMap: "prod-map" } }).success).toBe(true);+ expect(+ parseConfig({ location: "us-central1", certificateMapBinding: { certificateMap: "prod-map" } }).success+ ).toBe(false);+ });++ test("allows certificate map binding only on the default scope", () => {+ const rejected = parseConfig({+ scope: GcpCertificateManagerScope.EdgeCache,+ certificateMapBinding: { certificateMap: "prod-map" }+ });++ expect(rejected.success).toBe(false);+ expect(!rejected.success && rejected.error.issues[0].message).toContain("requires the Default scope");+ expect(+ parseConfig({+ scope: GcpCertificateManagerScope.Default,+ certificateMapBinding: { certificateMap: "prod-map" }+ }).success+ ).toBe(true);+ });++ test("validates the bound hostname", () => {+ expect(parseConfig({ certificateMapBinding: { certificateMap: "m", hostname: "app.example.com" } }).success).toBe(+ true+ );+ expect(parseConfig({ certificateMapBinding: { certificateMap: "m", hostname: "*.example.com" } }).success).toBe(+ true+ );+ expect(parseConfig({ certificateMapBinding: { certificateMap: "m", hostname: "not a hostname" } }).success).toBe(+ false+ );+ });++ test("rejects certificate map names GCP would refuse", () => {+ expect(parseConfig({ certificateMapBinding: { certificateMap: "Prod_Map" } }).success).toBe(false);+ });+});++describe("GCP Certificate Manager create schema", () => {+ const createPayload = (overrides: Record<string, unknown>) =>+ CreateGcpCertificateManagerPkiSyncSchema.safeParse({+ name: "gcp-sync",+ connectionId: "connection-id",+ destinationConfig: { gcpProjectId: "my-prod-project", location: "global" },+ syncOptions: { certificateNameSchema: "infisical-{{certificateId}}" },+ ...overrides+ });++ test("accepts certificate map binding up to the GCP limit of four certificates", () => {+ // GCP: "There can be defined up to four certificates in each Certificate Map Entry", which is+ // how an RSA and an ECDSA certificate serve one hostname.+ const parsed = createPayload({+ destinationConfig: {+ gcpProjectId: "my-prod-project",+ location: "global",+ certificateMapBinding: { certificateMap: "prod-map", hostname: "app.example.com" }+ },+ certificateIds: [+ "11111111-1111-1111-1111-111111111111",+ "22222222-2222-2222-2222-222222222222",+ "33333333-3333-3333-3333-333333333333",+ "44444444-4444-4444-4444-444444444444"+ ]+ });++ expect(parsed.success).toBe(true);+ });++ test("rejects certificate map binding past the GCP limit of four certificates", () => {+ const parsed = createPayload({+ destinationConfig: {+ gcpProjectId: "my-prod-project",+ location: "global",+ certificateMapBinding: { certificateMap: "prod-map", hostname: "app.example.com" }+ },+ certificateIds: [+ "11111111-1111-1111-1111-111111111111",+ "22222222-2222-2222-2222-222222222222",+ "33333333-3333-3333-3333-333333333333",+ "44444444-4444-4444-4444-444444444444",+ "55555555-5555-5555-5555-555555555555"+ ]+ });++ expect(parsed.success).toBe(false);+ });++ test("accepts certificate map binding with a single certificate", () => {+ const parsed = createPayload({+ destinationConfig: {+ gcpProjectId: "my-prod-project",+ location: "global",+ certificateMapBinding: { certificateMap: "prod-map" }+ },+ certificateIds: ["11111111-1111-1111-1111-111111111111"]+ });++ expect(parsed.success).toBe(true);+ });+});++describe("assertGcpCertificateManagerConfigUpdate", () => {+ const previous = { gcpProjectId: "my-prod-project", location: "global", scope: GcpCertificateManagerScope.Default };++ test("allows updates that leave the immutable fields alone", () => {+ expect(() =>+ assertGcpCertificateManagerConfigUpdate(previous, {+ ...previous,+ certificateMapBinding: { certificateMap: "prod-map" }+ })+ ).not.toThrow();+ });++ test("rejects a location change", () => {+ expect(() => assertGcpCertificateManagerConfigUpdate(previous, { ...previous, location: "us-central1" })).toThrow(+ /location is immutable/+ );+ });++ test("rejects a scope change", () => {+ expect(() =>+ assertGcpCertificateManagerConfigUpdate(previous, { ...previous, scope: GcpCertificateManagerScope.EdgeCache })+ ).toThrow(/scope is immutable/);+ });++ test("rejects a project change", () => {+ expect(() =>+ assertGcpCertificateManagerConfigUpdate(previous, { ...previous, gcpProjectId: "other-project" })+ ).toThrow(/GCP project cannot be changed/);+ });+});++describe("GCP Certificate Manager user labels", () => {+ const parseLabels = (labels: unknown) =>+ GcpCertificateManagerPkiSyncOptionsSchema.safeParse({+ certificateNameSchema: "infisical-{{certificateId}}",+ labels+ });++ test("accepts GCP-legal label keys and values", () => {+ expect(parseLabels([{ key: "team", value: "platform" }]).success).toBe(true);+ expect(parseLabels([{ key: "cost-center_1", value: "" }]).success).toBe(true);+ expect(parseLabels(undefined).success).toBe(true);+ });++ test("rejects keys GCP would refuse", () => {+ expect(parseLabels([{ key: "Team", value: "x" }]).success).toBe(false);+ expect(parseLabels([{ key: "1team", value: "x" }]).success).toBe(false);+ expect(parseLabels([{ key: "team.name", value: "x" }]).success).toBe(false);+ expect(parseLabels([{ key: "", value: "x" }]).success).toBe(false);+ expect(parseLabels([{ key: "a".repeat(64), value: "x" }]).success).toBe(false);+ });++ test("rejects values GCP would refuse", () => {+ expect(parseLabels([{ key: "team", value: "Platform" }]).success).toBe(false);+ expect(parseLabels([{ key: "team", value: "a b" }]).success).toBe(false);+ expect(parseLabels([{ key: "team", value: "a".repeat(64) }]).success).toBe(false);+ });++ test("refuses to let a user override Infisical's own labels", () => {+ expect(parseLabels([{ key: "managed-by", value: "someone-else" }]).success).toBe(false);+ expect(parseLabels([{ key: "infisical-certificate-id", value: "abc" }]).success).toBe(false);+ });++ test("rejects duplicate keys", () => {+ const parsed = parseLabels([+ { key: "team", value: "a" },+ { key: "team", value: "b" }+ ]);+ expect(parsed.success).toBe(false);+ expect(parsed.success === false && JSON.stringify(parsed.error.issues)).toContain("Duplicate label key");+ });++ test("caps the count so Infisical's two labels always fit GCP's limit of 64", () => {+ const make = (n: number) => Array.from({ length: n }, (_, i) => ({ key: `k${i}`, value: "v" }));+ expect(parseLabels(make(62)).success).toBe(true);+ expect(parseLabels(make(63)).success).toBe(false);+ });+});diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-schemas.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-schemas.tsnew file mode 100644index 0000000000..94571949ae--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-schemas.ts@@ -0,0 +1,206 @@+import { z } from "zod";++import { openApiHidden } from "@app/server/lib/schemas";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { GCP_GLOBAL_LOCATION, GCP_PROJECT_ID_PATTERN } from "@app/services/app-connection/gcp/gcp-connection-constants";+import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";+import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";+import {+ BasePkiSyncOptionsSchema,+ buildDestinationCertificateNameSchema,+ PkiSyncSchema+} from "@app/services/pki-sync/pki-sync-schemas";++import {+ GCP_CERTIFICATE_MANAGER_NAMING,+ GCP_CERTIFICATE_MAP_NAME_PATTERN,+ GCP_HOSTNAME_PATTERN,+ GCP_LABEL_KEY_PATTERN,+ GCP_LABEL_VALUE_PATTERN,+ GCP_LOCATION_PATTERN,+ GCP_MAX_CERTIFICATES_PER_MAP_ENTRY,+ GCP_MAX_USER_LABELS,+ GCP_NAME_LEADING_LETTER_PATTERN,+ GCP_RESERVED_LABEL_KEYS+} from "./gcp-certificate-manager-pki-sync-constants";+import { GcpCertificateManagerScope } from "./gcp-certificate-manager-pki-sync-enums";++const GcpCertificateMapBindingSchema = z.object({+ certificateMap: z+ .string()+ .trim()+ .min(1, "Certificate map name is required")+ .max(63)+ .refine((value) => GCP_CERTIFICATE_MAP_NAME_PATTERN.test(value), {+ message: "Certificate map name must contain only lowercase letters, digits and hyphens (1-63 characters)"+ }),+ hostname: z+ .string()+ .trim()+ .max(253)+ .optional()+ .transform((value) => value || undefined)+ .refine((value) => value === undefined || GCP_HOSTNAME_PATTERN.test(value), {+ message: 'Hostname must be a fully qualified domain name or a wildcard expression such as "*.example.com"'+ })+});++const BaseGcpCertificateManagerPkiSyncConfigSchema = z.object({+ gcpProjectId: z+ .string()+ .trim()+ .min(6)+ .max(30)+ .refine((value) => GCP_PROJECT_ID_PATTERN.test(value), {+ message:+ "GCP project ID must be 6-30 characters, start with a lowercase letter, contain only lowercase letters, digits and hyphens, and not end with a hyphen"+ }),+ location: z+ .string()+ .trim()+ .min(1, "Location is required")+ .refine((value) => GCP_LOCATION_PATTERN.test(value), {+ message: 'Location must be "global" or a GCP region ID such as "us-central1"'+ }),+ scope: z.nativeEnum(GcpCertificateManagerScope).default(GcpCertificateManagerScope.Default),+ certificateMapBinding: GcpCertificateMapBindingSchema.optional()+});++const assertScopeCompatibility = (+ config: z.infer<typeof BaseGcpCertificateManagerPkiSyncConfigSchema>,+ ctx: z.RefinementCtx+) => {+ if (config.certificateMapBinding && config.scope !== GcpCertificateManagerScope.Default) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["certificateMapBinding"],+ message: `Certificate map binding requires the Default scope, but this sync uses "${config.scope}". A certificate map entry can only reference a Default-scope certificate.`+ });+ }++ if (config.location === GCP_GLOBAL_LOCATION) return;++ if (config.scope === GcpCertificateManagerScope.AllRegions) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["scope"],+ message: `The ALL_REGIONS scope is only available for global certificates, but this sync targets "${config.location}".`+ });+ }++ if (config.certificateMapBinding) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["certificateMapBinding"],+ message: `Certificate map binding is only available for global certificates, but this sync targets "${config.location}". Regional Application Load Balancers attach certificates directly to the target HTTPS proxy, which Infisical does not manage.`+ });+ }+};++export const GcpCertificateManagerPkiSyncConfigSchema =+ BaseGcpCertificateManagerPkiSyncConfigSchema.superRefine(assertScopeCompatibility);++const GcpLabelSchema = z.object({+ key: z+ .string()+ .trim()+ .min(1, "Label key is required")+ .max(63)+ .refine((value) => GCP_LABEL_KEY_PATTERN.test(value), {+ message:+ "Label keys must start with a lowercase letter and contain only lowercase letters, digits, hyphens and underscores (up to 63 characters)"+ })+ .refine((value) => !(GCP_RESERVED_LABEL_KEYS as readonly string[]).includes(value), {+ message: `The label keys ${GCP_RESERVED_LABEL_KEYS.join(" and ")} are set by Infisical and cannot be overridden`+ }),+ value: z+ .string()+ .trim()+ .max(63)+ .refine((value) => GCP_LABEL_VALUE_PATTERN.test(value), {+ message:+ "Label values may contain only lowercase letters, digits, hyphens and underscores (up to 63 characters), and may be empty"+ })+});++export const GcpCertificateManagerPkiSyncOptionsSchema = BasePkiSyncOptionsSchema.omit({+ postSyncCommand: true+}).extend({+ canImportCertificates: z.literal(false).default(false),+ labels: GcpLabelSchema.array()+ .max(GCP_MAX_USER_LABELS, `At most ${GCP_MAX_USER_LABELS} labels can be set`)+ .optional()+ .superRefine((labels, ctx) => {+ if (!labels) return;+ const seen = new Set<string>();+ labels.forEach((label, index) => {+ if (seen.has(label.key)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: [index, "key"],+ message: `Duplicate label key "${label.key}"`+ });+ }+ seen.add(label.key);+ });+ }),+ certificateNameSchema: buildDestinationCertificateNameSchema({+ naming: GCP_CERTIFICATE_MANAGER_NAMING,+ message:+ "Certificate name schema must include the {{certificateId}} or {{shortCertificateId}} placeholder and result in names that contain only lowercase letters, digits and hyphens and are 1-63 characters long for GCP Certificate Manager. Available placeholders: {{certificateId}}, {{shortCertificateId}}, {{profileId}}, {{applicationId}}, {{applicationName}}, {{commonName}}",+ requireCertificateIdentifier: true+ }).refine((value) => GCP_NAME_LEADING_LETTER_PATTERN.test(value), {+ message:+ 'Certificate name schema must start with a lowercase letter, because GCP Certificate Manager requires a resource ID to start with a letter and a placeholder can resolve to a digit. Prefix the schema, for example "infisical-{{certificateId}}".'+ })+});++export const GcpCertificateManagerPkiSyncSchema = PkiSyncSchema.extend({+ destination: z.literal(PkiSync.GcpCertificateManager),+ destinationConfig: BaseGcpCertificateManagerPkiSyncConfigSchema,+ syncOptions: GcpCertificateManagerPkiSyncOptionsSchema+});++export const CreateGcpCertificateManagerPkiSyncSchema = z+ .object({+ name: z.string().trim().min(1).max(256),+ description: pkiDescriptionSchema.optional(),+ isAutoSyncEnabled: z.boolean().default(true),+ destinationConfig: GcpCertificateManagerPkiSyncConfigSchema,+ syncOptions: GcpCertificateManagerPkiSyncOptionsSchema,+ subscriberId: z.string().nullish(),+ connectionId: z.string(),+ projectId: z.string().trim().min(1).optional().describe(openApiHidden()),+ applicationId: z.string().uuid().optional(),+ certificateIds: z.array(z.string().uuid()).optional()+ })+ .superRefine((value, ctx) => {+ if (+ value.destinationConfig.certificateMapBinding &&+ (value.certificateIds?.length ?? 0) > GCP_MAX_CERTIFICATES_PER_MAP_ENTRY+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["destinationConfig", "certificateMapBinding"],+ message: `Certificate map binding supports up to ${GCP_MAX_CERTIFICATES_PER_MAP_ENTRY} certificates, which is the GCP limit for one certificate map entry.`+ });+ }+ });++export const UpdateGcpCertificateManagerPkiSyncSchema = z.object({+ name: z.string().trim().min(1).max(256).optional(),+ description: pkiDescriptionSchema.optional(),+ isAutoSyncEnabled: z.boolean().optional(),+ destinationConfig: GcpCertificateManagerPkiSyncConfigSchema.optional(),+ syncOptions: GcpCertificateManagerPkiSyncOptionsSchema.optional(),+ subscriberId: z.string().nullish(),+ connectionId: z.string().optional()+});++export const GcpCertificateManagerPkiSyncListItemSchema = z.object({+ name: z.literal("GCP Certificate Manager"),+ connection: z.literal(AppConnection.GCP),+ destination: z.literal(PkiSync.GcpCertificateManager),+ canImportCertificates: z.literal(false),+ canRemoveCertificates: z.literal(true)+});diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-types.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-types.tsnew file mode 100644index 0000000000..70477b8441--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-types.ts@@ -0,0 +1,77 @@+import { z } from "zod";++import { TGcpConnection } from "@app/services/app-connection/gcp/gcp-connection-types";++import {+ CreateGcpCertificateManagerPkiSyncSchema,+ GcpCertificateManagerPkiSyncConfigSchema,+ GcpCertificateManagerPkiSyncOptionsSchema,+ GcpCertificateManagerPkiSyncSchema,+ UpdateGcpCertificateManagerPkiSyncSchema+} from "./gcp-certificate-manager-pki-sync-schemas";++export type TGcpCertificateManagerPkiSyncConfig = z.infer<typeof GcpCertificateManagerPkiSyncConfigSchema>;++export type TGcpCertificateManagerPkiSyncOptions = z.infer<typeof GcpCertificateManagerPkiSyncOptionsSchema>;++export type TGcpCertificateManagerPkiSync = z.infer<typeof GcpCertificateManagerPkiSyncSchema>;++export type TGcpCertificateManagerPkiSyncInput = z.infer<typeof CreateGcpCertificateManagerPkiSyncSchema>;++export type TGcpCertificateManagerPkiSyncUpdate = z.infer<typeof UpdateGcpCertificateManagerPkiSyncSchema>;++export type TGcpCertificateManagerPkiSyncWithCredentials = TGcpCertificateManagerPkiSync & {+ connection: TGcpConnection;+};++export type TGcpCertificate = {+ name: string;+ description?: string;+ labels?: Record<string, string>;+ sanDnsnames?: string[];+ pemCertificate?: string;+ expireTime?: string;+ scope?: string;+ createTime?: string;+ updateTime?: string;+ usedBy?: { name: string }[];+};++export type TGcpCertificateMapEntry = {+ name: string;+ description?: string;+ labels?: Record<string, string>;+ certificates?: string[];+ hostname?: string;+ matcher?: string;+ state?: string;+};++export type TGcpCertificateMap = {+ name: string;+ description?: string;+ labels?: Record<string, string>;+};++export type TGcpOperationStatus = {+ code?: number;+ message?: string;+ details?: unknown[];+};++export type TGcpOperation = {+ name: string;+ done?: boolean;+ error?: TGcpOperationStatus;+ response?: Record<string, unknown>;+};++export type TGcpListCertificatesResponse = {+ certificates?: TGcpCertificate[];+ nextPageToken?: string;+};++export type TGcpListCertificateMapEntriesResponse = {+ certificateMapEntries?: TGcpCertificateMapEntry[];+ nextPageToken?: string;+};diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-update-fns.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-update-fns.tsnew file mode 100644index 0000000000..e1966e2504--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-update-fns.ts@@ -0,0 +1,44 @@+import { BadRequestError } from "@app/lib/errors";++import { GCP_MAX_CERTIFICATES_PER_MAP_ENTRY } from "./gcp-certificate-manager-pki-sync-constants";+import { TGcpCertificateManagerPkiSyncConfig } from "./gcp-certificate-manager-pki-sync-types";++export const assertGcpCertificateManagerConfigUpdate = (+ previous: TGcpCertificateManagerPkiSyncConfig,+ next: TGcpCertificateManagerPkiSyncConfig+) => {+ if (previous.gcpProjectId && next.gcpProjectId && next.gcpProjectId !== previous.gcpProjectId) {+ throw new BadRequestError({+ message: `The GCP project cannot be changed after a GCP Certificate Manager sync is created. Create a new sync targeting "${next.gcpProjectId}" instead.`+ });+ }++ if (previous.location && next.location && next.location !== previous.location) {+ throw new BadRequestError({+ message: `The location cannot be changed after a GCP Certificate Manager sync is created, because a GCP certificate's location is immutable. Create a new sync targeting "${next.location}" instead.`+ });+ }++ if (previous.scope && next.scope && next.scope !== previous.scope) {+ throw new BadRequestError({+ message: `The scope cannot be changed after a GCP Certificate Manager sync is created, because a GCP certificate's scope is immutable. Create a new sync with the "${next.scope}" scope instead.`+ });+ }+};++export const buildGcpTooManyCertificatesMessage = (certificateMap: string, certificateCount: number) =>+ `This sync attaches its certificates to the GCP certificate map "${certificateMap}", and GCP allows at most ${GCP_MAX_CERTIFICATES_PER_MAP_ENTRY} certificates in one certificate map entry. Turn off the certificate map binding to sync ${certificateCount} certificates, or link at most ${GCP_MAX_CERTIFICATES_PER_MAP_ENTRY}.`;++export const assertGcpCertificateManagerCertificateCount = (+ destinationConfig: TGcpCertificateManagerPkiSyncConfig | undefined,+ resultingCertificateCount: number+) => {+ if (resultingCertificateCount <= GCP_MAX_CERTIFICATES_PER_MAP_ENTRY) return;++ const certificateMapBinding = destinationConfig?.certificateMapBinding;+ if (!certificateMapBinding) return;++ throw new BadRequestError({+ message: buildGcpTooManyCertificatesMessage(certificateMapBinding.certificateMap, resultingCertificateCount)+ });+};diff --git a/backend/src/services/pki-sync/gcp-certificate-manager/index.ts b/backend/src/services/pki-sync/gcp-certificate-manager/index.tsnew file mode 100644index 0000000000..ea414597a6--- /dev/null+++ b/backend/src/services/pki-sync/gcp-certificate-manager/index.ts@@ -0,0 +1,7 @@+export * from "./gcp-certificate-manager-pki-sync-auth-fns";+export * from "./gcp-certificate-manager-pki-sync-constants";+export * from "./gcp-certificate-manager-pki-sync-enums";+export * from "./gcp-certificate-manager-pki-sync-fns";+export * from "./gcp-certificate-manager-pki-sync-schemas";+export * from "./gcp-certificate-manager-pki-sync-types";+export * from "./gcp-certificate-manager-pki-sync-update-fns";diff --git a/backend/src/services/pki-sync/pki-sync-certificate-name-fns.test.ts b/backend/src/services/pki-sync/pki-sync-certificate-name-fns.test.tsindex 0f38cb214f..c8de2ee388 100644--- a/backend/src/services/pki-sync/pki-sync-certificate-name-fns.test.ts+++ b/backend/src/services/pki-sync/pki-sync-certificate-name-fns.test.ts@@ -256,3 +256,12 @@ describe("certificateNameSchemaHasFreeTextPlaceholder", () => {expect(certificateNameSchemaHasFreeTextPlaceholder(undefined)).toBe(false);});});++describe("sanitizeCertificateNameValue for GCP Certificate Manager", () => {+ // GCP requires lowercase, but stripping letters here would destroy them instead of the+ // destination lowercasing them, turning "API.Example.com" into hyphens.+ test("keeps letters and replaces only disallowed characters", () => {+ expect(sanitizeCertificateNameValue("API.Example.com", PkiSync.GcpCertificateManager)).toBe("API-Example-com");+ expect(sanitizeCertificateNameValue("web_app", PkiSync.GcpCertificateManager)).toBe("web-app");+ });+});diff --git a/backend/src/services/pki-sync/pki-sync-certificate-name-fns.ts b/backend/src/services/pki-sync/pki-sync-certificate-name-fns.tsindex 2124307577..4f26c2a935 100644--- a/backend/src/services/pki-sync/pki-sync-certificate-name-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-certificate-name-fns.ts@@ -36,6 +36,7 @@ const NAME_VALUE_DISALLOWED_CHARS: Partial<Record<PkiSync, RE2>> = {[PkiSync.AzureKeyVault]: new RE2("[^a-zA-Z0-9-]", "g"),[PkiSync.CloudflareCustomCertificate]: new RE2("[^a-zA-Z0-9_-]", "g"),[PkiSync.Chef]: new RE2("[^a-zA-Z0-9_-]", "g"),+ [PkiSync.GcpCertificateManager]: new RE2("[^a-zA-Z0-9-]", "g"),[PkiSync.AwsCertificateManager]: new RE2("[^a-zA-Z0-9 _-]", "g"),[PkiSync.AwsElasticLoadBalancer]: new RE2("[^a-zA-Z0-9 _-]", "g"),[PkiSync.AwsSecretsManager]: new RE2("[^a-zA-Z0-9_-]", "g"),diff --git a/backend/src/services/pki-sync/pki-sync-dal.ts b/backend/src/services/pki-sync/pki-sync-dal.tsindex 73d379cdaf..eafe93ff62 100644--- a/backend/src/services/pki-sync/pki-sync-dal.ts+++ b/backend/src/services/pki-sync/pki-sync-dal.ts@@ -208,13 +208,16 @@ export const pkiSyncDALFactory = (db: TDbClient) => {projectId: string,processedRules?: ProcessedPermissionRules,tx?: Knex,- options?: { applicationId?: string | null }+ options?: { applicationId?: string | null; destination?: PkiSync }) => {try {const filter: PkiSyncFindFilter = { projectId };if (options?.applicationId !== undefined) {(filter as Record<string, unknown>).applicationId = options.applicationId;}+ if (options?.destination) {+ (filter as Record<string, unknown>).destination = options.destination;+ }const pkiSyncs = await basePkiSyncWithSubscriberQuery({filter,db,diff --git a/backend/src/services/pki-sync/pki-sync-enums.ts b/backend/src/services/pki-sync/pki-sync-enums.tsindex 37743f3d37..ed97e06fb3 100644--- a/backend/src/services/pki-sync/pki-sync-enums.ts+++ b/backend/src/services/pki-sync/pki-sync-enums.ts@@ -4,6 +4,7 @@ export enum PkiSync {AwsSecretsManager = "aws-secrets-manager",AwsElasticLoadBalancer = "aws-elastic-load-balancer",Chef = "chef",+ GcpCertificateManager = "gcp-certificate-manager",CloudflareCustomCertificate = "cloudflare-custom-certificate",NetScaler = "netscaler",F5BigIp = "f5-big-ip",diff --git a/backend/src/services/pki-sync/pki-sync-fns.test.ts b/backend/src/services/pki-sync/pki-sync-fns.test.tsindex 1f7fed1ae4..b0b4007270 100644--- a/backend/src/services/pki-sync/pki-sync-fns.test.ts+++ b/backend/src/services/pki-sync/pki-sync-fns.test.ts@@ -1,5 +1,5 @@import { PkiSync } from "./pki-sync-enums";-import { getPkiSyncProviderCapabilities, matchesCertificateNameSchema } from "./pki-sync-fns";+import { getPkiSyncProviderCapabilities, matchesCertificateNameSchema, parsePkiSyncErrorMessage } from "./pki-sync-fns";// A dash-stripped UUID (what {{certificateId}}, {{profileId}}, {{applicationId}} resolve to).const HEX = "550e8400e29b41d4a716446655440000";@@ -114,3 +114,28 @@ describe("getPkiSyncProviderCapabilities: canRunPostSyncCommand", () => {});});});++describe("parsePkiSyncErrorMessage", () => {+ // The three sync/import/remove message columns are varchar(255), so an over-long message makes+ // the status write throw and leaves the sync stuck reporting "running".+ test("caps the message at the width of the columns it is written to", () => {+ const message = parsePkiSyncErrorMessage(new Error("x".repeat(500)));++ expect(message).toHaveLength(255);+ expect(message.endsWith("...")).toBe(true);+ });++ test("caps a thrown string too", () => {+ expect(parsePkiSyncErrorMessage("y".repeat(500))).toHaveLength(255);+ });++ test("leaves a message that already fits untouched", () => {+ expect(parsePkiSyncErrorMessage(new Error("Connection refused by the destination host"))).toBe(+ "Connection refused by the destination host"+ );+ });++ test("falls back to a readable message for a non-error throw", () => {+ expect(parsePkiSyncErrorMessage({ weird: true })).toBe("An unknown error occurred during PKI sync operation");+ });+});diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.tsindex a719495660..fa26f36746 100644--- a/backend/src/services/pki-sync/pki-sync-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-fns.ts@@ -24,6 +24,13 @@ import { CLOUDFLARE_CUSTOM_CERTIFICATE_PKI_SYNC_LIST_OPTION } from "./cloudflareimport { cloudflareCustomCertificatePkiSyncFactory } from "./cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-fns";import { F5_BIG_IP_PKI_SYNC_LIST_OPTION } from "./f5-big-ip/f5-big-ip-pki-sync-constants";import { f5BigIpPkiSyncFactory } from "./f5-big-ip/f5-big-ip-pki-sync-fns";+import { GCP_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION } from "./gcp-certificate-manager/gcp-certificate-manager-pki-sync-constants";+import { gcpCertificateManagerPkiSyncFactory } from "./gcp-certificate-manager/gcp-certificate-manager-pki-sync-fns";+import { TGcpCertificateManagerPkiSyncConfig } from "./gcp-certificate-manager/gcp-certificate-manager-pki-sync-types";+import {+ assertGcpCertificateManagerCertificateCount,+ assertGcpCertificateManagerConfigUpdate+} from "./gcp-certificate-manager/gcp-certificate-manager-pki-sync-update-fns";import { KEMP_LOADMASTER_PKI_SYNC_LIST_OPTION } from "./kemp-loadmaster/kemp-loadmaster-pki-sync-constants";import { kempLoadMasterPkiSyncFactory } from "./kemp-loadmaster/kemp-loadmaster-pki-sync-fns";import { LINUX_SERVER_PKI_SYNC_LIST_OPTION } from "./linux-server/linux-server-pki-sync-constants";@@ -51,6 +58,7 @@ const PKI_SYNC_LIST_OPTIONS = {[PkiSync.AwsSecretsManager]: AWS_SECRETS_MANAGER_PKI_SYNC_LIST_OPTION,[PkiSync.AwsElasticLoadBalancer]: AWS_ELASTIC_LOAD_BALANCER_PKI_SYNC_LIST_OPTION,[PkiSync.Chef]: CHEF_PKI_SYNC_LIST_OPTION,+ [PkiSync.GcpCertificateManager]: GCP_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION,[PkiSync.CloudflareCustomCertificate]: CLOUDFLARE_CUSTOM_CERTIFICATE_PKI_SYNC_LIST_OPTION,[PkiSync.NetScaler]: NETSCALER_PKI_SYNC_LIST_OPTION,[PkiSync.F5BigIp]: F5_BIG_IP_PKI_SYNC_LIST_OPTION,@@ -100,6 +108,32 @@ export const getPkiSyncMaxCertificates = (destination: PkiSync): number | undefireturn undefined;};+export const assertPkiSyncDestinationConfigUpdate = (+ destination: PkiSync,+ previousConfig: Record<string, unknown>,+ nextConfig: Record<string, unknown>+) => {+ if (destination === PkiSync.GcpCertificateManager) {+ assertGcpCertificateManagerConfigUpdate(+ previousConfig as TGcpCertificateManagerPkiSyncConfig,+ nextConfig as TGcpCertificateManagerPkiSyncConfig+ );+ }+};++export const assertPkiSyncDestinationConfigAllowsCertificateCount = (+ destination: PkiSync,+ destinationConfig: Record<string, unknown> | undefined,+ resultingCertificateCount: number+) => {+ if (destination === PkiSync.GcpCertificateManager) {+ assertGcpCertificateManagerCertificateCount(+ destinationConfig as TGcpCertificateManagerPkiSyncConfig | undefined,+ resultingCertificateCount+ );+ }+};+export const matchesSchema = <T extends ZodSchema>(schema: T, data: unknown): data is z.infer<T> => {return schema.safeParse(data).success;};@@ -111,11 +145,11 @@ export const truncateSyncMessage = (message: string): string =>export const parsePkiSyncErrorMessage = (error: unknown): string => {if (error instanceof Error) {- return error.message;+ return truncateSyncMessage(error.message);}if (typeof error === "string") {- return error;+ return truncateSyncMessage(error);}return "An unknown error occurred during PKI sync operation";@@ -203,6 +237,11 @@ export const PkiSyncFns = {"Nutanix Prism Central does not support importing certificates into Infisical (private keys cannot be extracted)");}+ case PkiSync.GcpCertificateManager: {+ throw new Error(+ "GCP Certificate Manager does not support importing certificates into Infisical (private keys cannot be extracted)"+ );+ }default:throw new Error(`Unsupported PKI sync destination: ${String(pkiSync.destination)}`);}@@ -338,6 +377,14 @@ export const PkiSyncFns = {});return nutanixPkiSync.syncCertificates(pkiSync, certificateMap);}+ case PkiSync.GcpCertificateManager: {+ checkPkiSyncDestination(pkiSync, PkiSync.GcpCertificateManager as PkiSync);+ const gcpCertificateManagerPkiSync = gcpCertificateManagerPkiSyncFactory({+ certificateDAL: dependencies.certificateDAL,+ certificateSyncDAL: dependencies.certificateSyncDAL+ });+ return gcpCertificateManagerPkiSync.syncCertificates(pkiSync, certificateMap);+ }default:throw new Error(`Unsupported PKI sync destination: ${String(pkiSync.destination)}`);}@@ -510,6 +557,18 @@ export const PkiSyncFns = {message: "Nutanix Prism Central does not support removing certificates"});}+ case PkiSync.GcpCertificateManager: {+ checkPkiSyncDestination(pkiSync, PkiSync.GcpCertificateManager as PkiSync);+ const gcpCertificateManagerPkiSync = gcpCertificateManagerPkiSyncFactory({+ certificateDAL: dependencies.certificateDAL,+ certificateSyncDAL: dependencies.certificateSyncDAL+ });+ await gcpCertificateManagerPkiSync.removeCertificates(pkiSync, certificateNames, {+ certificateSyncDAL: dependencies.certificateSyncDAL,+ certificateMap: dependencies.certificateMap+ });+ break;+ }default:throw new Error(`Unsupported PKI sync destination: ${String(pkiSync.destination)}`);}diff --git a/backend/src/services/pki-sync/pki-sync-maps.ts b/backend/src/services/pki-sync/pki-sync-maps.tsindex 3aaa7f531f..048233dc23 100644--- a/backend/src/services/pki-sync/pki-sync-maps.ts+++ b/backend/src/services/pki-sync/pki-sync-maps.ts@@ -8,6 +8,7 @@ export const PKI_SYNC_NAME_MAP: Record<PkiSync, string> = {[PkiSync.AwsSecretsManager]: "AWS Secrets Manager",[PkiSync.AwsElasticLoadBalancer]: "AWS Elastic Load Balancer",[PkiSync.Chef]: "Chef",+ [PkiSync.GcpCertificateManager]: "GCP Certificate Manager",[PkiSync.CloudflareCustomCertificate]: "Cloudflare Custom SSL Certificate",[PkiSync.NetScaler]: "NetScaler",[PkiSync.F5BigIp]: "F5 BIG-IP",@@ -23,6 +24,7 @@ export const PKI_SYNC_CONNECTION_MAP: Record<PkiSync, AppConnection> = {[PkiSync.AwsSecretsManager]: AppConnection.AWS,[PkiSync.AwsElasticLoadBalancer]: AppConnection.AWS,[PkiSync.Chef]: AppConnection.Chef,+ [PkiSync.GcpCertificateManager]: AppConnection.GCP,[PkiSync.CloudflareCustomCertificate]: AppConnection.Cloudflare,[PkiSync.NetScaler]: AppConnection.NetScaler,[PkiSync.F5BigIp]: AppConnection.F5BigIp,diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.tsindex ca2b539440..84350d1558 100644--- a/backend/src/services/pki-sync/pki-sync-queue.ts+++ b/backend/src/services/pki-sync/pki-sync-queue.ts@@ -435,6 +435,7 @@ export const pkiSyncQueueFactory = ({let isSynced = false;let certSyncFailureCount = 0;let syncMessage: string | null = null;+ let partialFailure = false;let postSyncCommandResult: TPostSyncCommandResult | undefined;let isFinalAttempt = job.attemptsStarted === job.opts.attempts;@@ -623,8 +624,10 @@ export const pkiSyncQueueFactory = ({}postSyncCommandResult = syncResult.postSyncCommand;+ partialFailure = Boolean(syncResult.partialFailureMessage);const reasons = [certSyncFailureCount > 0 ? `${certSyncFailureCount} certificate(s) failed to sync to the destination` : null,+ syncResult.partialFailureMessage ?? null,postSyncCommandResult?.status === PkiSyncStatus.Failed? buildPostSyncCommandFailureMessage(postSyncCommandResult): null@@ -663,7 +666,7 @@ export const pkiSyncQueueFactory = ({} finally {const ranAt = new Date();const postSyncCommandFailed = postSyncCommandResult?.status === PkiSyncStatus.Failed;- const fullySynced = isSynced && certSyncFailureCount === 0 && !postSyncCommandFailed;+ const fullySynced = isSynced && certSyncFailureCount === 0 && !postSyncCommandFailed && !partialFailure;const syncStatus = fullySynced ? PkiSyncStatus.Succeeded : PkiSyncStatus.Failed;await auditLogService.createAuditLog({diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.tsindex a57f5954ad..224e2d10cb 100644--- a/backend/src/services/pki-sync/pki-sync-service.ts+++ b/backend/src/services/pki-sync/pki-sync-service.ts@@ -26,6 +26,8 @@ import { TPkiSyncDALFactory } from "./pki-sync-dal";import { PkiSync, PkiSyncStatus } from "./pki-sync-enums";import { PkiSyncExportFormat } from "./pki-sync-export-fns";import {+ assertPkiSyncDestinationConfigAllowsCertificateCount,+ assertPkiSyncDestinationConfigUpdate,enterprisePkiSyncCheck,getPkiSyncMaxCertificates,getPkiSyncProviderCapabilities,@@ -81,7 +83,6 @@ type TPkiSyncServiceFactoryDep = {| "findCertificateIdsByPkiSyncId"| "addCertificates"| "removeCertificates"- | "removeAllCertificatesFromSync"| "findWithDetails"| "updateSyncMetadata"| "clearSyncMetadataFlag"@@ -361,6 +362,7 @@ export const pkiSyncServiceFactory = ({assertWithinCertificateLimit(destination, certificateIds.length);await validateCertificatesForSync(certificateIds, projectId, applicationId);assertSyncOptionsAllowCertificateCount(resolvedSyncOptions, certificateIds.length);+ assertPkiSyncDestinationConfigAllowsCertificateCount(destination, destinationConfig, certificateIds.length);}const encryptedCredentials = credentials?.exportPassword@@ -416,7 +418,6 @@ export const pkiSyncServiceFactory = ({syncOptions,subscriberId,connectionId,- certificateIds,credentials}: Omit<TUpdatePkiSyncDTO, "auditLogInfo" | "projectId">,actor: OrgServiceActor@@ -476,6 +477,10 @@ export const pkiSyncServiceFactory = ({}}+ if (destinationConfig) {+ assertPkiSyncDestinationConfigUpdate(pkiSync.destination, pkiSync.destinationConfig ?? {}, destinationConfig);+ }+let effectiveConnection: { gatewayId?: string | null; gatewayPoolId?: string | null } | undefined;if (connectionId && connectionId !== pkiSync.connectionId) {const destinationApp = getDestinationAppType(pkiSync.destination);@@ -505,6 +510,9 @@ export const pkiSyncServiceFactory = ({}const effectiveSyncOptions = (resolvedSyncOptions ?? pkiSync.syncOptions) as Record<string, unknown> | undefined;+ const effectiveDestinationConfig = (destinationConfig ?? pkiSync.destinationConfig) as+ | Record<string, unknown>+ | undefined;await $assertMaySetPostSyncCommand(effectiveSyncOptions?.postSyncCommand,@@ -527,23 +535,14 @@ export const pkiSyncServiceFactory = ({);}- if (certificateIds !== undefined) {- if (certificateIds.length > 0) {- assertWithinCertificateLimit(pkiSync.destination, certificateIds.length);- await validateCertificatesForSync(certificateIds, pkiSync.projectId, pkiSync.applicationId);- assertSyncOptionsAllowCertificateCount(effectiveSyncOptions, certificateIds.length);- }-- await certificateSyncDAL.removeAllCertificatesFromSync(id);- if (certificateIds.length > 0) {- await certificateSyncDAL.addCertificates(- id,- certificateIds.map((certId) => ({ certificateId: certId }))- );- }- } else if (syncOptions) {+ if (syncOptions || destinationConfig) {const existingCount = (await certificateSyncDAL.findByPkiSyncId(id)).length;assertSyncOptionsAllowCertificateCount(effectiveSyncOptions, existingCount);+ assertPkiSyncDestinationConfigAllowsCertificateCount(+ pkiSync.destination,+ effectiveDestinationConfig,+ existingCount+ );}if (@@ -558,7 +557,7 @@ export const pkiSyncServiceFactory = ({? await encryptPkiSyncCredentials({ orgId: actor.orgId, projectId: pkiSync.projectId, credentials, kmsService }): undefined;- const updatedPkiSync = await pkiSyncDAL.updateById(id, {+ const update = {name,description,isAutoSyncEnabled,@@ -567,7 +566,11 @@ export const pkiSyncServiceFactory = ({subscriberId,connectionId,...(encryptedCredentials ? { encryptedCredentials } : {})- });+ };++ if (Object.values(update).every((value) => value === undefined)) return pkiSync as TPkiSync;++ const updatedPkiSync = await pkiSyncDAL.updateById(id, update);return updatedPkiSync as TPkiSync;};@@ -623,7 +626,7 @@ export const pkiSyncServiceFactory = ({};const listPkiSyncsByProjectId = async (- { projectId, certificateId, applicationId }: TListPkiSyncsByProjectId,+ { projectId, certificateId, applicationId, destination }: TListPkiSyncsByProjectId,actor: OrgServiceActor): Promise<TPkiSync[]> => {let processedRules: ReturnType<typeof getProcessedPermissionRules> | undefined;@@ -662,7 +665,10 @@ export const pkiSyncServiceFactory = ({projectId,processedRules,undefined,- applicationId !== undefined ? { applicationId } : undefined+ {+ ...(applicationId !== undefined ? { applicationId } : {}),+ ...(destination ? { destination } : {})+ });if (certificateId) {@@ -872,6 +878,11 @@ export const pkiSyncServiceFactory = ({pkiSync.syncOptions as Record<string, unknown> | undefined,prospectiveCount);+ assertPkiSyncDestinationConfigAllowsCertificateCount(+ pkiSync.destination,+ pkiSync.destinationConfig,+ prospectiveCount+ );const alreadyLinked = new Set(existingCertificateIds);const certificateIdsToAdd = certificateIds.filter((id) => !alreadyLinked.has(id));diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.tsindex f6615509e4..c5eb0b90c7 100644--- a/backend/src/services/pki-sync/pki-sync-types.ts+++ b/backend/src/services/pki-sync/pki-sync-types.ts@@ -106,6 +106,7 @@ export type TPkiSyncSyncResult = {skippedCertificates?: Array<{ name: string; reason: string }>;validationErrors?: Array<{ name: string; error: string }>;};+ partialFailureMessage?: string;};export type TCreatePkiSyncDTO = {@@ -136,7 +137,6 @@ export type TUpdatePkiSyncDTO = {syncOptions?: Record<string, unknown>;subscriberId?: string | null;connectionId?: string;- certificateIds?: string[];credentials?: { exportPassword?: string };auditLogInfo: AuditLogInfo;resourceInternalMetadata?: ResourceMetadataDTO;@@ -153,6 +153,7 @@ export type TListPkiSyncsByProjectId = {projectId: string;certificateId?: string;applicationId?: string | null;+ destination?: PkiSync;};export type TFindPkiSyncByIdDTO = {diff --git a/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/create.mdx b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/create.mdxnew file mode 100644index 0000000000..2ed0c85b45--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/create.mdx@@ -0,0 +1,4 @@+---+title: "Create GCP Certificate Manager PKI Sync"+openapi: "POST /api/v1/cert-manager/syncs/gcp-certificate-manager"+---diff --git a/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/delete.mdx b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/delete.mdxnew file mode 100644index 0000000000..eefb8e7594--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete GCP Certificate Manager PKI Sync"+openapi: "DELETE /api/v1/cert-manager/syncs/gcp-certificate-manager/{pkiSyncId}"+---diff --git a/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/get-by-id.mdx b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/get-by-id.mdxnew file mode 100644index 0000000000..ba7780a9b1--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/get-by-id.mdx@@ -0,0 +1,4 @@+---+title: "Get GCP Certificate Manager PKI Sync by ID"+openapi: "GET /api/v1/cert-manager/syncs/gcp-certificate-manager/{pkiSyncId}"+---diff --git a/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/list.mdx b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/list.mdxnew file mode 100644index 0000000000..65dc51a7d2--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/list.mdx@@ -0,0 +1,4 @@+---+title: "List GCP Certificate Manager PKI Syncs"+openapi: "GET /api/v1/cert-manager/syncs/gcp-certificate-manager"+---diff --git a/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/remove-certificates.mdx b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/remove-certificates.mdxnew file mode 100644index 0000000000..cefbcdf234--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/remove-certificates.mdx@@ -0,0 +1,4 @@+---+title: "Remove Certificates from GCP Certificate Manager"+openapi: "POST /api/v1/cert-manager/syncs/gcp-certificate-manager/{pkiSyncId}/remove-certificates"+---diff --git a/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/sync-certificates.mdx b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/sync-certificates.mdxnew file mode 100644index 0000000000..b5379720c2--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/sync-certificates.mdx@@ -0,0 +1,4 @@+---+title: "Sync Certificates to GCP Certificate Manager"+openapi: "POST /api/v1/cert-manager/syncs/gcp-certificate-manager/{pkiSyncId}/sync"+---diff --git a/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/update.mdx b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/update.mdxnew file mode 100644index 0000000000..59951b598f--- /dev/null+++ b/docs/api-reference/endpoints/pki/syncs/gcp-certificate-manager/update.mdx@@ -0,0 +1,4 @@+---+title: "Update GCP Certificate Manager PKI Sync"+openapi: "PATCH /api/v1/cert-manager/syncs/gcp-certificate-manager/{pkiSyncId}"+---diff --git a/docs/docs.json b/docs/docs.jsonindex 95e9e23114..9d0e286614 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -1008,7 +1008,8 @@"documentation/platform/pki/applications/certificate-syncs/kemp-loadmaster","documentation/platform/pki/applications/certificate-syncs/linux-server","documentation/platform/pki/applications/certificate-syncs/windows-server",- "documentation/platform/pki/applications/certificate-syncs/nutanix-prism-central"+ "documentation/platform/pki/applications/certificate-syncs/nutanix-prism-central",+ "documentation/platform/pki/applications/certificate-syncs/gcp-certificate-manager"]}]@@ -3925,6 +3926,18 @@"api-reference/endpoints/pki/syncs/nutanix-prism-central/delete","api-reference/endpoints/pki/syncs/nutanix-prism-central/sync-certificates"]+ },+ {+ "group": "GCP Certificate Manager",+ "pages": [+ "api-reference/endpoints/pki/syncs/gcp-certificate-manager/list",+ "api-reference/endpoints/pki/syncs/gcp-certificate-manager/get-by-id",+ "api-reference/endpoints/pki/syncs/gcp-certificate-manager/create",+ "api-reference/endpoints/pki/syncs/gcp-certificate-manager/update",+ "api-reference/endpoints/pki/syncs/gcp-certificate-manager/delete",+ "api-reference/endpoints/pki/syncs/gcp-certificate-manager/sync-certificates",+ "api-reference/endpoints/pki/syncs/gcp-certificate-manager/remove-certificates"+ ]}]}diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/gcp-certificate-manager.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/gcp-certificate-manager.mdxnew file mode 100644index 0000000000..c879f6f39f--- /dev/null+++ b/docs/documentation/platform/pki/applications/certificate-syncs/gcp-certificate-manager.mdx@@ -0,0 +1,251 @@+---+title: "GCP Certificate Manager"+sidebarTitle: "GCP Certificate Manager"+description: "Upload certificates to GCP Certificate Manager and rotate them in place."+---++Upload certificates managed in Infisical to GCP Certificate Manager as self-managed certificates. When a certificate is renewed, Infisical updates the same GCP certificate in place, so the load balancers serving it pick up the new material with no change in GCP.++<Info>+ Certificate Syncs are configured per Application. First select which certificate to sync, then configure the GCP Certificate Manager destination.+</Info>++## Prerequisites++- A [GCP Connection](/integrations/app-connections/gcp)+- These APIs enabled on the GCP project that will hold your certificates:++ ```bash+ gcloud services enable \+ certificatemanager.googleapis.com \+ cloudresourcemanager.googleapis.com \+ serviceusage.googleapis.com \+ --project=PROJECT_ID+ ```++- These roles granted to the connection's service account on that same project:++ | Role | Needed for |+ | --- | --- |+ | Certificate Manager Editor (`roles/certificatemanager.editor`) | Uploading and rotating certificates, and maintaining certificate map entries |+ | Service Usage Viewer (`roles/serviceusage.serviceUsageViewer`) | Listing the projects that have Certificate Manager enabled |+ | Browser (`roles/browser`) | Showing the project in the sync form |+ | Certificate Manager Owner (`roles/certificatemanager.owner`) | Removing certificates, only if you enable removal on the sync |++<Note>+ If you manage several GCP projects, make sure the APIs and roles are applied to the project that will hold your certificates, not to whichever project you happen to have open.+</Note>++## Create a GCP Certificate Manager Sync++<Tabs>+ <Tab title="Infisical UI">+ 1. In your Application, go to the **Certificate Syncs** tab and click **Create Sync**.++ 2. Select the **GCP Certificate Manager** option.++ 3. Configure the **Destination**:+ - **GCP Connection**: Choose the connection to authenticate with.+ - **GCP Project**: Select the target project. Only projects with the Certificate Manager API enabled appear in the list.+ - **Location**: Select **Global** for global external Application Load Balancers and Media CDN, or a region for regional Application Load Balancers.+ - **Scope**: Select the scope matching your load balancer. See [Scopes](#scopes) below.+ - **Attach to a certificate map**: Optionally have Infisical maintain the certificate map entry that puts this certificate in front of traffic. Available for global certificates using the Default scope only.++ 4. Configure the **Sync Options**:+ - **Auto-Sync Enabled**: Automatically push the certificate to GCP whenever it is renewed or updated in Infisical.+ - **Certificate name schema**: Controls the GCP certificate resource ID. Must start with a lowercase letter and produce lowercase letters, digits and hyphens only.+ - **Preserve certificate on renewal**: Enabled by default. See [Certificate renewal behavior](#certificate-renewal-behavior).++ 5. Configure the **Details**:+ - **Name**: A name for this sync.+ - **Description**: Optional description.++ 6. Select the certificates to sync.++ 7. Review and click **Create Sync**.+ </Tab>+ <Tab title="API">+ To create a **GCP Certificate Manager Certificate Sync**, make an API request to the [Create GCP Certificate Manager PKI Sync](/api-reference/endpoints/pki/syncs/gcp-certificate-manager/create) API endpoint.++ ### Sample request++ <Note>+ You can optionally specify `certificateIds` during sync creation to immediately add certificates to the sync.+ If not provided, you can add them later using the certificate management endpoints.+ </Note>++ ```bash Request+ curl --request POST \+ --url https://app.infisical.com/api/v1/cert-manager/syncs/gcp-certificate-manager \+ --header 'Authorization: Bearer <access-token>' \+ --header 'Content-Type: application/json' \+ --data '{+ "name": "my-gcp-cert-sync",+ "applicationId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",+ "description": "Push TLS certs to the production load balancer",+ "connectionId": "550e8400-e29b-41d4-a716-446655440000",+ "destination": "gcp-certificate-manager",+ "isAutoSyncEnabled": true,+ "certificateIds": [+ "550e8400-e29b-41d4-a716-446655440000"+ ],+ "destinationConfig": {+ "gcpProjectId": "my-prod-project",+ "location": "global",+ "scope": "default",+ "certificateMapBinding": {+ "certificateMap": "prod-map",+ "hostname": "app.example.com"+ }+ },+ "syncOptions": {+ "canImportCertificates": false,+ "canRemoveCertificates": true,+ "preserveItemOnRenewal": true,+ "certificateNameSchema": "infisical-{{certificateId}}"+ }+ }'+ ```++ ### Sample response++ ```json Response+ {+ "pkiSync": {+ "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",+ "name": "my-gcp-cert-sync",+ "description": "Push TLS certs to the production load balancer",+ "destination": "gcp-certificate-manager",+ "isAutoSyncEnabled": true,+ "destinationConfig": {+ "gcpProjectId": "my-prod-project",+ "location": "global",+ "scope": "default",+ "certificateMapBinding": {+ "certificateMap": "prod-map",+ "hostname": "app.example.com"+ }+ },+ "syncOptions": {+ "canImportCertificates": false,+ "canRemoveCertificates": true,+ "preserveItemOnRenewal": true,+ "certificateNameSchema": "infisical-{{certificateId}}"+ },+ "applicationId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",+ "connectionId": "550e8400-e29b-41d4-a716-446655440000",+ "createdAt": "2026-08-19T00:00:00.000Z",+ "updatedAt": "2026-08-19T00:00:00.000Z"+ }+ }+ ```+ </Tab>+</Tabs>++## Certificate Naming++GCP Certificate Manager resource IDs must start with a letter, contain only lowercase letters, digits and hyphens, and be 1 to 63 characters. The default certificate name schema is `infisical-{{certificateId}}`, which always satisfies that. A schema has to begin with a letter rather than a placeholder, because a certificate ID can begin with a digit, and Infisical rejects one that does not when you save the sync.++If you use `{{commonName}}` or `{{applicationName}}` in the schema, their values are lowercased and any other character becomes a hyphen, so `API.Example.com` becomes `api-example-com`.++A compiled name longer than 63 characters is trimmed from the front, so the per-certificate identifier at the end always survives and two certificates can never collapse onto one GCP certificate. Use `{{shortCertificateId}}` if you want short names that stay fully readable.++## Labels++Under **Sync Options**, enable **Configure labels** to attach your own GCP labels to every certificate the sync manages. Use them to group certificates for billing, filtering, or your own inventory tooling.++Label keys must start with a lowercase letter and contain only lowercase letters, digits, hyphens and underscores, up to 63 characters. Values follow the same character rules and may be empty. You can set up to 62 labels.++Infisical always adds two labels of its own, which you cannot override:++- `managed-by: infisical` marks the certificate as managed by this sync.+- `infisical-certificate-id` records the Infisical certificate ID, so you can find a certificate in GCP with `gcloud certificate-manager certificates list --filter="labels.infisical-certificate-id=CERTIFICATE_ID"`.++## Scopes++The scope is set when Infisical creates each certificate and is immutable in GCP, so pick the one matching how the certificate will be served. Certificates already uploaded by an earlier sync keep the scope they were created with.++- **Default**: Global external Application Load Balancers and regional services. This is the common choice.+- **Edge Cache**: Media CDN.+- **All Regions**: Cross-region internal Application Load Balancers. Available for global certificates only.+- **Client Auth**: Backend mTLS client certificates.++<Note>+ Certificate map binding requires the **Default** scope. A certificate map entry can only reference a Default-scope certificate, so Infisical rejects the combination when you save the sync.+</Note>++## Attaching Certificates to Traffic++Uploading a certificate does not by itself serve any traffic. Something has to reference it.++For a **global** certificate, a certificate map entry maps a hostname to the certificate, and a target HTTPS proxy attaches the map. You have two options:++- **Wire it yourself once.** Create the certificate map entry pointing at the certificate Infisical created. Because renewals update that same certificate in place, you never have to touch it again.+- **Let Infisical maintain the entry.** Enable **Attach to a certificate map** and pick an existing map. Infisical creates one entry per sync, pointed at the sync's certificate, and repoints it if the certificate is replaced. This requires the Default scope.++## Certificate Renewal Behavior++**Preserve certificate on renewal** is enabled by default. An existing GCP certificate is updated in place and keeps its resource name, so certificate map entries and target proxies keep working with no change in GCP. This also pins the resource name against later edits to the certificate name schema. This is the recommended setting.++When disabled, a renewal or a name change creates a new GCP certificate and deletes the old one. If a certificate map entry references the old certificate, Infisical repoints its own entry before deleting. Anything else pointing at the old certificate has to be repointed manually, and GCP refuses to delete a certificate that is still referenced.++<Warning>+ Every certificate in the entry must cover the hostname you bind it to. GCP rejects a certificate map entry whose hostname is not in the certificate's Common Name or Subject Alternative Names, so binding `app.example.com` to a certificate issued for `web.example.com` fails at sync time. A wildcard certificate for `*.example.com` covers `app.example.com`.++ For the same reason, keep Subject Alternative Names stable across renewals when an entry matches on hostname.+</Warning>++## Supported Key Algorithms++GCP Certificate Manager accepts RSA 2048, RSA 3072, RSA 4096, ECDSA P-256 and ECDSA P-384. Certificates using any other key algorithm are skipped.++## Manual Certificate Sync++You can manually trigger certificate synchronization, which is useful for:++- Initial setup when uploading certificates for the first time+- Testing certificate sync configurations+- Forcing a sync after making changes++Use the [Sync Certificates](/api-reference/endpoints/pki/syncs/gcp-certificate-manager/sync-certificates) API endpoint or the manual sync option in the Infisical UI.++## FAQ++<AccordionGroup>+ <Accordion title="Can I import certificates from GCP back into Infisical?">+ No. GCP never returns the private key of a self-managed certificate, so importing certificates from GCP Certificate Manager into Infisical is not supported.+ </Accordion>++ <Accordion title="Why can't I change the location or scope of an existing sync?">+ A GCP certificate's location and scope are immutable, and the location is part of the certificate's resource path. Changing either on an existing sync would leave the original certificates behind, still serving traffic under the old scope. Create a new sync instead.+ </Accordion>++ <Accordion title="Why did removing a certificate fail?">+ GCP refuses to delete a certificate that is still referenced by a certificate map entry. Detach it from the map, then run the sync again.+ </Accordion>++ <Accordion title="Is this GCP Certificate Authority Service?">+ No. GCP Certificate Manager stores certificates and serves them from Google's load balancers. Certificate Authority Service is a certificate authority, which issues certificates rather than receiving them.+ </Accordion>++ <Accordion title="How many certificates can one sync push?">+ GCP allows 1,000 self-managed certificates per project for global certificates, and 100 per region for regional certificates. A sync using certificate map binding is limited to four certificates, which is the GCP limit for one certificate map entry, and every one of them has to cover the bound hostname.+ </Accordion>+</AccordionGroup>++## What's Next?++<CardGroup cols={2}>+ <Card title="AWS Certificate Manager" icon="aws" href="/documentation/platform/pki/applications/certificate-syncs/aws-certificate-manager">+ Import certificates into ACM for use with AWS services.+ </Card>+ <Card title="Auto-Renewal" icon="arrows-spin" href="/documentation/platform/pki/applications/certificates#server-driven-renewal">+ Enable automatic certificate renewal and syncing.+ </Card>+ <Card title="Alerting" icon="bell" href="/documentation/platform/pki/applications/alerting/overview">+ Get notified about certificate lifecycle events.+ </Card>+ <Card title="Other Sync Destinations" icon="arrows-rotate" href="/documentation/platform/pki/applications/certificate-syncs/overview">+ View all supported sync destinations.+ </Card>+</CardGroup>diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdxindex 228571dcfc..7889433612 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx@@ -71,6 +71,9 @@ flowchart LR<Card title="Azure Key Vault" icon="microsoft" href="/documentation/platform/pki/applications/certificate-syncs/azure-key-vault">Import certificates into Azure Key Vault.</Card>+ <Card title="GCP Certificate Manager" icon="google" href="/documentation/platform/pki/applications/certificate-syncs/gcp-certificate-manager">+ Upload certificates for Google Cloud load balancers.+ </Card><Card title="Cloudflare" icon="cloudflare" href="/documentation/platform/pki/applications/certificate-syncs/cloudflare-custom-certificate">Deploy custom SSL certificates to Cloudflare zones.</Card>diff --git a/docs/images/app-connections/gcp/service-account-certificate-sync-permission.png b/docs/images/app-connections/gcp/service-account-certificate-sync-permission.pngnew file mode 100644index 0000000000..7fed0b151eBinary files /dev/null and b/docs/images/app-connections/gcp/service-account-certificate-sync-permission.png differdiff --git a/docs/integrations/app-connections/gcp.mdx b/docs/integrations/app-connections/gcp.mdxindex 66c581a5a8..d6d4e35413 100644--- a/docs/integrations/app-connections/gcp.mdx+++ b/docs/integrations/app-connections/gcp.mdx@@ -87,6 +87,22 @@ Infisical supports [service account impersonation](https://cloud.google.com/iam/Add the required permissions for secret syncs:</Tab>+ <Tab title="Certificate Sync">+ Add the required permissions for [certificate syncs](/documentation/platform/pki/applications/certificate-syncs/gcp-certificate-manager):+ ++ Grant these roles on the project that holds your certificates, and enable the three APIs Infisical calls on that same project:++ ```bash+ gcloud services enable \+ certificatemanager.googleapis.com \+ cloudresourcemanager.googleapis.com \+ serviceusage.googleapis.com \+ --project=PROJECT_ID+ ```++ Certificate Manager Owner is only needed if you enable certificate removal on a sync.+ </Tab></Tabs>After configuring the appropriate roles, press "DONE".</Step>diff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsxindex c9e8380b5d..4de3f99649 100644--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx@@ -26,7 +26,11 @@ import {Switch} from "@app/components/v3";import { useProject } from "@app/context";-import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";+import {+ PKI_SYNC_MAP,+ PRESERVE_ARN_DESTINATIONS,+ PRESERVE_ITEM_ON_RENEWAL_DESTINATIONS+} from "@app/helpers/pkiSyncs";import {PkiSync,PkiSyncExportFormat,@@ -189,8 +193,11 @@ export const CreatePkiSyncForm = ({syncOptions: {canImportCertificates: false,canRemoveCertificates: false,- preserveArn: true,certificateNameSchema: syncOption?.defaultCertificateNameSchema,+ ...(PRESERVE_ARN_DESTINATIONS.includes(destination) && { preserveArn: true }),+ ...(PRESERVE_ITEM_ON_RENEWAL_DESTINATIONS.includes(destination) && {+ preserveItemOnRenewal: true+ }),...((destination === PkiSync.LinuxServer || destination === PkiSync.WindowsServer) && {exportFormat:destination === PkiSync.WindowsServerdiff --git a/frontend/src/components/pki-syncs/forms/GcpCertificateManagerPkiSyncFields.tsx b/frontend/src/components/pki-syncs/forms/GcpCertificateManagerPkiSyncFields.tsxnew file mode 100644index 0000000000..21d6b5c1bb--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/GcpCertificateManagerPkiSyncFields.tsx@@ -0,0 +1,378 @@+import { Controller, FieldError as TFieldError, useFormContext, useWatch } from "react-hook-form";+import { SingleValue } from "react-select";+import { AxiosError } from "axios";+import { Info, Loader2Icon } from "lucide-react";++import {+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ FilterableSelect,+ Input,+ Label,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Switch,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import {+ useGcpConnectionListCertificateManagerLocations,+ useGcpConnectionListCertificateManagerProjects,+ useGcpConnectionListCertificateMaps+} from "@app/hooks/api/appConnections/gcp/queries";+import { TGcpCertificateMap } from "@app/hooks/api/appConnections/gcp/types";+import { GcpCertificateManagerScope, PkiSync } from "@app/hooks/api/pkiSyncs";+import {+ GCP_CERTIFICATE_MANAGER_GLOBAL_LOCATION,+ GCP_CERTIFICATE_MANAGER_SCOPES+} from "@app/hooks/api/pkiSyncs/types/gcp-certificate-manager-sync";++import { TPkiSyncForm } from "./schemas/pki-sync-schema";+import { PkiSyncConnectionField } from "./PkiSyncConnectionField";++type TGcpCertificateManagerForm = TPkiSyncForm & { destination: PkiSync.GcpCertificateManager };++const resolveError = (+ fieldError: TFieldError | undefined,+ {+ isEnabled,+ isError,+ error,+ fallback+ }: { isEnabled: boolean; isError: boolean; error: unknown; fallback: string }+): TFieldError | undefined => {+ if (fieldError) return fieldError;+ if (!isEnabled || !isError) return undefined;++ return {+ type: "manual",+ message: (error as AxiosError<{ message?: string }>)?.response?.data?.message ?? fallback+ };+};++const LoadingRow = ({ label }: { label: string }) => (+ <div className="flex items-center gap-2 py-2 text-sm text-muted">+ <Loader2Icon className="size-4 animate-spin" />+ {label}+ </div>+);++export const GcpCertificateManagerPkiSyncFields = () => {+ const { control, setValue } = useFormContext<TGcpCertificateManagerForm>();++ const connectionId = useWatch({ name: "connection.id", control });+ const gcpProjectId = useWatch({ name: "destinationConfig.gcpProjectId", control });+ const location = useWatch({ name: "destinationConfig.location", control });+ const scope = useWatch({ name: "destinationConfig.scope", control });+ const certificateMapBinding = useWatch({+ name: "destinationConfig.certificateMapBinding",+ control+ });++ const isGlobal = location === GCP_CERTIFICATE_MANAGER_GLOBAL_LOCATION;+ const isDefaultScope =+ (scope ?? GcpCertificateManagerScope.Default) === GcpCertificateManagerScope.Default;+ const canBindCertificateMap = isGlobal && isDefaultScope;++ const {+ data: projects,+ isFetching: isLoadingProjects,+ isError: isProjectsError,+ error: projectsError+ } = useGcpConnectionListCertificateManagerProjects(connectionId, {+ enabled: Boolean(connectionId)+ });++ const {+ data: locations,+ isFetching: isLoadingLocations,+ isError: isLocationsError,+ error: locationsError+ } = useGcpConnectionListCertificateManagerLocations(+ { connectionId, gcpProjectId },+ { enabled: Boolean(connectionId && gcpProjectId) }+ );++ const {+ data: certificateMaps,+ isFetching: isLoadingCertificateMaps,+ isError: isCertificateMapsError,+ error: certificateMapsError+ } = useGcpConnectionListCertificateMaps(+ { connectionId, gcpProjectId },+ { enabled: Boolean(connectionId && gcpProjectId && isGlobal) }+ );++ const certificateMapBindingHelpText = (() => {+ if (!isGlobal)+ return "Certificate maps exist only for global certificates. Regional Application Load Balancers attach certificates directly to the target HTTPS proxy.";+ if (!isDefaultScope)+ return `A certificate map entry can only reference a Default-scope certificate, so this is unavailable with the ${GCP_CERTIFICATE_MANAGER_SCOPES[scope as GcpCertificateManagerScope].label} scope.`;+ return "Infisical keeps a certificate map entry pointed at this sync's certificate, so renewals need no change in GCP. Leave this off to upload certificates only.";+ })();++ const resetDestinationConfig = () => {+ setValue("destinationConfig.gcpProjectId", "");+ setValue("destinationConfig.location", "");+ setValue("destinationConfig.certificateMapBinding", undefined);+ };++ return (+ <>+ <PkiSyncConnectionField onChange={resetDestinationConfig} />++ <Controller+ name="destinationConfig.gcpProjectId"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => {+ const combinedError = resolveError(error, {+ isEnabled: Boolean(connectionId),+ isError: isProjectsError,+ error: projectsError,+ fallback: "Failed to list GCP projects. Check the connection's permissions."+ });++ return (+ <Field className="mb-4">+ <FieldLabel>+ GCP Project+ <Tooltip>+ <TooltipTrigger asChild>+ <Info />+ </TooltipTrigger>+ <TooltipContent className="max-w-sm">+ Only projects with the Certificate Manager API enabled are listed.+ </TooltipContent>+ </Tooltip>+ </FieldLabel>+ {connectionId && isLoadingProjects ? (+ <LoadingRow label="Loading projects..." />+ ) : (+ <Select+ value={value ?? ""}+ onValueChange={(newValue) => {+ onChange(newValue);+ setValue("destinationConfig.location", "");+ setValue("destinationConfig.certificateMapBinding", undefined);+ }}+ disabled={!connectionId || isLoadingProjects}+ >+ <SelectTrigger className="w-full" isError={Boolean(combinedError)}>+ <SelectValue+ placeholder={connectionId ? "Select a project" : "Select a connection first"}+ />+ </SelectTrigger>+ <SelectContent position="popper">+ {(projects ?? []).map((project) => (+ <SelectItem key={project.id} value={project.id}>+ {project.name} ({project.id})+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ <FieldError errors={[combinedError]} />+ </Field>+ );+ }}+ />++ <Controller+ name="destinationConfig.location"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => {+ const combinedError = resolveError(error, {+ isEnabled: Boolean(gcpProjectId),+ isError: isLocationsError,+ error: locationsError,+ fallback: "Failed to list Certificate Manager locations."+ });++ return (+ <Field className="mb-4">+ <FieldLabel>+ Location+ <Tooltip>+ <TooltipTrigger asChild>+ <Info />+ </TooltipTrigger>+ <TooltipContent className="max-w-sm">+ A certificate's location is immutable and cannot be changed after this sync+ is created. Use Global for global external Application Load Balancers.+ </TooltipContent>+ </Tooltip>+ </FieldLabel>+ {gcpProjectId && isLoadingLocations ? (+ <LoadingRow label="Loading locations..." />+ ) : (+ <Select+ value={value ?? ""}+ onValueChange={(newValue) => {+ onChange(newValue);+ if (newValue !== GCP_CERTIFICATE_MANAGER_GLOBAL_LOCATION) {+ setValue("destinationConfig.certificateMapBinding", undefined);+ if (scope === GcpCertificateManagerScope.AllRegions) {+ setValue("destinationConfig.scope", GcpCertificateManagerScope.Default);+ }+ }+ }}+ disabled={!gcpProjectId || isLoadingLocations}+ >+ <SelectTrigger className="w-full" isError={Boolean(combinedError)}>+ <SelectValue+ placeholder={gcpProjectId ? "Select a location" : "Select a project first"}+ />+ </SelectTrigger>+ <SelectContent position="popper">+ {(locations ?? []).map((gcpLocation) => (+ <SelectItem key={gcpLocation.locationId} value={gcpLocation.locationId}>+ {gcpLocation.locationId === GCP_CERTIFICATE_MANAGER_GLOBAL_LOCATION+ ? "Global"+ : gcpLocation.displayName}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ <FieldError errors={[combinedError]} />+ </Field>+ );+ }}+ />++ <Controller+ name="destinationConfig.scope"+ control={control}+ defaultValue={GcpCertificateManagerScope.Default}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>Scope</FieldLabel>+ <Select+ value={value ?? GcpCertificateManagerScope.Default}+ onValueChange={(nextScope) => {+ onChange(nextScope);+ if (nextScope !== GcpCertificateManagerScope.Default) {+ setValue("destinationConfig.certificateMapBinding", undefined);+ }+ }}+ disabled={!location}+ >+ <SelectTrigger className="w-full" isError={Boolean(error)}>+ <SelectValue placeholder="Select a scope" />+ </SelectTrigger>+ <SelectContent position="popper">+ {Object.values(GcpCertificateManagerScope)+ .filter((option) => isGlobal || option !== GcpCertificateManagerScope.AllRegions)+ .map((option) => (+ <SelectItem key={option} value={option}>+ {GCP_CERTIFICATE_MANAGER_SCOPES[option].label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldDescription>+ {+ GCP_CERTIFICATE_MANAGER_SCOPES[+ (value as GcpCertificateManagerScope) ?? GcpCertificateManagerScope.Default+ ].description+ }+ </FieldDescription>+ <FieldError errors={[error]} />+ </Field>+ )}+ />++ <Field className="mb-4">+ <Field orientation="horizontal">+ <FieldContent>+ <Label htmlFor="gcp-attach-certificate-map" className="flex items-center gap-1.5">+ Attach to a certificate map+ </Label>+ </FieldContent>+ <Switch+ id="gcp-attach-certificate-map"+ variant="project"+ checked={Boolean(certificateMapBinding)}+ disabled={!canBindCertificateMap}+ onCheckedChange={(isChecked) =>+ setValue(+ "destinationConfig.certificateMapBinding",+ isChecked ? { certificateMap: "" } : undefined,+ { shouldDirty: true }+ )+ }+ />+ </Field>+ <FieldDescription>{certificateMapBindingHelpText}</FieldDescription>+ </Field>++ {certificateMapBinding && canBindCertificateMap && (+ <>+ <Controller+ name="destinationConfig.certificateMapBinding.certificateMap"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => {+ const combinedError = resolveError(error, {+ isEnabled: true,+ isError: isCertificateMapsError,+ error: certificateMapsError,+ fallback: "Failed to list certificate maps."+ });++ return (+ <Field className="mb-4">+ <FieldLabel>Certificate Map</FieldLabel>+ <FieldContent>+ <FilterableSelect+ isClearable+ isLoading={isLoadingCertificateMaps}+ value={certificateMaps?.find((map) => map.name === value) ?? null}+ onChange={(option) =>+ onChange((option as SingleValue<TGcpCertificateMap>)?.name ?? "")+ }+ options={certificateMaps ?? []}+ getOptionLabel={(option) => option.name}+ getOptionValue={(option) => option.name}+ placeholder="Select a certificate map"+ isError={Boolean(combinedError)}+ />+ </FieldContent>+ <FieldDescription>+ Infisical creates entries inside this map but never creates or deletes the map+ itself.+ </FieldDescription>+ <FieldError errors={[combinedError]} />+ </Field>+ );+ }}+ />++ <Controller+ name="destinationConfig.certificateMapBinding.hostname"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>+ Hostname <span className="text-muted">(optional)</span>+ </FieldLabel>+ <Input {...field} value={field.value ?? ""} placeholder="app.example.com" />+ <FieldDescription>+ Leave empty to serve this certificate as the map's primary certificate, used+ when no hostname matches.+ </FieldDescription>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ </>+ )}+ </>+ );+};diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsxindex 8157f38415..1cb8f0ae38 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx@@ -10,6 +10,7 @@ import { AzureKeyVaultPkiSyncFields } from "./AzureKeyVaultPkiSyncFields";import { ChefPkiSyncFields } from "./ChefPkiSyncFields";import { CloudflareCustomCertificatePkiSyncFields } from "./CloudflareCustomCertificatePkiSyncFields";import { F5BigIpPkiSyncFields } from "./F5BigIpPkiSyncFields";+import { GcpCertificateManagerPkiSyncFields } from "./GcpCertificateManagerPkiSyncFields";import { KempLoadMasterPkiSyncFields } from "./KempLoadMasterPkiSyncFields";import { LinuxServerPkiSyncFields } from "./LinuxServerPkiSyncFields";import { NetScalerPkiSyncFields } from "./NetScalerPkiSyncFields";@@ -34,6 +35,8 @@ export const PkiSyncDestinationFields = () => {return <ChefPkiSyncFields />;case PkiSync.CloudflareCustomCertificate:return <CloudflareCustomCertificatePkiSyncFields />;+ case PkiSync.GcpCertificateManager:+ return <GcpCertificateManagerPkiSyncFields />;case PkiSync.NetScaler:return <NetScalerPkiSyncFields />;case PkiSync.F5BigIp:diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/GcpCertificateManagerSyncOptions.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/GcpCertificateManagerSyncOptions.tsxnew file mode 100644index 0000000000..8ae570a18c--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/GcpCertificateManagerSyncOptions.tsx@@ -0,0 +1,121 @@+import { Controller, useFieldArray, useFormContext, useWatch } from "react-hook-form";+import { Plus, Trash2 } from "lucide-react";++import {+ Button,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ IconButton,+ Input,+ Label,+ Switch+} from "@app/components/v3";+import { PkiSync } from "@app/hooks/api/pkiSyncs";++import { TPkiSyncForm } from "../schemas/pki-sync-schema";+import { PreserveItemOnRenewalField } from "./PreserveItemOnRenewalField";++type TGcpForm = TPkiSyncForm & { destination: PkiSync.GcpCertificateManager };++const GcpLabelsEditor = () => {+ const { control } = useFormContext<TGcpForm>();+ const labelFields = useFieldArray({ control, name: "syncOptions.labels" });++ return (+ <div className="mt-3 flex flex-col gap-3">+ <div className="flex flex-col gap-2">+ {labelFields.fields.map(({ id }, i) => (+ <div key={id} className="grid grid-cols-12 items-end gap-2">+ <div className="col-span-5">+ {i === 0 && <p className="mb-1 text-xs text-muted">Key</p>}+ <Controller+ control={control}+ name={`syncOptions.labels.${i}.key`}+ render={({ field, fieldState: { error } }) => (+ <>+ <Input {...field} isError={Boolean(error)} className="h-8" />+ <FieldError errors={[error]} />+ </>+ )}+ />+ </div>+ <div className="col-span-6">+ {i === 0 && <p className="mb-1 text-xs text-muted">Value (optional)</p>}+ <Controller+ control={control}+ name={`syncOptions.labels.${i}.value`}+ render={({ field, fieldState: { error } }) => (+ <>+ <Input {...field} isError={Boolean(error)} className="h-8" />+ <FieldError errors={[error]} />+ </>+ )}+ />+ </div>+ <div className="col-span-1 flex justify-end">+ <IconButton+ variant="ghost-muted"+ aria-label="Remove label"+ size="sm"+ onClick={() => labelFields.remove(i)}+ >+ <Trash2 />+ </IconButton>+ </div>+ </div>+ ))}+ </div>+ <Button+ variant="outline"+ size="xs"+ type="button"+ className="w-fit"+ onClick={() => labelFields.append({ key: "", value: "" })}+ >+ <Plus />+ Add label+ </Button>+ </div>+ );+};++export const GcpCertificateManagerSyncOptions = () => {+ const { control, setValue } = useFormContext<TGcpForm>();+ const labels = useWatch({ control, name: "syncOptions.labels" });++ return (+ <>+ <PreserveItemOnRenewalField+ label="Preserve certificate on renewal"+ description="When enabled, an existing GCP certificate is updated in place and keeps its resource name, so certificate map entries and target proxies keep working with no change in GCP. This also pins the name against later edits to the certificate name schema. When disabled, a renewal or a name change creates a new GCP certificate and deletes the old one, which requires repointing anything that referenced it."+ />+ <Field className="mb-4">+ <Field orientation="horizontal">+ <FieldContent>+ <Label htmlFor="gcp-configure-labels">Configure labels</Label>+ <FieldDescription>+ Labels applied to every certificate this sync manages, alongside the+ <span className="font-mono"> managed-by </span>+ and+ <span className="font-mono"> infisical-certificate-id </span>+ labels Infisical sets.+ </FieldDescription>+ </FieldContent>+ <Switch+ id="gcp-configure-labels"+ variant="project"+ checked={Array.isArray(labels)}+ onCheckedChange={(isChecked) =>+ setValue("syncOptions.labels", isChecked ? [{ key: "", value: "" }] : undefined, {+ shouldDirty: true+ })+ }+ />+ </Field>+ {Array.isArray(labels) && <GcpLabelsEditor />}+ </Field>+ </>+ );+};diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsxindex 4ad72157eb..9561e7400b 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx@@ -10,6 +10,7 @@ import { AwsSecretsManagerSyncOptions } from "./AwsSecretsManagerSyncOptions";import { AzureKeyVaultSyncOptions } from "./AzureKeyVaultSyncOptions";import { ChefSyncOptions } from "./ChefSyncOptions";import { F5BigIpSyncOptions } from "./F5BigIpSyncOptions";+import { GcpCertificateManagerSyncOptions } from "./GcpCertificateManagerSyncOptions";import { KempLoadMasterSyncOptions } from "./KempLoadMasterSyncOptions";import { LinuxServerSyncOptions } from "./LinuxServerSyncOptions";import { NameSchemaHoverCard } from "./NameSchemaHoverCard";@@ -34,6 +35,8 @@ const renderDestinationOptions = (currentDestination: PkiSync, isUpdate?: booleareturn <AwsSecretsManagerSyncOptions />;case PkiSync.Chef:return <ChefSyncOptions />;+ case PkiSync.GcpCertificateManager:+ return <GcpCertificateManagerSyncOptions />;case PkiSync.NetScaler:return <NetScalerSyncOptions />;case PkiSync.F5BigIp:diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsxindex b9c2716450..3962cc0e1a 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx@@ -18,6 +18,7 @@ import { useProject } from "@app/context";import {BOOLEAN_SYNC_OPTION_FIELDS,getCertificateDisplayName,+ KEY_VALUE_SYNC_OPTION_FIELDS,PKI_SYNC_MAP,truncateCertificateSerialNumber,VALUE_SYNC_OPTION_FIELDS@@ -27,8 +28,8 @@ import { useListWorkspaceCertificates } from "@app/hooks/api/projects";import { TPkiSyncForm } from "./schemas/pki-sync-schema";const ReviewFieldLabel = ({ label, children }: { label: string; children?: ReactNode }) => (- <div className="flex h-full min-w-0 flex-col justify-between gap-1">- <p className="text-xs font-medium text-muted">{label}</p>+ <div className="row-span-2 grid min-w-0 grid-rows-subgrid pb-2">+ <p className="mb-1 text-xs font-medium text-muted">{label}</p>{children ? (<div className="text-sm break-words text-foreground">{children}</div>) : (@@ -138,7 +139,7 @@ export const PkiSyncReviewFields = () => {<div className="w-full border-b border-border"><span className="text-sm text-muted">Destination</span></div>- <div className="grid grid-cols-3 gap-x-8 gap-y-4">+ <div className="grid grid-cols-3 gap-x-8"><ReviewFieldLabel label="Connection">{connection?.name}</ReviewFieldLabel><ReviewFieldLabel label="Service">{destinationName}</ReviewFieldLabel>{destinationConfig && "vaultBaseUrl" in destinationConfig && (@@ -150,7 +151,7 @@ export const PkiSyncReviewFields = () => {<div className="w-full border-b border-border"><span className="text-sm text-muted">Sync Options</span></div>- <div className="grid grid-cols-3 gap-x-8 gap-y-4">+ <div className="grid grid-cols-3 gap-x-8"><ReviewFieldLabel label="Auto-Sync"><Badge variant={isAutoSyncEnabled ? "success" : "danger"}>{isAutoSyncEnabled ? "Enabled" : "Disabled"}@@ -167,6 +168,22 @@ export const PkiSyncReviewFields = () => {</ReviewFieldLabel>);})}+ {KEY_VALUE_SYNC_OPTION_FIELDS.map(({ key, label }) => {+ const optionValue = (syncOptions as Record<string, unknown> | undefined)?.[key];+ if (!Array.isArray(optionValue) || !optionValue.length) return null;+ const pairs = optionValue as { key: string; value?: string }[];+ return (+ <ReviewFieldLabel key={key} label={label}>+ <div className="flex flex-wrap gap-1">+ {pairs.map((pair) => (+ <Badge key={pair.key} variant="neutral" isTruncatable>+ <span>{pair.value ? `${pair.key}: ${pair.value}` : pair.key}</span>+ </Badge>+ ))}+ </div>+ </ReviewFieldLabel>+ );+ })}{VALUE_SYNC_OPTION_FIELDS.map(({ key, label }) => {const optionValue = (syncOptions as Record<string, unknown> | undefined)?.[key];if (optionValue === undefined || optionValue === null || optionValue === "")@@ -191,7 +208,7 @@ export const PkiSyncReviewFields = () => {<div className="w-full border-b border-border"><span className="text-sm text-muted">Details</span></div>- <div className="grid grid-cols-3 gap-x-8 gap-y-4">+ <div className="grid grid-cols-3 gap-x-8"><ReviewFieldLabel label="Name">{name}</ReviewFieldLabel><ReviewFieldLabel label="Description">{description}</ReviewFieldLabel></div>diff --git a/frontend/src/components/pki-syncs/forms/schemas/gcp-certificate-manager-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/gcp-certificate-manager-pki-sync-destination-schema.tsnew file mode 100644index 0000000000..dcb3d718f6--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/schemas/gcp-certificate-manager-pki-sync-destination-schema.ts@@ -0,0 +1,186 @@+import { z } from "zod";++import { GcpCertificateManagerScope, PkiSync } from "@app/hooks/api/pkiSyncs";+import { GCP_CERTIFICATE_MANAGER_GLOBAL_LOCATION } from "@app/hooks/api/pkiSyncs/types/gcp-certificate-manager-sync";++import { BasePkiSyncSchema } from "./base-pki-sync-schema";++const GCP_CERTIFICATE_NAME_ALLOWED_CONTENT =+ /^([a-z0-9-]|\{\{certificateId\}\}|\{\{shortCertificateId\}\}|\{\{profileId\}\}|\{\{applicationId\}\}|\{\{applicationName\}\}|\{\{commonName\}\})*$/;++const compileTestName = (schema: string) =>+ schema+ .replace(/\{\{shortCertificateId\}\}/g, "0".repeat(22))+ .replace(/\{\{(certificateId|profileId|applicationId)\}\}/g, "0".repeat(32))+ .replace(/\{\{applicationName\}\}/g, "application-name")+ .replace(/\{\{commonName\}\}/g, "common-name");++const GCP_RESERVED_LABEL_KEYS = ["managed-by", "infisical-certificate-id"];++const GCP_NAME_LEADING_LETTER = /^[a-z]/;++const GCP_MAX_NAME_LENGTH = 63;++const GcpLabelSchema = z.object({+ key: z+ .string()+ .trim()+ .min(1, "Label key is required")+ .max(63)+ .regex(+ /^[a-z][a-z0-9_-]{0,62}$/,+ "Label keys must start with a lowercase letter and contain only lowercase letters, digits, hyphens and underscores"+ )+ .refine((value) => !GCP_RESERVED_LABEL_KEYS.includes(value), {+ message: "This label key is set by Infisical and cannot be overridden"+ }),+ value: z+ .string()+ .trim()+ .max(63)+ .regex(+ /^[a-z0-9_-]*$/,+ "Label values may contain only lowercase letters, digits, hyphens and underscores"+ )+});++const GcpCertificateManagerSyncOptionsSchema = z.object({+ canImportCertificates: z.literal(false).default(false),+ preserveItemOnRenewal: z.boolean().default(true),+ labels: GcpLabelSchema.array()+ .max(62, "At most 62 labels can be set")+ .optional()+ .superRefine((labels, ctx) => {+ if (!labels) return;+ const seen = new Set<string>();+ labels.forEach((label, index) => {+ if (seen.has(label.key)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: [index, "key"],+ message: `Duplicate label key "${label.key}"`+ });+ }+ seen.add(label.key);+ });+ }),+ certificateNameSchema: z+ .string()+ .trim()+ .min(1, "Certificate name schema is required")+ .refine(+ (value) => value.includes("{{certificateId}}") || value.includes("{{shortCertificateId}}"),+ {+ message:+ "Certificate name schema must include the {{certificateId}} or {{shortCertificateId}} placeholder so every certificate gets a unique name"+ }+ )+ .refine((value) => GCP_CERTIFICATE_NAME_ALLOWED_CONTENT.test(value), {+ message:+ "Certificate name schema may only contain lowercase letters, digits, hyphens and placeholders. GCP Certificate Manager does not allow uppercase letters, underscores or dots in a resource ID"+ })+ .refine((value) => GCP_NAME_LEADING_LETTER.test(value), {+ message:+ 'Certificate name schema must start with a lowercase letter, because GCP Certificate Manager requires a resource ID to start with a letter and a placeholder can resolve to a digit. Prefix the schema, for example "infisical-{{certificateId}}"'+ })+ .refine((value) => compileTestName(value).length <= GCP_MAX_NAME_LENGTH, {+ message: `Certificate name schema must compile to at most ${GCP_MAX_NAME_LENGTH} characters for GCP Certificate Manager`+ })+});++const GcpCertificateManagerDestinationConfigSchema = z+ .object({+ gcpProjectId: z+ .string()+ .trim()+ .min(1, "GCP project is required")+ .max(30)+ .regex(+ /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/,+ "GCP project ID must be 6-30 characters of lowercase letters, digits and hyphens"+ ),+ location: z.string().trim().min(1, "Location is required"),+ scope: z.nativeEnum(GcpCertificateManagerScope).default(GcpCertificateManagerScope.Default),+ certificateMapBinding: z+ .object({+ certificateMap: z+ .string()+ .trim()+ .min(1, "Certificate map is required")+ .max(63)+ .regex(+ /^[a-z0-9-]{1,63}$/,+ "Certificate map name must contain only lowercase letters, digits and hyphens"+ ),+ hostname: z+ .string()+ .trim()+ .max(253)+ .optional()+ .transform((value) => value || undefined)+ .refine(+ (value) =>+ value === undefined ||+ /^(\*\.)?([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/.test(value),+ 'Hostname must be a fully qualified domain name or a wildcard expression such as "*.example.com"'+ )+ })+ .optional()+ })+ .superRefine((config, ctx) => {+ if (config.certificateMapBinding && config.scope !== GcpCertificateManagerScope.Default) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["certificateMapBinding"],+ message:+ "Certificate map binding requires the Default scope. A certificate map entry can only reference a Default-scope certificate."+ });+ }++ if (config.location === GCP_CERTIFICATE_MANAGER_GLOBAL_LOCATION) return;++ if (config.scope === GcpCertificateManagerScope.AllRegions) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["scope"],+ message: `The ALL_REGIONS scope is only available for global certificates, but this sync targets "${config.location}".`+ });+ }++ if (config.certificateMapBinding) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["certificateMapBinding"],+ message:+ "Certificate map binding is only available for global certificates. Regional Application Load Balancers attach certificates directly to the target HTTPS proxy."+ });+ }+ });++export const GcpCertificateManagerPkiSyncDestinationSchema = BasePkiSyncSchema(+ GcpCertificateManagerSyncOptionsSchema+).merge(+ z.object({+ destination: z.literal(PkiSync.GcpCertificateManager),+ destinationConfig: GcpCertificateManagerDestinationConfigSchema+ })+);++export const UpdateGcpCertificateManagerPkiSyncDestinationSchema =+ GcpCertificateManagerPkiSyncDestinationSchema.partial().merge(+ z.object({+ name: z+ .string()+ .trim()+ .min(1, "Name is required")+ .max(255, "Name must be less than 255 characters"),+ destination: z.literal(PkiSync.GcpCertificateManager),+ connection: z.object({+ id: z.string().uuid("Invalid connection ID format"),+ name: z+ .string()+ .min(1, "Connection name is required")+ .max(255, "Connection name must be less than 255 characters")+ })+ })+ );diff --git a/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.tsindex b81ec13014..ae530fd299 100644--- a/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts@@ -1,6 +1,7 @@import { z } from "zod";import { PkiSync, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";+import { GCP_MAX_CERTIFICATES_PER_MAP_ENTRY } from "@app/hooks/api/pkiSyncs/types/gcp-certificate-manager-sync";import {AwsCertificateManagerPkiSyncDestinationSchema,@@ -30,6 +31,10 @@ import {F5BigIpPkiSyncDestinationSchema,UpdateF5BigIpPkiSyncDestinationSchema} from "./f5-big-ip-pki-sync-destination-schema";+import {+ GcpCertificateManagerPkiSyncDestinationSchema,+ UpdateGcpCertificateManagerPkiSyncDestinationSchema+} from "./gcp-certificate-manager-pki-sync-destination-schema";import {KempLoadMasterPkiSyncDestinationSchema,UpdateKempLoadMasterPkiSyncDestinationSchema@@ -58,6 +63,7 @@ const PkiSyncUnionSchema = z.discriminatedUnion("destination", [AwsSecretsManagerPkiSyncDestinationSchema,ChefPkiSyncDestinationSchema,CloudflareCustomCertificatePkiSyncDestinationSchema,+ GcpCertificateManagerPkiSyncDestinationSchema,NetScalerPkiSyncDestinationSchema,F5BigIpPkiSyncDestinationSchema,KempLoadMasterPkiSyncDestinationSchema,@@ -73,6 +79,7 @@ const UpdatePkiSyncUnionSchema = z.discriminatedUnion("destination", [UpdateAwsSecretsManagerPkiSyncDestinationSchema,UpdateChefPkiSyncDestinationSchema,UpdateCloudflareCustomCertificatePkiSyncDestinationSchema,+ UpdateGcpCertificateManagerPkiSyncDestinationSchema,UpdateNetScalerPkiSyncDestinationSchema,UpdateF5BigIpPkiSyncDestinationSchema,UpdateKempLoadMasterPkiSyncDestinationSchema,@@ -82,6 +89,18 @@ const UpdatePkiSyncUnionSchema = z.discriminatedUnion("destination", []);export const PkiSyncFormSchema = PkiSyncUnionSchema.superRefine((data, ctx) => {+ if (+ data.destination === PkiSync.GcpCertificateManager &&+ data.destinationConfig?.certificateMapBinding &&+ (data.certificateIds?.length ?? 0) > GCP_MAX_CERTIFICATES_PER_MAP_ENTRY+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["destinationConfig", "certificateMapBinding"],+ message: `Certificate map binding supports up to ${GCP_MAX_CERTIFICATES_PER_MAP_ENTRY} certificates, which is the GCP limit for one certificate map entry.`+ });+ }+if ((data.destination === PkiSync.WindowsServer || data.destination === PkiSync.LinuxServer) &&data.syncOptions?.exportFormat === PkiSyncExportFormat.Pkcs12 &&diff --git a/frontend/src/helpers/pkiSyncs.ts b/frontend/src/helpers/pkiSyncs.tsindex 376b6a46a5..7359ab329a 100644--- a/frontend/src/helpers/pkiSyncs.ts+++ b/frontend/src/helpers/pkiSyncs.ts@@ -40,6 +40,12 @@ export const PKI_SYNC_MAP: Record<category: "Infrastructure",description: "Sync certificates to a Chef data bag."},+ [PkiSync.GcpCertificateManager]: {+ name: "GCP Certificate Manager",+ image: "Google Cloud Platform.png",+ category: "GCP",+ description: "Sync certificates to GCP Certificate Manager."+ },[PkiSync.CloudflareCustomCertificate]: {name: "Cloudflare Custom SSL",image: "Cloudflare.png",@@ -117,6 +123,7 @@ export const PKI_SYNC_CONNECTION_MAP: Record<PkiSync, AppConnection> = {[PkiSync.AwsSecretsManager]: AppConnection.AWS,[PkiSync.AwsElasticLoadBalancer]: AppConnection.AWS,[PkiSync.Chef]: AppConnection.Chef,+ [PkiSync.GcpCertificateManager]: AppConnection.GCP,[PkiSync.CloudflareCustomCertificate]: AppConnection.Cloudflare,[PkiSync.NetScaler]: AppConnection.NetScaler,[PkiSync.F5BigIp]: AppConnection.F5BigIp,@@ -139,6 +146,21 @@ export const BOOLEAN_SYNC_OPTION_FIELDS = [{ key: "includePrivateKey", label: "Include Private Key" }] as const;+export const KEY_VALUE_SYNC_OPTION_FIELDS = [{ key: "labels", label: "Labels" }] as const;++export const PRESERVE_ARN_DESTINATIONS: PkiSync[] = [+ PkiSync.AwsCertificateManager,+ PkiSync.AwsElasticLoadBalancer+];++export const PRESERVE_ITEM_ON_RENEWAL_DESTINATIONS: PkiSync[] = [+ PkiSync.Chef,+ PkiSync.F5BigIp,+ PkiSync.GcpCertificateManager,+ PkiSync.KempLoadMaster,+ PkiSync.NetScaler+];+export const VALUE_SYNC_OPTION_FIELDS = [{ key: "certificateNameSchema", label: "Certificate Name Schema" },{ key: "caCertificateNameSchema", label: "CA Certificate Name Schema" },diff --git a/frontend/src/hooks/api/appConnections/gcp/queries.tsx b/frontend/src/hooks/api/appConnections/gcp/queries.tsxindex c8535aae1b..ab777db7fa 100644--- a/frontend/src/hooks/api/appConnections/gcp/queries.tsx+++ b/frontend/src/hooks/api/appConnections/gcp/queries.tsx@@ -3,14 +3,34 @@ import { useQuery, UseQueryOptions } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";import { appConnectionKeys } from "../queries";-import { TGcpLocation, TGcpProject, TListProjectLocations } from "./types";+import {+ TGcpCertificateMap,+ TGcpLocation,+ TGcpProject,+ TListCertificateManagerResources,+ TListProjectLocations+} from "./types";const gcpConnectionKeys = {all: [...appConnectionKeys.all, "gcp"] as const,listProjects: (connectionId: string) =>[...gcpConnectionKeys.all, "projects", connectionId] as const,listProjectLocations: ({ projectId, connectionId }: TListProjectLocations) =>- [...gcpConnectionKeys.all, "project-locations", connectionId, projectId] as const+ [...gcpConnectionKeys.all, "project-locations", connectionId, projectId] as const,+ listCertificateManagerProjects: (connectionId: string) =>+ [...gcpConnectionKeys.all, "certificate-manager-projects", connectionId] as const,+ listCertificateManagerLocations: ({+ connectionId,+ gcpProjectId+ }: TListCertificateManagerResources) =>+ [+ ...gcpConnectionKeys.all,+ "certificate-manager-locations",+ connectionId,+ gcpProjectId+ ] as const,+ listCertificateMaps: ({ connectionId, gcpProjectId }: TListCertificateManagerResources) =>+ [...gcpConnectionKeys.all, "certificate-maps", connectionId, gcpProjectId] as const};export const useGcpConnectionListProjects = (@@ -63,3 +83,80 @@ export const useGcpConnectionListProjectLocations = (...options});};++export const useGcpConnectionListCertificateManagerProjects = (+ connectionId: string,+ options?: Omit<+ UseQueryOptions<+ TGcpProject[],+ unknown,+ TGcpProject[],+ ReturnType<typeof gcpConnectionKeys.listCertificateManagerProjects>+ >,+ "queryKey" | "queryFn"+ >+) => {+ return useQuery({+ queryKey: gcpConnectionKeys.listCertificateManagerProjects(connectionId),+ queryFn: async () => {+ const { data } = await apiRequest.get<TGcpProject[]>(+ `/api/v1/app-connections/gcp/${connectionId}/certificate-manager-projects`+ );++ return data;+ },+ ...options+ });+};++export const useGcpConnectionListCertificateManagerLocations = (+ { connectionId, gcpProjectId }: TListCertificateManagerResources,+ options?: Omit<+ UseQueryOptions<+ TGcpLocation[],+ unknown,+ TGcpLocation[],+ ReturnType<typeof gcpConnectionKeys.listCertificateManagerLocations>+ >,+ "queryKey" | "queryFn"+ >+) => {+ return useQuery({+ queryKey: gcpConnectionKeys.listCertificateManagerLocations({ connectionId, gcpProjectId }),+ queryFn: async () => {+ const { data } = await apiRequest.get<TGcpLocation[]>(+ `/api/v1/app-connections/gcp/${connectionId}/certificate-manager-locations`,+ { params: { gcpProjectId } }+ );++ return data;+ },+ ...options+ });+};++export const useGcpConnectionListCertificateMaps = (+ { connectionId, gcpProjectId }: TListCertificateManagerResources,+ options?: Omit<+ UseQueryOptions<+ TGcpCertificateMap[],+ unknown,+ TGcpCertificateMap[],+ ReturnType<typeof gcpConnectionKeys.listCertificateMaps>+ >,+ "queryKey" | "queryFn"+ >+) => {+ return useQuery({+ queryKey: gcpConnectionKeys.listCertificateMaps({ connectionId, gcpProjectId }),+ queryFn: async () => {+ const { data } = await apiRequest.get<TGcpCertificateMap[]>(+ `/api/v1/app-connections/gcp/${connectionId}/certificate-maps`,+ { params: { gcpProjectId } }+ );++ return data;+ },+ ...options+ });+};diff --git a/frontend/src/hooks/api/appConnections/gcp/types.ts b/frontend/src/hooks/api/appConnections/gcp/types.tsindex c5b594446e..0040d9b342 100644--- a/frontend/src/hooks/api/appConnections/gcp/types.ts+++ b/frontend/src/hooks/api/appConnections/gcp/types.ts@@ -12,3 +12,13 @@ export type TGcpLocation = {displayName: string;locationId: string;};++export type TListCertificateManagerResources = {+ connectionId: string;+ gcpProjectId: string;+};++export type TGcpCertificateMap = {+ name: string;+ description?: string;+};diff --git a/frontend/src/hooks/api/pkiSyncs/enums.ts b/frontend/src/hooks/api/pkiSyncs/enums.tsindex 10f2bd2cb2..158e098971 100644--- a/frontend/src/hooks/api/pkiSyncs/enums.ts+++ b/frontend/src/hooks/api/pkiSyncs/enums.ts@@ -4,6 +4,7 @@ export enum PkiSync {AwsSecretsManager = "aws-secrets-manager",AwsElasticLoadBalancer = "aws-elastic-load-balancer",Chef = "chef",+ GcpCertificateManager = "gcp-certificate-manager",CloudflareCustomCertificate = "cloudflare-custom-certificate",NetScaler = "netscaler",F5BigIp = "f5-big-ip",diff --git a/frontend/src/hooks/api/pkiSyncs/types/gcp-certificate-manager-sync.ts b/frontend/src/hooks/api/pkiSyncs/types/gcp-certificate-manager-sync.tsnew file mode 100644index 0000000000..286e17862d--- /dev/null+++ b/frontend/src/hooks/api/pkiSyncs/types/gcp-certificate-manager-sync.ts@@ -0,0 +1,63 @@+import { AppConnection } from "@app/hooks/api/appConnections/enums";++import { PkiSync } from "../enums";+import { RootPkiSyncOptions, TRootPkiSync } from "./common";++export const GCP_CERTIFICATE_MANAGER_GLOBAL_LOCATION = "global";++export const GCP_MAX_CERTIFICATES_PER_MAP_ENTRY = 4;++export enum GcpCertificateManagerScope {+ Default = "default",+ EdgeCache = "edge-cache",+ AllRegions = "all-regions",+ ClientAuth = "client-auth"+}++export const GCP_CERTIFICATE_MANAGER_SCOPES: Record<+ GcpCertificateManagerScope,+ { label: string; description: string }+> = {+ [GcpCertificateManagerScope.Default]: {+ label: "Default",+ description: "Global external Application Load Balancers and regional services."+ },+ [GcpCertificateManagerScope.EdgeCache]: {+ label: "Edge Cache",+ description: "Media CDN."+ },+ [GcpCertificateManagerScope.AllRegions]: {+ label: "All Regions",+ description: "Cross-region internal Application Load Balancers. Global certificates only."+ },+ [GcpCertificateManagerScope.ClientAuth]: {+ label: "Client Authentication",+ description: "Backend mTLS client certificates."+ }+};++export type TGcpLabel = {+ key: string;+ value: string;+};++export type TGcpCertificateManagerPkiSync = TRootPkiSync & {+ destination: PkiSync.GcpCertificateManager;+ destinationConfig: {+ gcpProjectId: string;+ location: string;+ scope: GcpCertificateManagerScope;+ certificateMapBinding?: {+ certificateMap: string;+ hostname?: string;+ };+ };+ syncOptions: RootPkiSyncOptions & {+ labels?: TGcpLabel[];+ };+ connection: {+ app: AppConnection.GCP;+ name: string;+ id: string;+ };+};diff --git a/frontend/src/hooks/api/pkiSyncs/types/index.ts b/frontend/src/hooks/api/pkiSyncs/types/index.tsindex ff30359bad..b46bc90ccc 100644--- a/frontend/src/hooks/api/pkiSyncs/types/index.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/index.ts@@ -7,6 +7,11 @@ import { TAzureKeyVaultPkiSync } from "./azure-key-vault-sync";import { TChefPkiSync } from "./chef-sync";import { TCloudflareCustomCertificatePkiSync } from "./cloudflare-custom-certificate-sync";import { TF5BigIpPkiSync } from "./f5-big-ip-sync";+import {+ GcpCertificateManagerScope,+ TGcpCertificateManagerPkiSync,+ TGcpLabel+} from "./gcp-certificate-manager-sync";import { TKempLoadMasterPkiSync } from "./kemp-loadmaster-sync";import { TLinuxServerPkiSync } from "./linux-server-sync";import { TNetScalerPkiSync } from "./netscaler-sync";@@ -35,6 +40,7 @@ export type TPkiSync =| TAwsElasticLoadBalancerPkiSync| TChefPkiSync| TCloudflareCustomCertificatePkiSync+ | TGcpCertificateManagerPkiSync| TNetScalerPkiSync| TF5BigIpPkiSync| TKempLoadMasterPkiSync@@ -70,6 +76,7 @@ type TCreatePkiSyncDTOBase = {certificateChain: string;caCertificate: string;};+ labels?: TGcpLabel[];};credentials?: {exportPassword?: string;@@ -104,10 +111,17 @@ export type TCreatePkiSyncDTO = TCreatePkiSyncDTOBase & {clusterId?: string;clusterName?: string;destinationPath?: string;+ gcpProjectId?: string;+ location?: string;+ scope?: GcpCertificateManagerScope;+ certificateMapBinding?: {+ certificateMap: string;+ hostname?: string;+ };};};-export type TUpdatePkiSyncDTO = Partial<Omit<TCreatePkiSyncDTO, "projectId">> & {+export type TUpdatePkiSyncDTO = Partial<Omit<TCreatePkiSyncDTO, "projectId" | "certificateIds">> & {syncId: string;projectId: string;};@@ -144,6 +158,7 @@ export * from "./chef-sync";export * from "./cloudflare-custom-certificate-sync";export * from "./common";export * from "./f5-big-ip-sync";+export * from "./gcp-certificate-manager-sync";export * from "./kemp-loadmaster-sync";export * from "./linux-server-sync";export * from "./netscaler-sync";diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsxindex 1974dec278..3e26d380ce 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx@@ -21,8 +21,8 @@ import {} from "@app/components/v2";import { ROUTE_PATHS } from "@app/const/routes";import { useOrganization, useProject } from "@app/context";+import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";import {- PkiSync,useAddCertificatesToPkiSync,useListPkiSyncsWithCertificate,useRemoveCertificatesFromPkiSync@@ -120,17 +120,6 @@ export const CertificateManagePkiSyncsModal = ({handleClose();};- const getDestinationDisplayName = (destination: string) => {- switch (destination) {- case PkiSync.AzureKeyVault:- return "Azure Key Vault";- case PkiSync.AwsCertificateManager:- return "AWS Certificate Manager";- default:- return destination;- }- };-useEffect(() => {if (!certificateId || !pkiSyncs || pkiSyncs.length === 0) return;@@ -271,9 +260,9 @@ export const CertificateManagePkiSyncsModal = ({<Td className="w-1/2 max-w-0"><divclassName="truncate capitalize"- title={getDestinationDisplayName(sync.destination)}+ title={PKI_SYNC_MAP[sync.destination].name}>- {getDestinationDisplayName(sync.destination)}+ {PKI_SYNC_MAP[sync.destination].name}</div></Td></Tr>diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsxindex aa003b021f..8e03be0bbd 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx@@ -11,6 +11,7 @@ import {AzureKeyVaultPkiSyncDestinationSection,ChefPkiSyncDestinationSection,F5BigIpPkiSyncDestinationSection,+ GcpCertificateManagerPkiSyncDestinationSection,KempLoadMasterPkiSyncDestinationSection,LinuxServerPkiSyncDestinationSection,NetScalerPkiSyncDestinationSection,@@ -44,6 +45,9 @@ export const PkiSyncDestinationSection = ({ pkiSync }: Props) => {case PkiSync.Chef:DestinationComponents = <ChefPkiSyncDestinationSection pkiSync={pkiSync} />;break;+ case PkiSync.GcpCertificateManager:+ DestinationComponents = <GcpCertificateManagerPkiSyncDestinationSection pkiSync={pkiSync} />;+ break;case PkiSync.NetScaler:DestinationComponents = <NetScalerPkiSyncDestinationSection pkiSync={pkiSync} />;break;diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/GcpCertificateManagerPkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/GcpCertificateManagerPkiSyncDestinationSection.tsxnew file mode 100644index 0000000000..875e5b4fea--- /dev/null+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/GcpCertificateManagerPkiSyncDestinationSection.tsx@@ -0,0 +1,90 @@+import {+ Badge,+ ButtonGroup,+ Detail,+ DetailLabel,+ DetailValue,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import {+ GCP_CERTIFICATE_MANAGER_GLOBAL_LOCATION,+ GCP_CERTIFICATE_MANAGER_SCOPES,+ TGcpCertificateManagerPkiSync+} from "@app/hooks/api/pkiSyncs/types/gcp-certificate-manager-sync";++type Props = {+ pkiSync: TGcpCertificateManagerPkiSync;+};++export const GcpCertificateManagerPkiSyncDestinationSection = ({ pkiSync }: Props) => {+ const { gcpProjectId, location, scope, certificateMapBinding } = pkiSync.destinationConfig;+ const { labels } = pkiSync.syncOptions;++ return (+ <>+ <Detail>+ <DetailLabel>GCP Project</DetailLabel>+ <DetailValue>{gcpProjectId}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Location</DetailLabel>+ <DetailValue>+ <Badge variant="neutral">+ {location === GCP_CERTIFICATE_MANAGER_GLOBAL_LOCATION ? "Global" : location}+ </Badge>+ </DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Scope</DetailLabel>+ <DetailValue>+ <Badge variant="neutral">{GCP_CERTIFICATE_MANAGER_SCOPES[scope]?.label ?? scope}</Badge>+ </DetailValue>+ </Detail>+ {certificateMapBinding && (+ <>+ <Detail>+ <DetailLabel>Certificate Map</DetailLabel>+ <DetailValue>{certificateMapBinding.certificateMap}</DetailValue>+ </Detail>+ {certificateMapBinding.hostname && (+ <Detail>+ <DetailLabel>Hostname</DetailLabel>+ <DetailValue>{certificateMapBinding.hostname}</DetailValue>+ </Detail>+ )}+ </>+ )}+ {labels?.length ? (+ <Detail>+ <DetailLabel>Labels</DetailLabel>+ <DetailValue className="flex flex-wrap gap-2">+ {labels.map(({ key, value }) => (+ <ButtonGroup className="min-w-0" key={key}>+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge isTruncatable>+ <span>{key}</span>+ </Badge>+ </TooltipTrigger>+ <TooltipContent className="max-w-sm break-all">{key}</TooltipContent>+ </Tooltip>+ {value ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="outline" isTruncatable>+ <span>{value}</span>+ </Badge>+ </TooltipTrigger>+ <TooltipContent className="max-w-sm break-all">{value}</TooltipContent>+ </Tooltip>+ ) : null}+ </ButtonGroup>+ ))}+ </DetailValue>+ </Detail>+ ) : null}+ </>+ );+};diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.tsindex 19548b19ec..f5e9966832 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts@@ -4,6 +4,7 @@ export { AwsSecretsManagerPkiSyncDestinationSection } from "./AwsSecretsManagerPexport { AzureKeyVaultPkiSyncDestinationSection } from "./AzureKeyVaultPkiSyncDestinationSection";export { ChefPkiSyncDestinationSection } from "./ChefPkiSyncDestinationSection";export { F5BigIpPkiSyncDestinationSection } from "./F5BigIpPkiSyncDestinationSection";+export { GcpCertificateManagerPkiSyncDestinationSection } from "./GcpCertificateManagerPkiSyncDestinationSection";export { KempLoadMasterPkiSyncDestinationSection } from "./KempLoadMasterPkiSyncDestinationSection";export { LinuxServerPkiSyncDestinationSection } from "./LinuxServerPkiSyncDestinationSection";export { NetScalerPkiSyncDestinationSection } from "./NetScalerPkiSyncDestinationSection";