Skip to content

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

Address PR comments

Carlos Monastyrski666abcf5dd86
diff --git a/.infisicalignore b/.infisicalignore
index b1e9c0dcc7..b61e98cd84 100644
--- a/.infisicalignore
+++ b/.infisicalignore
@@ -66,3 +66,4 @@ backend/src/ee/services/honey-token/honey-token-service.ts:generic-api-key:49
docs/integrations/app-connections/ovh.mdx:private-key:84
docs/integrations/app-connections/datadog.mdx:generic-api-key:161
docs/integrations/app-connections/qovery.mdx:generic-api-key:96
+backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-reconcile.test.ts:private-key:38
diff --git a/backend/src/db/migrations/20260827142317_pki-syncs-increase-message-length.ts b/backend/src/db/migrations/20260827142317_pki-syncs-increase-message-length.ts
new file mode 100644
index 0000000000..74184f9fdc
--- /dev/null
+++ b/backend/src/db/migrations/20260827142317_pki-syncs-increase-message-length.ts
@@ -0,0 +1,17 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PkiSync)) {
+ await knex.schema.alterTable(TableName.PkiSync, (t) => {
+ t.string("lastSyncMessage", 1024).alter();
+ t.string("lastImportMessage", 1024).alter();
+ t.string("lastRemoveMessage", 1024).alter();
+ });
+ }
+}
+
+export async function down(): Promise<void> {
+ // No down migration or it will error
+}
diff --git a/backend/src/services/app-connection/gcp/gcp-connection-service.ts b/backend/src/services/app-connection/gcp/gcp-connection-service.ts
index f28e0cf5e8..e56c28e525 100644
--- a/backend/src/services/app-connection/gcp/gcp-connection-service.ts
+++ b/backend/src/services/app-connection/gcp/gcp-connection-service.ts
@@ -10,9 +10,8 @@ import {
getGcpSecretManagerProjects
} from "./gcp-connection-fns";
import {
+ TGcpCertificateManagerProjectScopedDTO,
TGcpConnection,
- TGetGcpCertificateManagerLocationsDTO,
- TGetGcpCertificateMapsDTO,
TGetGCPProjectLocationsDTO
} from "./gcp-connection-types";
@@ -63,7 +62,7 @@ export const gcpConnectionService = (getAppConnection: TGetAppConnectionFunc) =>
};
const listCertificateManagerLocations = async (
- { connectionId, gcpProjectId }: TGetGcpCertificateManagerLocationsDTO,
+ { connectionId, gcpProjectId }: TGcpCertificateManagerProjectScopedDTO,
actor: OrgServiceActor
) => {
const appConnection = await getAppConnection(AppConnection.GCP, connectionId, actor);
@@ -77,7 +76,7 @@ export const gcpConnectionService = (getAppConnection: TGetAppConnectionFunc) =>
};
const listCertificateMaps = async (
- { connectionId, gcpProjectId }: TGetGcpCertificateMapsDTO,
+ { connectionId, gcpProjectId }: TGcpCertificateManagerProjectScopedDTO,
actor: OrgServiceActor
) => {
const appConnection = await getAppConnection(AppConnection.GCP, connectionId, actor);
diff --git a/backend/src/services/app-connection/gcp/gcp-connection-types.ts b/backend/src/services/app-connection/gcp/gcp-connection-types.ts
index 8d6a8ec19c..966db3d97c 100644
--- a/backend/src/services/app-connection/gcp/gcp-connection-types.ts
+++ b/backend/src/services/app-connection/gcp/gcp-connection-types.ts
@@ -70,12 +70,7 @@ export type GCPGetCertificateMapsRes = {
nextPageToken?: string;
};
-export type TGetGcpCertificateManagerLocationsDTO = {
- connectionId: string;
- gcpProjectId: string;
-};
-
-export type TGetGcpCertificateMapsDTO = {
+export type TGcpCertificateManagerProjectScopedDTO = {
connectionId: string;
gcpProjectId: string;
};
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.ts
index 16b763f9e6..67fd8d80c9 100644
--- 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.ts
@@ -6,6 +6,12 @@ import {
isCertificateInUseError,
mapGcpError
} from "./gcp-certificate-manager-pki-sync-client";
+import {
+ gcpCertificateMapEntryPermission,
+ gcpCertificateMapPermission,
+ gcpCertificatePermission
+} from "./gcp-certificate-manager-pki-sync-constants";
+import { GcpCertificateManagerAction } from "./gcp-certificate-manager-pki-sync-enums";
const googleError = (httpStatus: number, status: string, message: string) => {
const error = new AxiosError(message);
@@ -25,15 +31,38 @@ 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"
+ permission: gcpCertificatePermission(GcpCertificateManagerAction.Create)
});
expect(mapped.shouldRetry).toBe(false);
- expect(mapped.message).toContain("certificatemanager.certificates.create");
+ expect(mapped.message).toContain("certificatemanager.certs.create");
expect(mapped.message).toContain("my-prod-project");
expect(mapped.message).toContain("roles/certificatemanager.editor");
});
+ test("uses the permission IDs GCP actually publishes", () => {
+ expect(gcpCertificatePermission(GcpCertificateManagerAction.Delete)).toBe("certificatemanager.certs.delete");
+ expect(gcpCertificateMapPermission(GcpCertificateManagerAction.Get)).toBe("certificatemanager.certmaps.get");
+ expect(gcpCertificateMapEntryPermission(GcpCertificateManagerAction.Create)).toBe(
+ "certificatemanager.certmapentries.create"
+ );
+ });
+
+ test("asks for the owner role when the denied permission is a delete", () => {
+ const denied = (permission: string) =>
+ mapGcpError(googleError(403, "PERMISSION_DENIED", "caller lacks permission"), { ...context, permission }).message;
+
+ expect(denied(gcpCertificatePermission(GcpCertificateManagerAction.Delete))).toContain(
+ "roles/certificatemanager.owner"
+ );
+ expect(denied(gcpCertificateMapEntryPermission(GcpCertificateManagerAction.Delete))).toContain(
+ "roles/certificatemanager.owner"
+ );
+ expect(denied(gcpCertificateMapEntryPermission(GcpCertificateManagerAction.Update))).toContain(
+ "roles/certificatemanager.editor"
+ );
+ });
+
test("detects a disabled Certificate Manager API", () => {
const mapped = mapGcpError(
googleError(
@@ -122,19 +151,27 @@ 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"';
+ const map = (error: unknown) =>
+ mapGcpError(error, {
+ operation: "certificate map entry creation",
+ gcpProjectId: "crested-trilogy-457818-q2",
+ resource: 'certificate map entry "infisical-3b223ee0-917a-40fa-a6b9-e59e995b1b28"',
+ permission: gcpCertificateMapEntryPermission(GcpCertificateManagerAction.Create)
+ });
+
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"
- });
+ ])("%s fits the column", (_label, error) => {
+ expect(map(error).message.length).toBeLessThanOrEqual(1024);
+ });
- expect(mapped.message.length).toBeLessThanOrEqual(255);
+ test.each([
+ ["INVALID_ARGUMENT", googleError(400, "INVALID_ARGUMENT", longGoogleMessage)],
+ ["unmapped status", googleError(500, "INTERNAL", longGoogleMessage)]
+ ])("%s keeps Google's reason instead of truncating it away", (_label, error) => {
+ expect(map(error).message).toContain("does not cover map entry hostname");
});
});
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.ts
index 8e1565a787..525cd9ad56 100644
--- 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.ts
@@ -15,9 +15,14 @@ import {
GCP_OPERATION_POLL_TIMEOUT_MS,
GCP_PRIMARY_MATCHER,
GCP_RATE_LIMIT_CONFIG,
- GCP_SCOPE_API_VALUES
+ GCP_SCOPE_API_VALUES,
+ gcpCertificatePermission
} from "./gcp-certificate-manager-pki-sync-constants";
-import { GcpCertificateManagerScope } from "./gcp-certificate-manager-pki-sync-enums";
+import {
+ GcpCertificateManagerAction,
+ GcpCertificateManagerScope,
+ GcpErrorStatus
+} from "./gcp-certificate-manager-pki-sync-enums";
import {
TGcpCertificate,
TGcpCertificateMapEntry,
@@ -34,11 +39,6 @@ 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;
@@ -61,6 +61,11 @@ export const getGcpErrorStatus = (error: unknown) => getGoogleError(error)?.stat
export const getGcpHttpStatus = (error: unknown) => getGoogleError(error)?.httpStatus;
+const roleGranting = (permission: string) =>
+ permission.endsWith(`.${GcpCertificateManagerAction.Delete}`)
+ ? "roles/certificatemanager.owner"
+ : "roles/certificatemanager.editor";
+
export const mapGcpError = (
error: unknown,
context: { operation: string; gcpProjectId: string; resource?: string; permission?: string }
@@ -69,9 +74,7 @@ export const mapGcpError = (
if (!details) {
return new PkiSyncError({
- message: cap(
- `GCP Certificate Manager ${context.operation} failed: ${error instanceof Error ? error.message : String(error)}`
- ),
+ message: `GCP Certificate Manager ${context.operation} failed: ${error instanceof Error ? error.message : String(error)}`,
cause: error instanceof Error ? error : undefined,
context
});
@@ -80,53 +83,54 @@ export const mapGcpError = (
const { httpStatus, status, message } = details;
const resourceSuffix = context.resource ? ` for ${context.resource}` : "";
- if (status === "PERMISSION_DENIED" || httpStatus === 403) {
+ if (status === GcpErrorStatus.PermissionDenied || 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.`
- ),
+ message: `The Certificate Manager API is not enabled on GCP project "${context.gcpProjectId}". Enable certificatemanager.googleapis.com and try again.`,
context
});
}
+ const permission = context.permission ?? gcpCertificatePermission(GcpCertificateManagerAction.Get);
+
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.`
- ),
+ message: `The app connection's service account is missing the "${permission}" permission on GCP project "${context.gcpProjectId}". Grant ${roleGranting(permission)} and try again.`,
context
});
}
- if (status === "NOT_FOUND" || httpStatus === 404) {
+ if (status === GcpErrorStatus.NotFound || 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.`
- ),
+ message: `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) {
+ if (status === GcpErrorStatus.ResourceExhausted || httpStatus === 429 || httpStatus === 503) {
return new PkiSyncError({
- message: cap(`GCP Certificate Manager rate limited the ${context.operation} request. Infisical will retry.`),
+ message: `GCP Certificate Manager rate limited the ${context.operation} request. Infisical will retry.`,
context
});
}
- if (status === "FAILED_PRECONDITION" || status === "INVALID_ARGUMENT" || httpStatus === 400 || httpStatus === 409) {
+ if (
+ status === GcpErrorStatus.FailedPrecondition ||
+ status === GcpErrorStatus.InvalidArgument ||
+ httpStatus === 400 ||
+ httpStatus === 409
+ ) {
return new PkiSyncError({
shouldRetry: false,
- message: cap(`GCP rejected the ${context.operation}: ${message}${resourceSuffix}`),
+ message: `GCP rejected the ${context.operation}: ${message}${resourceSuffix}`,
context: { ...context, googleMessage: message }
});
}
return new PkiSyncError({
- message: cap(`GCP Certificate Manager ${context.operation} failed${resourceSuffix}: ${message}`),
+ message: `GCP Certificate Manager ${context.operation} failed${resourceSuffix}: ${message}`,
context
});
};
@@ -134,7 +138,11 @@ export const mapGcpError = (
export const isCertificateInUseError = (error: unknown) => {
const details = getGoogleError(error);
if (!details) return false;
- if (details.status !== "FAILED_PRECONDITION" && details.httpStatus !== 400 && details.httpStatus !== 409) {
+ if (
+ details.status !== GcpErrorStatus.FailedPrecondition &&
+ details.httpStatus !== 400 &&
+ details.httpStatus !== 409
+ ) {
return false;
}
@@ -309,7 +317,7 @@ export const createGcpCertificateManagerClient = ({
);
await awaitOperation(data, `certificate creation (${certificateId})`);
} catch (error) {
- if (getGcpErrorStatus(error) !== "ALREADY_EXISTS" && getGcpHttpStatus(error) !== 409) throw error;
+ if (getGcpErrorStatus(error) !== GcpErrorStatus.AlreadyExists && getGcpHttpStatus(error) !== 409) throw error;
await patchCertificate();
}
};
@@ -332,6 +340,23 @@ export const createGcpCertificateManagerClient = ({
logContext: { certificateMap }
});
+ const getCertificateMapEntry = async (certificateMap: string, entryId: string) => {
+ try {
+ const { data } = await withRateLimitRetry(
+ () =>
+ request.get<TGcpCertificateMapEntry>(
+ `${globalPath}/certificateMaps/${certificateMap}/certificateMapEntries/${entryId}`,
+ { headers }
+ ),
+ { operation: "get-certificate-map-entry", syncId, identifier: entryId }
+ );
+ return data;
+ } catch (error) {
+ if (getGcpErrorStatus(error) === GcpErrorStatus.NotFound || getGcpHttpStatus(error) === 404) return undefined;
+ throw error;
+ }
+ };
+
const createCertificateMapEntry = async ({
certificateMap,
entryId,
@@ -424,6 +449,7 @@ export const createGcpCertificateManagerClient = ({
upsertCertificate,
deleteCertificate,
listCertificateMapEntries,
+ getCertificateMapEntry,
createCertificateMapEntry,
updateCertificateMapEntryCertificates,
deleteCertificateMapEntry,
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.ts
index c2926d396f..319e511fa7 100644
--- 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.ts
@@ -4,7 +4,7 @@ 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";
+import { GcpCertificateManagerAction, GcpCertificateManagerScope } from "./gcp-certificate-manager-pki-sync-enums";
const GCP_CERTIFICATE_MANAGER_NAME_REGEX_SOURCE = "^[a-z][a-z0-9-]{0,62}$";
@@ -85,3 +85,9 @@ export const GCP_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION = {
maxCertificateNameLength: GCP_CERTIFICATE_MANAGER_NAMING.MAX_NAME_LENGTH,
minCertificateNameLength: GCP_CERTIFICATE_MANAGER_NAMING.MIN_NAME_LENGTH
} as const;
+
+export const gcpCertificatePermission = (action: GcpCertificateManagerAction) => `certificatemanager.certs.${action}`;
+export const gcpCertificateMapPermission = (action: GcpCertificateManagerAction) =>
+ `certificatemanager.certmaps.${action}`;
+export const gcpCertificateMapEntryPermission = (action: GcpCertificateManagerAction) =>
+ `certificatemanager.certmapentries.${action}`;
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.ts
index e69e0acde7..e10761e519 100644
--- 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.ts
@@ -4,3 +4,20 @@ export enum GcpCertificateManagerScope {
AllRegions = "all-regions",
ClientAuth = "client-auth"
}
+
+export enum GcpCertificateManagerAction {
+ Get = "get",
+ List = "list",
+ Create = "create",
+ Update = "update",
+ Delete = "delete"
+}
+
+export enum GcpErrorStatus {
+ PermissionDenied = "PERMISSION_DENIED",
+ NotFound = "NOT_FOUND",
+ AlreadyExists = "ALREADY_EXISTS",
+ ResourceExhausted = "RESOURCE_EXHAUSTED",
+ FailedPrecondition = "FAILED_PRECONDITION",
+ InvalidArgument = "INVALID_ARGUMENT"
+}
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.ts
index a4f26dd7d4..2d4b7bccd3 100644
--- 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.ts
@@ -23,12 +23,18 @@ import {
GCP_MANAGED_BY_LABEL_KEY,
GCP_MANAGED_BY_LABEL_VALUE,
GCP_MAX_CERTIFICATES_PER_MAP_ENTRY,
- GCP_PRIMARY_MATCHER
+ GCP_PRIMARY_MATCHER,
+ gcpCertificateMapEntryPermission,
+ gcpCertificateMapPermission,
+ gcpCertificatePermission
} from "./gcp-certificate-manager-pki-sync-constants";
-import { GcpCertificateManagerScope } from "./gcp-certificate-manager-pki-sync-enums";
+import {
+ GcpCertificateManagerAction,
+ GcpCertificateManagerScope,
+ GcpErrorStatus
+} from "./gcp-certificate-manager-pki-sync-enums";
import { assertKeyAlgorithmSupported } from "./gcp-certificate-manager-pki-sync-key-fns";
import {
- buildGcpCertificateMapEntryResourceName,
buildGcpCertificateResourceName,
toGcpCertificateId,
toGcpCertificateMapEntryId
@@ -102,6 +108,14 @@ const buildPemChain = (cert: string, certificateChain?: string) => {
return chain ? `${leaf}\n${chain}` : leaf;
};
+const GCP_MAP_ENTRY_OPERATION: Record<GcpCertificateManagerAction, string> = {
+ [GcpCertificateManagerAction.Get]: "certificate map entry lookup",
+ [GcpCertificateManagerAction.List]: "certificate map entry list",
+ [GcpCertificateManagerAction.Create]: "certificate map entry creation",
+ [GcpCertificateManagerAction.Update]: "certificate map entry update",
+ [GcpCertificateManagerAction.Delete]: "certificate map entry deletion"
+};
+
export const gcpCertificateManagerPkiSyncFactory = ({
certificateSyncDAL,
certificateDAL
@@ -131,22 +145,19 @@ export const gcpCertificateManagerPkiSyncFactory = ({
}) => {
const { certificateMap, hostname } = certificateMapBinding;
const entryId = toGcpCertificateMapEntryId(pkiSync.id);
- const entryResourceName = buildGcpCertificateMapEntryResourceName({ gcpProjectId, certificateMap, entryId });
- let entries: Map<string, TGcpCertificateMapEntry>;
+ let existingEntry: TGcpCertificateMapEntry | undefined;
try {
- entries = await client.listCertificateMapEntries(certificateMap);
+ existingEntry = await client.getCertificateMapEntry(certificateMap, entryId);
} catch (error) {
throw mapGcpError(error, {
- operation: "certificate map entry list",
+ operation: "certificate map entry lookup",
gcpProjectId,
- resource: `certificate map "${certificateMap}"`,
- permission: "certificatemanager.certificatemapentries.list"
+ resource: `certificate map entry "${entryId}" in map "${certificateMap}"`,
+ permission: gcpCertificateMapEntryPermission(GcpCertificateManagerAction.Get)
});
}
- const existingEntry = entries.get(entryResourceName);
-
const desiredResourceNames = Array.from(
new Set([
...certificateResourceNames,
@@ -161,7 +172,21 @@ export const gcpCertificateManagerPkiSyncFactory = ({
});
}
- if (!existingEntry && !hostname) {
+ const willBecomePrimary = !hostname && existingEntry?.matcher !== GCP_PRIMARY_MATCHER;
+
+ if (willBecomePrimary) {
+ 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: gcpCertificateMapEntryPermission(GcpCertificateManagerAction.List)
+ });
+ }
+
const conflictingPrimary = Array.from(entries.values()).find((entry) => entry.matcher === GCP_PRIMARY_MATCHER);
if (conflictingPrimary) {
throw new PkiSyncError({
@@ -173,6 +198,8 @@ export const gcpCertificateManagerPkiSyncFactory = ({
}
}
+ let attempted = existingEntry ? GcpCertificateManagerAction.Update : GcpCertificateManagerAction.Create;
+
try {
if (!existingEntry) {
await client.createCertificateMapEntry({
@@ -189,7 +216,9 @@ export const gcpCertificateManagerPkiSyncFactory = ({
// means deleting and recreating rather than patching
const desiredMatcher = hostname ? undefined : GCP_PRIMARY_MATCHER;
if (existingEntry.hostname !== hostname || existingEntry.matcher !== desiredMatcher) {
+ attempted = GcpCertificateManagerAction.Delete;
await client.deleteCertificateMapEntry({ certificateMap, entryId });
+ attempted = GcpCertificateManagerAction.Create;
await client.createCertificateMapEntry({
certificateMap,
entryId,
@@ -211,12 +240,10 @@ export const gcpCertificateManagerPkiSyncFactory = ({
} catch (error) {
if (error instanceof PkiSyncError) throw error;
throw mapGcpError(error, {
- operation: existingEntry ? "certificate map entry update" : "certificate map entry creation",
+ operation: GCP_MAP_ENTRY_OPERATION[attempted],
gcpProjectId,
resource: `certificate map entry "${entryId}"`,
- permission: existingEntry
- ? "certificatemanager.certificatemapentries.update"
- : "certificatemanager.certificatemapentries.create"
+ permission: gcpCertificateMapEntryPermission(attempted)
});
}
};
@@ -240,20 +267,16 @@ export const gcpCertificateManagerPkiSyncFactory = ({
}) => {
if (certificateMapBinding) {
const entryId = toGcpCertificateMapEntryId(pkiSync.id);
- const entryResourceName = buildGcpCertificateMapEntryResourceName({
- gcpProjectId,
- certificateMap: certificateMapBinding.certificateMap,
- entryId
- });
+ let attempted = GcpCertificateManagerAction.Get;
try {
- const entries = await client.listCertificateMapEntries(certificateMapBinding.certificateMap);
- const entry = entries.get(entryResourceName);
+ const entry = await client.getCertificateMapEntry(certificateMapBinding.certificateMap, entryId);
if (entry && isInfisicalManaged(entry.labels) && entry.certificates?.includes(resourceName)) {
const remaining = entry.certificates.filter((name) => name !== resourceName);
if (remaining.length) {
+ attempted = GcpCertificateManagerAction.Update;
await client.updateCertificateMapEntryCertificates({
certificateMap: certificateMapBinding.certificateMap,
entryId,
@@ -261,6 +284,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({
labels: entry.labels ?? {}
});
} else {
+ attempted = GcpCertificateManagerAction.Delete;
await client.deleteCertificateMapEntry({
certificateMap: certificateMapBinding.certificateMap,
entryId
@@ -270,10 +294,10 @@ export const gcpCertificateManagerPkiSyncFactory = ({
} catch (error) {
if (error instanceof PkiSyncError) throw error;
throw mapGcpError(error, {
- operation: "certificate map entry detach",
+ operation: GCP_MAP_ENTRY_OPERATION[attempted],
gcpProjectId,
resource: `certificate map entry "${entryId}" in map "${certificateMapBinding.certificateMap}"`,
- permission: "certificatemanager.certificatemapentries.update"
+ permission: gcpCertificateMapEntryPermission(attempted)
});
}
}
@@ -283,7 +307,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({
} catch (error) {
if (error instanceof PkiSyncError) throw error;
- if (getGcpErrorStatus(error) === "NOT_FOUND" || getGcpHttpStatus(error) === 404) return;
+ if (getGcpErrorStatus(error) === GcpErrorStatus.NotFound || getGcpHttpStatus(error) === 404) return;
if (isCertificateInUseError(error)) {
throw new PkiSyncError({
@@ -296,7 +320,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({
operation: "certificate deletion",
gcpProjectId,
resource: `certificate "${certificateId}"`,
- permission: "certificatemanager.certificates.delete"
+ permission: gcpCertificatePermission(GcpCertificateManagerAction.Delete)
});
}
};
@@ -327,14 +351,19 @@ export const gcpCertificateManagerPkiSyncFactory = ({
});
});
+ const failedReaps: string[] = [];
+
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) {
+ failedReaps.push(`"${entryId}" in map "${certificateMap}"`);
logger.warn({ syncId: pkiSync.id, entry: name, error }, "Failed to remove orphaned GCP certificate map entry");
}
}
+
+ return failedReaps;
};
const $planCertificate = async ({
@@ -498,8 +527,8 @@ export const gcpCertificateManagerPkiSyncFactory = ({
gcpProjectId,
resource: `certificate "${target.certificateId}"`,
permission: target.shouldPatch
- ? "certificatemanager.certificates.update"
- : "certificatemanager.certificates.create"
+ ? gcpCertificatePermission(GcpCertificateManagerAction.Update)
+ : gcpCertificatePermission(GcpCertificateManagerAction.Create)
});
}
@@ -622,7 +651,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({
operation: "certificate map lookup",
gcpProjectId,
resource: `certificate map "${certificateMapBinding.certificateMap}"`,
- permission: "certificatemanager.certificatemaps.get"
+ permission: gcpCertificateMapPermission(GcpCertificateManagerAction.Get)
});
}
}
@@ -634,7 +663,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({
throw mapGcpError(error, {
operation: "certificate list",
gcpProjectId,
- permission: "certificatemanager.certificates.list"
+ permission: gcpCertificatePermission(GcpCertificateManagerAction.List)
});
}
@@ -671,17 +700,17 @@ export const gcpCertificateManagerPkiSyncFactory = ({
(result): result is PromiseFulfilledResult<TUploadTarget> => result.status === "fulfilled"
);
- const failedUploads = uploadResults
+ const failedUploadTargets = uploadResults
.map((result, index) => ({ result, target: uploadTargets[index] }))
- .filter(({ result }) => result.status === "rejected")
- .map(({ result, target }) => ({
- target,
- name: target?.key ?? "unknown",
- error:
- (result as PromiseRejectedResult).reason instanceof Error
- ? ((result as PromiseRejectedResult).reason as Error).message
- : "Unknown error"
- }));
+ .filter(({ result }) => result.status === "rejected");
+
+ const failedUploads = failedUploadTargets.map(({ result, target }) => ({
+ name: target?.key ?? "unknown",
+ error:
+ (result as PromiseRejectedResult).reason instanceof Error
+ ? ((result as PromiseRejectedResult).reason as Error).message
+ : "Unknown error"
+ }));
let failedMapEntry: string | undefined;
if (certificateMapBinding && successfulUploads.length) {
@@ -694,7 +723,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({
certificateResourceNames: successfulUploads.map(({ value }) => value.resourceName),
retainResourceNames: [
...retainResourceNames,
- ...failedUploads.flatMap(({ target }) => $servingResourceName(target) ?? [])
+ ...failedUploadTargets.flatMap(({ target }) => $servingResourceName(target) ?? [])
],
userLabels
});
@@ -707,6 +736,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({
}
}
+ let failedReaps: string[] = [];
const mapEntryOutOfSync =
Boolean(certificateMapBinding) &&
(Boolean(failedMapEntry) || (uploadTargets.length > 0 && !successfulUploads.length));
@@ -717,7 +747,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({
"Skipping GCP certificate map entry cleanup because the entry could not be brought up to date"
);
} else {
- await $reapOrphanedMapEntries({
+ failedReaps = await $reapOrphanedMapEntries({
client,
pkiSync,
certificates: existingCertificates,
@@ -753,11 +783,23 @@ export const gcpCertificateManagerPkiSyncFactory = ({
const details: TPkiSyncSyncResult["details"] = {};
if (skippedCertificates.length) details.skippedCertificates = skippedCertificates;
- if (failedUploads.length) details.failedUploads = failedUploads.map(({ name, error }) => ({ name, error }));
+ 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;
+ const buildPartialFailureMessage = () => {
+ if (failedMapEntry) {
+ return `${successfulUploads.length} certificate(s) reached GCP Certificate Manager, but the certificate map entry could not be updated: ${failedMapEntry}`;
+ }
+
+ if (failedReaps.length) {
+ return `${successfulUploads.length} certificate(s) reached GCP Certificate Manager, but ${failedReaps.length} certificate map entry from a previous binding could not be removed (${failedReaps.join(
+ ", "
+ )}). Those entries keep serving the certificate they already point at.`;
+ }
+
+ return undefined;
+ };
+
+ const partialFailureMessage = buildPartialFailureMessage();
return {
uploaded: successfulUploads.length,
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.ts
index 20d3b1a853..7dc5cceafc 100644
--- 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.ts
@@ -1,5 +1,4 @@
import {
- buildGcpCertificateMapEntryResourceName,
buildGcpCertificateResourceName,
toGcpCertificateId,
toGcpCertificateMapEntryId
@@ -25,10 +24,19 @@ describe("toGcpCertificateId", () => {
expect(toGcpCertificateId(".infisical.")).toBe("infisical");
});
- test("truncates to 63 characters", () => {
+ test("shortens to 63 characters", () => {
expect(toGcpCertificateId("a".repeat(80))).toHaveLength(63);
});
+ test("keeps the start of the name and replaces the end, not the other way round", () => {
+ const tail = "550e8400e29b41d4a716446655440000";
+ const shortened = toGcpCertificateId(`checkout-service-eu-west-1-payments-internal-example-com-${tail}`);
+
+ expect(shortened).toBe("checkout-service-eu-west-1-payments-internal-example-c-3e574b24");
+ expect(shortened).not.toContain(tail);
+ expect(shortened.startsWith("checkout-service")).toBe(true);
+ });
+
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)}`);
@@ -85,14 +93,4 @@ describe("resource name builders", () => {
})
).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.ts
index a7b28660ed..b212e5bbeb 100644
--- 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.ts
@@ -2,8 +2,6 @@ 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,
@@ -15,14 +13,14 @@ 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 keepPrefixAndAppendHash = (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, "");
+ const wholeNameDigest = crypto.createHash("sha256").update(cleaned).digest("hex").slice(0, GCP_NAME_HASH_LENGTH);
+ const keptPrefix = cleaned.slice(0, MAX_NAME_LENGTH - GCP_NAME_HASH_LENGTH - 1).replace(SURROUNDING_HYPHENS, "");
- return `${head}-${digest}`;
+ return `${keptPrefix}-${wholeNameDigest}`;
};
export const toGcpCertificateId = (name: string): string => {
@@ -32,7 +30,7 @@ export const toGcpCertificateId = (name: string): string => {
.replace(REPEATED_HYPHENS, "-")
.replace(SURROUNDING_HYPHENS, "");
- const normalized = truncateToLimit(cleaned).replace(SURROUNDING_HYPHENS, "");
+ const normalized = keepPrefixAndAppendHash(cleaned).replace(SURROUNDING_HYPHENS, "");
if (!normalized) {
throw new PkiSyncError({
@@ -61,15 +59,4 @@ export const buildGcpCertificateResourceName = ({
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-reconcile.test.ts b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-reconcile.test.ts
new file mode 100644
index 0000000000..8be66c0455
--- /dev/null
+++ b/backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-reconcile.test.ts
@@ -0,0 +1,372 @@
+import { AxiosError, AxiosHeaders } from "axios";
+import { beforeEach, vi } from "vitest";
+
+import { gcpCertificateManagerPkiSyncFactory } from "./gcp-certificate-manager-pki-sync-fns";
+
+const { clientMock, createClientMock, calls } = vi.hoisted(() => {
+ const order: string[] = [];
+ const client = {
+ assertCertificateMapExists: vi.fn(),
+ listCertificates: vi.fn(),
+ listCertificateMapEntries: vi.fn(),
+ getCertificateMapEntry: vi.fn(),
+ createCertificateMapEntry: vi.fn(),
+ updateCertificateMapEntryCertificates: vi.fn(),
+ deleteCertificateMapEntry: vi.fn(),
+ upsertCertificate: vi.fn(),
+ deleteCertificate: vi.fn()
+ };
+ return { clientMock: client, createClientMock: vi.fn(() => client), calls: order };
+});
+
+vi.mock("./gcp-certificate-manager-pki-sync-auth-fns", () => ({
+ getGcpAccessToken: vi.fn().mockResolvedValue("token")
+}));
+
+vi.mock("./gcp-certificate-manager-pki-sync-client", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./gcp-certificate-manager-pki-sync-client")>()),
+ createGcpCertificateManagerClient: createClientMock
+}));
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }
+}));
+
+const LEAF =
+ "-----BEGIN CERTIFICATE-----\nMIIDFTCCAf2gAwIBAgIUEvrsmSKnzo8HANa2TOeNIcg5b7AwDQYJKoZIhvcNAQEL\nBQAwGjEYMBYGA1UEAwwPYXBwLmV4YW1wbGUuY29tMB4XDTI2MDgyNjIwMzcxOFoX\nDTI2MDgyODIwMzcxOFowGjEYMBYGA1UEAwwPYXBwLmV4YW1wbGUuY29tMIIBIjAN\nBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs/7FAanft8ZcQ/08/U86mRfsdX8Y\nmykUf9VYgO/26TG7dh5M6awS1mGybPiQ/ni887zulgUkYwYkRyxcSz3xQ9B5SSdG\nAcz2mX3mU95ZsqtE9YbAo7rLgoOb1tj9yOHDiLzlJ2wtkDm0SLDebFe/m0A5f0uP\nPCxknOHwcLXN8AFmr28LiPI9CSXHe3iynL7eluwV531E7ku1kVbxfxxmxmPOyQO9\nS0Gd94m6qFfZpSJmxGSkaUQWx1wtz2Y59tTIsglc2/p+cUajy9PSrSqtanUYIGdb\n9haYl5HwSf9NMPRq8+mjo5HSeavz2Bk438w/BGYLnrtdIx81KwuMXvZ+DwIDAQAB\no1MwUTAdBgNVHQ4EFgQUD1/0yZj6YtwdDH/Iyd611C9v34owHwYDVR0jBBgwFoAU\nD1/0yZj6YtwdDH/Iyd611C9v34owDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B\nAQsFAAOCAQEAcK7qES2oaXKQc8xuFPzAb7Igb4UvPhPQhRiB2nX5dmTDrVm1lbM8\ncvg5Z38sXMbiQOLpBuhp38Q4F1DIBFrVYOt1wxHTRXYwHBrsG/Acfc6gA1sZcFEG\n+iVavLshStDDQPSL630uzpLnNfEqsdplg7NKajKvc2pazQKQjf9NA9BPp1MmGU1P\ndv33JB0AiCkySXJlSD5mPMorE0G4NA3qSfzC+89Hywo+fJzj4uASolZ7kIkNrEhs\nP3ov7gfOYfdkSns5mLUY8H6VhX4PUm/IT8LQ4DeCOS/qKxSaTJgywp3xr1q8n1xa\nN11/kEdbuLRx+bQ19ULTVFQ2vNEq8C9HYw==\n-----END CERTIFICATE-----";
+const KEY =
+ "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCz/sUBqd+3xlxD\n/Tz9TzqZF+x1fxibKRR/1ViA7/bpMbt2HkzprBLWYbJs+JD+eLzzvO6WBSRjBiRH\nLFxLPfFD0HlJJ0YBzPaZfeZT3lmyq0T1hsCjusuCg5vW2P3I4cOIvOUnbC2QObRI\nsN5sV7+bQDl/S488LGSc4fBwtc3wAWavbwuI8j0JJcd7eLKcvt6W7BXnfUTuS7WR\nVvF/HGbGY87JA71LQZ33ibqoV9mlImbEZKRpRBbHXC3PZjn21MiyCVzb+n5xRqPL\n09KtKq1qdRggZ1v2FpiXkfBJ/00w9Grz6aOjkdJ5q/PYGTjfzD8EZgueu10jHzUr\nC4xe9n4PAgMBAAECggEAU5ruFSS7lpgbeTUiZCKt/Dhhi/36BvAg5nPJhTJxBMYl\n5eqTHSLhKRT+FKGsb5bTZX+HbsV6rkhHB4wyXnyqGS63d2Q3n1R94rPZDXHFRjlJ\ncaYiyqpUJw5Mj5IA55L+CQB8jEAyNcCn3e/RkI99n3ZIfrkxEeko3roPvbqkqmqk\ns5GBXoyQHyPQChZxLuJygGvf6CcQzVgeUyYhB+F+0FqiAXpozX0V/E41AtAzIOe5\nuGzMgEaij8F2eFtFqGLEx9hFB7XbBpO3mxUduXk/hTcGhTnAWb91650OOrYFy8gB\nU0H2OT102CLxKr/iSiLcKZkQjVom6tOjQ6hxBYOBUQKBgQDci+b47ZY/sOzWS0Hz\n8aI36l9xS7bzrSHS3aV/1Hny7vJGdRXENE5JKA13YNE7zbdY78Qbq1bEE0JLqDpo\nOizx5+HvB64RsKdh2IGE7F+g26WCGj8z9tIP5AiIjUN4UK8wdnM2CCv1JPK/pSM4\n512WL7eg5cJKxNhp+zrSg2gsxwKBgQDQ7hG7VJeZtXhIVsj+7JwfSYWZ77Qtk70+\nSAuG/lT+REURPtN9DBpZLiS7XIo5jgciC9dD4e+wA66XJfiC8wEFyVAIO1OtG7oG\nMVhvn1kUqTIquPHs8sfnpXWGpz6qYij6t5AZVOTCC3wuNJ4CPasMD7/Maia1gADS\n+udmumAMeQKBgBlEHc3eyhu51SgnrwKXaBIn049TMT5xUzKpGdCvMtlV7oOL3lZ/\n94gCAqjueonzY1HZBgp1cpc77ZhlSWuvXn7IJeYQZyy3pDVdbFkiC0KOZ0OkZiE5\n4Y7YfPHH3TbnZ2qR51kFTqPi+7xg2swmFV6jUNIqADw4mOJrWa3MSB75AoGAQwYc\nahwZBhZRH+O3VxBQhTjwwxFCm9xpOTGjgQrV+TutbHrbHaJkUXecEP7+2LfXUfS6\neexhF/YWbCaiMmACU/jg08M0dLQQWSw7UpOr4BTnIw1xjrHTr1xE941vbPlQbB22\n/GlfeWB11dzLU6y00om63biv8km9+fDDixD+/wECgYBbp6wjgpXRnR7ybjB8iBZj\nY60XenGYWzrvktn8JUyOS0Ncw3rqobZNGgsg43urqKOmTFe5EM2k+jcm9vkeQcFd\n1SAYGGJYe7vKVhIN4uZ7F683dpuhzYWGCzFbuZaGtIPYPguF2QnK7rh1OColkkQc\n7jgp3wz7ElOrqIoa8tGEHw==\n-----END PRIVATE KEY-----";
+const SYNC_ID = "11111111-1111-1111-1111-111111111111";
+const CERT_A = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+const CERT_B = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
+const PROJECT = "my-prod-project";
+const MAP = "prod-map";
+
+const resourceName = (id: string) => `projects/${PROJECT}/locations/global/certificates/${id}`;
+const entryName = (map: string) =>
+ `projects/${PROJECT}/locations/global/certificateMaps/${map}/certificateMapEntries/infisical-${SYNC_ID}`;
+
+const pkiSync = (overrides: Record<string, unknown> = {}) =>
+ ({
+ id: SYNC_ID,
+ destination: "gcp-certificate-manager",
+ destinationConfig: {
+ gcpProjectId: PROJECT,
+ location: "global",
+ scope: "default",
+ certificateMapBinding: { certificateMap: MAP }
+ },
+ syncOptions: { preserveItemOnRenewal: true },
+ ...overrides
+ }) as never;
+
+const gcpCertificate = (id: string, usedByEntry?: string) => ({
+ name: resourceName(id),
+ labels: { "managed-by": "infisical" },
+ ...(usedByEntry ? { usedBy: [{ name: usedByEntry }] } : {})
+});
+
+const managedEntry = (map: string, certificates: string[]) => ({
+ name: entryName(map),
+ labels: { "managed-by": "infisical" },
+ matcher: "PRIMARY",
+ certificates
+});
+
+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;
+};
+
+let syncRecords: Array<{ id: string; certificateId: string; externalIdentifier: string }>;
+let certificateRows: Record<string, { id: string; renewedByCertificateId?: string; renewedFromCertificateId?: string }>;
+let removedRecordIds: string[][];
+
+const certificateSyncDAL = {
+ findByPkiSyncId: vi.fn(async () => syncRecords),
+ findByPkiSyncAndCertificate: vi.fn(async (_syncId: string, certificateId: string) =>
+ syncRecords.find((row) => row.certificateId === certificateId)
+ ),
+ addCertificates: vi.fn(async () => []),
+ updateById: vi.fn(async () => undefined),
+ removeCertificates: vi.fn(async (_syncId: string, ids: string[]) => {
+ removedRecordIds.push(ids);
+ return 0;
+ }),
+ updateSyncStatus: vi.fn(async () => undefined)
+} as never;
+
+const certificateDAL = {
+ findById: vi.fn(async (id: string) => certificateRows[id])
+} as never;
+
+const buildFns = () => gcpCertificateManagerPkiSyncFactory({ certificateSyncDAL, certificateDAL });
+
+const unboundSync = (syncOptions: Record<string, unknown>) =>
+ pkiSync({
+ destinationConfig: { gcpProjectId: PROJECT, location: "global", scope: "default" },
+ syncOptions
+ });
+
+beforeEach(() => {
+ calls.length = 0;
+ syncRecords = [];
+ certificateRows = {};
+ removedRecordIds = [];
+ Object.values(clientMock).forEach((fn) => fn.mockReset());
+ clientMock.assertCertificateMapExists.mockResolvedValue(undefined);
+ clientMock.listCertificates.mockResolvedValue(new Map());
+ clientMock.listCertificateMapEntries.mockResolvedValue(new Map());
+ clientMock.getCertificateMapEntry.mockResolvedValue(undefined);
+ clientMock.upsertCertificate.mockResolvedValue(undefined);
+ clientMock.createCertificateMapEntry.mockImplementation(async () => {
+ calls.push("createEntry");
+ });
+ clientMock.updateCertificateMapEntryCertificates.mockImplementation(async () => {
+ calls.push("updateEntry");
+ });
+ clientMock.deleteCertificateMapEntry.mockImplementation(async () => {
+ calls.push("deleteEntry");
+ });
+ clientMock.deleteCertificate.mockImplementation(async () => {
+ calls.push("deleteCertificate");
+ });
+});
+
+describe("certificate map entry reconciliation", () => {
+ test("keeps a certificate whose upload failed in the entry instead of dropping it from traffic", async () => {
+ syncRecords = [
+ { id: "rec-a", certificateId: CERT_A, externalIdentifier: resourceName("cert-a") },
+ { id: "rec-b", certificateId: CERT_B, externalIdentifier: resourceName("cert-b") }
+ ];
+ certificateRows = { [CERT_A]: { id: CERT_A }, [CERT_B]: { id: CERT_B } };
+ clientMock.listCertificates.mockResolvedValue(
+ new Map([
+ [resourceName("cert-a"), gcpCertificate("cert-a", entryName(MAP))],
+ [resourceName("cert-b"), gcpCertificate("cert-b", entryName(MAP))]
+ ])
+ );
+ clientMock.getCertificateMapEntry.mockResolvedValue(
+ managedEntry(MAP, [resourceName("cert-a"), resourceName("cert-b")])
+ );
+ clientMock.upsertCertificate.mockImplementation(async ({ certificateId }: { certificateId: string }) => {
+ if (certificateId === "cert-b") throw new Error("GCP rejected the certificate update");
+ });
+
+ const result = await buildFns().syncCertificates(pkiSync(), {
+ "cert-a": { cert: LEAF, privateKey: KEY, certificateId: CERT_A },
+ "cert-b": { cert: LEAF, privateKey: KEY, certificateId: CERT_B }
+ } as never);
+
+ expect(result.uploaded).toBe(1);
+ expect(result.details?.failedUploads).toHaveLength(1);
+ expect(clientMock.updateCertificateMapEntryCertificates).not.toHaveBeenCalled();
+ expect(clientMock.deleteCertificateMapEntry).not.toHaveBeenCalled();
+ expect(clientMock.deleteCertificate).not.toHaveBeenCalled();
+ });
+
+ test("never puts an upload target in the failure details, because a target holds the private key", async () => {
+ certificateRows = { [CERT_A]: { id: CERT_A } };
+ clientMock.upsertCertificate.mockRejectedValue(new Error("GCP rejected the certificate upload"));
+
+ const result = await buildFns().syncCertificates(unboundSync({}), {
+ "cert-a": { cert: LEAF, privateKey: KEY, certificateId: CERT_A }
+ } as never);
+
+ expect(result.details?.failedUploads).toHaveLength(1);
+ expect(Object.keys(result.details!.failedUploads![0]).sort()).toEqual(["error", "name"]);
+ expect(JSON.stringify(result)).not.toContain("BEGIN PRIVATE KEY");
+ });
+
+ test("keeps a skipped certificate in the entry", async () => {
+ syncRecords = [
+ { id: "rec-a", certificateId: CERT_A, externalIdentifier: resourceName("cert-a") },
+ { id: "rec-b", certificateId: CERT_B, externalIdentifier: resourceName("cert-b") }
+ ];
+ certificateRows = { [CERT_A]: { id: CERT_A }, [CERT_B]: { id: CERT_B } };
+ clientMock.listCertificates.mockResolvedValue(
+ new Map([
+ [resourceName("cert-a"), gcpCertificate("cert-a", entryName(MAP))],
+ [resourceName("cert-b"), gcpCertificate("cert-b", entryName(MAP))]
+ ])
+ );
+ clientMock.getCertificateMapEntry.mockResolvedValue(
+ managedEntry(MAP, [resourceName("cert-a"), resourceName("cert-b")])
+ );
+
+ const result = await buildFns().syncCertificates(pkiSync(), {
+ "cert-a": { cert: LEAF, privateKey: KEY, certificateId: CERT_A },
+ "cert-b": { cert: LEAF, certificateId: CERT_B }
+ } as never);
+
+ expect(result.skipped).toBe(1);
+ expect(clientMock.updateCertificateMapEntryCertificates).not.toHaveBeenCalled();
+ expect(clientMock.deleteCertificate).not.toHaveBeenCalled();
+ });
+
+ test("does not delete certificates or reap entries when the entry could not be reconciled", async () => {
+ syncRecords = [{ id: "rec-a", certificateId: CERT_A, externalIdentifier: resourceName("stale-cert") }];
+ certificateRows = { [CERT_A]: { id: CERT_A } };
+ clientMock.listCertificates.mockResolvedValue(
+ new Map([[resourceName("stale-cert"), gcpCertificate("stale-cert", entryName("an-old-map"))]])
+ );
+ clientMock.getCertificateMapEntry.mockRejectedValue(new Error("boom"));
+
+ const result = await buildFns().syncCertificates(pkiSync({ syncOptions: { preserveItemOnRenewal: false } }), {
+ "cert-a": { cert: LEAF, privateKey: KEY, certificateId: CERT_A }
+ } as never);
+
+ expect(result.partialFailureMessage).toContain("certificate map entry could not be updated");
+ expect(result.removed).toBe(0);
+ expect(clientMock.deleteCertificate).not.toHaveBeenCalled();
+ expect(clientMock.deleteCertificateMapEntry).not.toHaveBeenCalled();
+ });
+
+ test("blames the delete, not the update, when a hostname change cannot remove the old entry", async () => {
+ certificateRows = { [CERT_A]: { id: CERT_A } };
+ clientMock.getCertificateMapEntry.mockResolvedValue({
+ ...managedEntry(MAP, [resourceName("cert-a")]),
+ matcher: undefined,
+ hostname: "old.example.com"
+ });
+ clientMock.deleteCertificateMapEntry.mockRejectedValue(
+ googleError(403, "PERMISSION_DENIED", "caller lacks permission")
+ );
+
+ const result = await buildFns().syncCertificates(
+ pkiSync({
+ destinationConfig: {
+ gcpProjectId: PROJECT,
+ location: "global",
+ scope: "default",
+ certificateMapBinding: { certificateMap: MAP, hostname: "new.example.com" }
+ }
+ }),
+ { "cert-a": { cert: LEAF, privateKey: KEY, certificateId: CERT_A } } as never
+ );
+
+ expect(result.partialFailureMessage).toContain("certificatemanager.certmapentries.delete");
+ expect(result.partialFailureMessage).toContain("roles/certificatemanager.owner");
+ });
+
+ test("creates the entry in the new map before reaping the entry in the old one", async () => {
+ syncRecords = [{ id: "rec-a", certificateId: CERT_A, externalIdentifier: resourceName("cert-a") }];
+ certificateRows = { [CERT_A]: { id: CERT_A } };
+ clientMock.listCertificates.mockResolvedValue(
+ new Map([[resourceName("cert-a"), gcpCertificate("cert-a", entryName("previous-map"))]])
+ );
+
+ await buildFns().syncCertificates(pkiSync(), {
+ "cert-a": { cert: LEAF, privateKey: KEY, certificateId: CERT_A }
+ } as never);
+
+ expect(calls).toEqual(["createEntry", "deleteEntry"]);
+ });
+
+ test("reports a failed cleanup of a previous binding instead of finishing green", async () => {
+ certificateRows = { [CERT_A]: { id: CERT_A } };
+ clientMock.listCertificates.mockResolvedValue(
+ new Map([[resourceName("cert-a"), gcpCertificate("cert-a", entryName("previous-map"))]])
+ );
+ clientMock.deleteCertificateMapEntry.mockRejectedValue(
+ googleError(403, "PERMISSION_DENIED", "caller lacks permission")
+ );
+
+ const result = await buildFns().syncCertificates(pkiSync(), {
+ "cert-a": { cert: LEAF, privateKey: KEY, certificateId: CERT_A }
+ } as never);
+
+ expect(result.partialFailureMessage).toContain("previous-map");
+ expect(result.partialFailureMessage).toContain("could not be removed");
+ });
+
+ test("refuses to drop a working entry when clearing the hostname would collide with another primary", async () => {
+ certificateRows = { [CERT_A]: { id: CERT_A } };
+ clientMock.getCertificateMapEntry.mockResolvedValue({
+ ...managedEntry(MAP, [resourceName("cert-a")]),
+ matcher: undefined,
+ hostname: "old.example.com"
+ });
+ clientMock.listCertificateMapEntries.mockResolvedValue(
+ new Map([["someone-elses-entry", { name: "someone-elses-entry", matcher: "PRIMARY", certificates: [] }]])
+ );
+
+ const result = await buildFns().syncCertificates(pkiSync(), {
+ "cert-a": { cert: LEAF, privateKey: KEY, certificateId: CERT_A }
+ } as never);
+
+ expect(clientMock.deleteCertificateMapEntry).not.toHaveBeenCalled();
+ expect(result.partialFailureMessage).toContain("already has a primary entry");
+ });
+
+ test("only lists the whole map when it is about to create a primary entry", async () => {
+ certificateRows = { [CERT_A]: { id: CERT_A } };
+ clientMock.getCertificateMapEntry.mockResolvedValue(managedEntry(MAP, [resourceName("cert-a")]));
+
+ await buildFns().syncCertificates(pkiSync(), {
+ "cert-a": { cert: LEAF, privateKey: KEY, certificateId: CERT_A }
+ } as never);
+
+ expect(clientMock.getCertificateMapEntry).toHaveBeenCalledTimes(1);
+ expect(clientMock.listCertificateMapEntries).not.toHaveBeenCalled();
+ });
+});
+
+describe("renewal that replaces the GCP resource", () => {
+ const renewalRows = {
+ [CERT_A]: { id: CERT_A },
+ [CERT_B]: { id: CERT_B, renewedFromCertificateId: CERT_A }
+ };
+
+ test("keeps the old sync record until the old GCP certificate is actually deleted", async () => {
+ syncRecords = [{ id: "rec-a", certificateId: CERT_A, externalIdentifier: resourceName("old-name") }];
+ certificateRows = renewalRows;
+ clientMock.listCertificates.mockResolvedValue(new Map([[resourceName("old-name"), gcpCertificate("old-name")]]));
+ clientMock.deleteCertificate.mockRejectedValue(
+ googleError(409, "FAILED_PRECONDITION", "can't delete certificate that is referenced by a CertificateMapEntry")
+ );
+
+ const result = await buildFns().syncCertificates(unboundSync({ preserveItemOnRenewal: false }), {
+ "new-name": { cert: LEAF, privateKey: KEY, certificateId: CERT_B }
+ } as never);
+
+ expect(result.failedRemovals).toBe(1);
+ expect(removedRecordIds.flat()).not.toContain(CERT_A);
+ });
+
+ test("clears the old sync record when GCP reports the certificate is already gone", async () => {
+ syncRecords = [{ id: "rec-a", certificateId: CERT_A, externalIdentifier: resourceName("old-name") }];
+ certificateRows = renewalRows;
+ clientMock.listCertificates.mockResolvedValue(new Map([[resourceName("old-name"), gcpCertificate("old-name")]]));
+ clientMock.deleteCertificate.mockRejectedValue(googleError(404, "NOT_FOUND", "certificate not found"));
+
+ const result = await buildFns().syncCertificates(unboundSync({ preserveItemOnRenewal: false }), {
+ "new-name": { cert: LEAF, privateKey: KEY, certificateId: CERT_B }
+ } as never);
+
+ expect(result.failedRemovals).toBe(0);
+ expect(removedRecordIds.flat()).toContain(CERT_A);
+ });
+
+ test("drops the old sync record immediately when renewal reuses the same resource name", async () => {
+ syncRecords = [{ id: "rec-a", certificateId: CERT_A, externalIdentifier: resourceName("reused-name") }];
+ certificateRows = renewalRows;
+ clientMock.listCertificates.mockResolvedValue(
+ new Map([[resourceName("reused-name"), gcpCertificate("reused-name")]])
+ );
+
+ await buildFns().syncCertificates(unboundSync({ preserveItemOnRenewal: true }), {
+ "reused-name": { cert: LEAF, privateKey: KEY, certificateId: CERT_B }
+ } as never);
+
+ expect(removedRecordIds.flat()).toContain(CERT_A);
+ expect(clientMock.deleteCertificate).not.toHaveBeenCalled();
+ });
+});
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.ts
index b0fd948e73..3f7784fd03 100644
--- 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.ts
@@ -2,9 +2,10 @@ import { GcpCertificateManagerScope } from "./gcp-certificate-manager-pki-sync-e
import {
CreateGcpCertificateManagerPkiSyncSchema,
GcpCertificateManagerPkiSyncConfigSchema,
- GcpCertificateManagerPkiSyncOptionsSchema
+ GcpCertificateManagerPkiSyncOptionsSchema,
+ UpdateGcpCertificateManagerPkiSyncSchema
} from "./gcp-certificate-manager-pki-sync-schemas";
-import { assertGcpCertificateManagerConfigUpdate } from "./gcp-certificate-manager-pki-sync-update-fns";
+import { resolveGcpCertificateManagerConfigUpdate } from "./gcp-certificate-manager-pki-sync-update-fns";
const parseConfig = (overrides: Record<string, unknown> = {}) =>
GcpCertificateManagerPkiSyncConfigSchema.safeParse({
@@ -209,12 +210,58 @@ describe("GCP Certificate Manager create schema", () => {
});
});
-describe("assertGcpCertificateManagerConfigUpdate", () => {
+describe("updating a sync whose scope is not the default", () => {
+ const stored = { gcpProjectId: "my-prod-project", location: "global", scope: GcpCertificateManagerScope.EdgeCache };
+
+ const parseUpdate = (destinationConfig: Record<string, unknown>) =>
+ UpdateGcpCertificateManagerPkiSyncSchema.safeParse({ destinationConfig });
+
+ test("an update that leaves scope out means unchanged, not 'set it to default'", () => {
+ const parsed = parseUpdate({ gcpProjectId: "my-prod-project", location: "global" });
+
+ expect(parsed.success).toBe(true);
+ expect(parsed.success && parsed.data.destinationConfig?.scope).toBeUndefined();
+
+ const resolved = resolveGcpCertificateManagerConfigUpdate(
+ stored,
+ parsed.success ? parsed.data.destinationConfig! : stored
+ );
+
+ expect(resolved.scope).toBe(GcpCertificateManagerScope.EdgeCache);
+ });
+
+ test("still rejects an explicit scope change", () => {
+ const parsed = parseUpdate({
+ gcpProjectId: "my-prod-project",
+ location: "global",
+ scope: GcpCertificateManagerScope.Default
+ });
+
+ expect(() =>
+ resolveGcpCertificateManagerConfigUpdate(stored, parsed.success ? parsed.data.destinationConfig! : stored)
+ ).toThrow(/scope cannot be changed/);
+ });
+
+ test("still rejects adding a certificate map binding, judged against the stored scope", () => {
+ const parsed = parseUpdate({
+ gcpProjectId: "my-prod-project",
+ location: "global",
+ certificateMapBinding: { certificateMap: "prod-map" }
+ });
+
+ expect(parsed.success).toBe(true);
+ expect(() =>
+ resolveGcpCertificateManagerConfigUpdate(stored, parsed.success ? parsed.data.destinationConfig! : stored)
+ ).toThrow(/requires the Default scope/);
+ });
+});
+
+describe("resolveGcpCertificateManagerConfigUpdate", () => {
const previous = { gcpProjectId: "my-prod-project", location: "global", scope: GcpCertificateManagerScope.Default };
test("allows updates that leave the immutable fields alone", () => {
expect(() =>
- assertGcpCertificateManagerConfigUpdate(previous, {
+ resolveGcpCertificateManagerConfigUpdate(previous, {
...previous,
certificateMapBinding: { certificateMap: "prod-map" }
})
@@ -222,20 +269,20 @@ describe("assertGcpCertificateManagerConfigUpdate", () => {
});
test("rejects a location change", () => {
- expect(() => assertGcpCertificateManagerConfigUpdate(previous, { ...previous, location: "us-central1" })).toThrow(
+ expect(() => resolveGcpCertificateManagerConfigUpdate(previous, { ...previous, location: "us-central1" })).toThrow(
/location is immutable/
);
});
test("rejects a scope change", () => {
expect(() =>
- assertGcpCertificateManagerConfigUpdate(previous, { ...previous, scope: GcpCertificateManagerScope.EdgeCache })
+ resolveGcpCertificateManagerConfigUpdate(previous, { ...previous, scope: GcpCertificateManagerScope.EdgeCache })
).toThrow(/scope is immutable/);
});
test("rejects a project change", () => {
expect(() =>
- assertGcpCertificateManagerConfigUpdate(previous, { ...previous, gcpProjectId: "other-project" })
+ resolveGcpCertificateManagerConfigUpdate(previous, { ...previous, gcpProjectId: "other-project" })
).toThrow(/GCP project cannot be changed/);
});
});
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.ts
index c1af212332..e03ef63183 100644
--- 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.ts
@@ -45,7 +45,7 @@ const GcpCertificateMapBindingSchema = z.object({
})
});
-const BaseGcpCertificateManagerPkiSyncConfigSchema = z.object({
+const GcpCertificateManagerPkiSyncConfigFieldsSchema = z.object({
gcpProjectId: z
.string()
.trim()
@@ -62,15 +62,22 @@ const BaseGcpCertificateManagerPkiSyncConfigSchema = z.object({
.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 BaseGcpCertificateManagerPkiSyncConfigSchema = GcpCertificateManagerPkiSyncConfigFieldsSchema.extend({
+ scope: z.nativeEnum(GcpCertificateManagerScope).default(GcpCertificateManagerScope.Default)
+});
+
+const UpdateGcpCertificateManagerPkiSyncConfigSchema = GcpCertificateManagerPkiSyncConfigFieldsSchema.extend({
+ scope: z.nativeEnum(GcpCertificateManagerScope).optional()
+});
+
const assertScopeCompatibility = (
- config: z.infer<typeof BaseGcpCertificateManagerPkiSyncConfigSchema>,
+ config: z.infer<typeof UpdateGcpCertificateManagerPkiSyncConfigSchema>,
ctx: z.RefinementCtx
) => {
- if (config.certificateMapBinding && config.scope !== GcpCertificateManagerScope.Default) {
+ if (config.certificateMapBinding && config.scope && config.scope !== GcpCertificateManagerScope.Default) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["certificateMapBinding"],
@@ -100,6 +107,9 @@ const assertScopeCompatibility = (
export const GcpCertificateManagerPkiSyncConfigSchema =
BaseGcpCertificateManagerPkiSyncConfigSchema.superRefine(assertScopeCompatibility);
+export const GcpCertificateManagerPkiSyncConfigUpdateSchema =
+ UpdateGcpCertificateManagerPkiSyncConfigSchema.superRefine(assertScopeCompatibility);
+
const GcpLabelSchema = z.object({
key: z
.string()
@@ -191,7 +201,7 @@ export const UpdateGcpCertificateManagerPkiSyncSchema = z.object({
name: z.string().trim().min(1).max(256).optional(),
description: pkiDescriptionSchema.optional(),
isAutoSyncEnabled: z.boolean().optional(),
- destinationConfig: GcpCertificateManagerPkiSyncConfigSchema.optional(),
+ destinationConfig: GcpCertificateManagerPkiSyncConfigUpdateSchema.optional(),
syncOptions: GcpCertificateManagerPkiSyncOptionsSchema.optional(),
subscriberId: z.string().nullish(),
connectionId: z.string().uuid().optional()
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.ts
index 70477b8441..22d76323e2 100644
--- 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.ts
@@ -5,6 +5,7 @@ import { TGcpConnection } from "@app/services/app-connection/gcp/gcp-connection-
import {
CreateGcpCertificateManagerPkiSyncSchema,
GcpCertificateManagerPkiSyncConfigSchema,
+ GcpCertificateManagerPkiSyncConfigUpdateSchema,
GcpCertificateManagerPkiSyncOptionsSchema,
GcpCertificateManagerPkiSyncSchema,
UpdateGcpCertificateManagerPkiSyncSchema
@@ -12,6 +13,8 @@ import {
export type TGcpCertificateManagerPkiSyncConfig = z.infer<typeof GcpCertificateManagerPkiSyncConfigSchema>;
+export type TGcpCertificateManagerPkiSyncConfigUpdate = z.infer<typeof GcpCertificateManagerPkiSyncConfigUpdateSchema>;
+
export type TGcpCertificateManagerPkiSyncOptions = z.infer<typeof GcpCertificateManagerPkiSyncOptionsSchema>;
export type TGcpCertificateManagerPkiSync = z.infer<typeof GcpCertificateManagerPkiSyncSchema>;
@@ -47,12 +50,6 @@ export type TGcpCertificateMapEntry = {
state?: string;
};
-export type TGcpCertificateMap = {
- name: string;
- description?: string;
- labels?: Record<string, string>;
-};
-
export type TGcpOperationStatus = {
code?: number;
message?: 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.ts
index e1966e2504..9b2e74281c 100644
--- 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.ts
@@ -1,11 +1,15 @@
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";
+import { GcpCertificateManagerScope } from "./gcp-certificate-manager-pki-sync-enums";
+import {
+ TGcpCertificateManagerPkiSyncConfig,
+ TGcpCertificateManagerPkiSyncConfigUpdate
+} from "./gcp-certificate-manager-pki-sync-types";
-export const assertGcpCertificateManagerConfigUpdate = (
+export const resolveGcpCertificateManagerConfigUpdate = (
previous: TGcpCertificateManagerPkiSyncConfig,
- next: TGcpCertificateManagerPkiSyncConfig
+ next: TGcpCertificateManagerPkiSyncConfigUpdate
) => {
if (previous.gcpProjectId && next.gcpProjectId && next.gcpProjectId !== previous.gcpProjectId) {
throw new BadRequestError({
@@ -24,6 +28,15 @@ export const assertGcpCertificateManagerConfigUpdate = (
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.`
});
}
+
+ const effectiveScope = next.scope ?? previous.scope;
+ if (next.certificateMapBinding && effectiveScope && effectiveScope !== GcpCertificateManagerScope.Default) {
+ throw new BadRequestError({
+ message: `Certificate map binding requires the Default scope, but this sync uses "${effectiveScope}". A certificate map entry can only reference a Default-scope certificate.`
+ });
+ }
+
+ return { ...next, ...(effectiveScope ? { scope: effectiveScope } : {}) };
};
export const buildGcpTooManyCertificatesMessage = (certificateMap: string, certificateCount: number) =>
diff --git a/backend/src/services/pki-sync/pki-sync-fns.test.ts b/backend/src/services/pki-sync/pki-sync-fns.test.ts
index b0b4007270..b8a25af106 100644
--- a/backend/src/services/pki-sync/pki-sync-fns.test.ts
+++ b/backend/src/services/pki-sync/pki-sync-fns.test.ts
@@ -116,17 +116,24 @@ describe("getPkiSyncProviderCapabilities: canRunPostSyncCommand", () => {
});
describe("parsePkiSyncErrorMessage", () => {
- // The three sync/import/remove message columns are varchar(255), so an over-long message makes
+ // The three sync/import/remove message columns are varchar(1024), 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)));
+ const message = parsePkiSyncErrorMessage(new Error("x".repeat(2000)));
- expect(message).toHaveLength(255);
+ expect(message).toHaveLength(1024);
expect(message.endsWith("...")).toBe(true);
});
test("caps a thrown string too", () => {
- expect(parsePkiSyncErrorMessage("y".repeat(500))).toHaveLength(255);
+ expect(parsePkiSyncErrorMessage("y".repeat(2000))).toHaveLength(1024);
+ });
+
+ test("leaves a provider message that fits the widened column alone", () => {
+ const provider = `GCP rejected the certificate map entry creation: ${"detail ".repeat(60)}`;
+
+ expect(provider.length).toBeGreaterThan(255);
+ expect(parsePkiSyncErrorMessage(new Error(provider))).toBe(provider);
});
test("leaves a message that already fits untouched", () => {
diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.ts
index fa26f36746..372b7defbe 100644
--- a/backend/src/services/pki-sync/pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-fns.ts
@@ -26,10 +26,13 @@ import { F5_BIG_IP_PKI_SYNC_LIST_OPTION } from "./f5-big-ip/f5-big-ip-pki-sync-c
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 {
+ TGcpCertificateManagerPkiSyncConfig,
+ TGcpCertificateManagerPkiSyncConfigUpdate
+} from "./gcp-certificate-manager/gcp-certificate-manager-pki-sync-types";
import {
assertGcpCertificateManagerCertificateCount,
- assertGcpCertificateManagerConfigUpdate
+ resolveGcpCertificateManagerConfigUpdate
} 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";
@@ -108,17 +111,19 @@ export const getPkiSyncMaxCertificates = (destination: PkiSync): number | undefi
return undefined;
};
-export const assertPkiSyncDestinationConfigUpdate = (
+export const resolvePkiSyncDestinationConfigUpdate = (
destination: PkiSync,
previousConfig: Record<string, unknown>,
nextConfig: Record<string, unknown>
-) => {
+): Record<string, unknown> => {
if (destination === PkiSync.GcpCertificateManager) {
- assertGcpCertificateManagerConfigUpdate(
+ return resolveGcpCertificateManagerConfigUpdate(
previousConfig as TGcpCertificateManagerPkiSyncConfig,
- nextConfig as TGcpCertificateManagerPkiSyncConfig
- );
+ nextConfig as TGcpCertificateManagerPkiSyncConfigUpdate
+ ) as Record<string, unknown>;
}
+
+ return nextConfig;
};
export const assertPkiSyncDestinationConfigAllowsCertificateCount = (
@@ -138,7 +143,7 @@ export const matchesSchema = <T extends ZodSchema>(schema: T, data: unknown): da
return schema.safeParse(data).success;
};
-const MAX_SYNC_MESSAGE_LENGTH = 255;
+const MAX_SYNC_MESSAGE_LENGTH = 1024;
export const truncateSyncMessage = (message: string): string =>
message.length > MAX_SYNC_MESSAGE_LENGTH ? `${message.slice(0, MAX_SYNC_MESSAGE_LENGTH - 3)}...` : message;
diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.ts
index 224e2d10cb..f56c9e1324 100644
--- a/backend/src/services/pki-sync/pki-sync-service.ts
+++ b/backend/src/services/pki-sync/pki-sync-service.ts
@@ -27,11 +27,11 @@ import { PkiSync, PkiSyncStatus } from "./pki-sync-enums";
import { PkiSyncExportFormat } from "./pki-sync-export-fns";
import {
assertPkiSyncDestinationConfigAllowsCertificateCount,
- assertPkiSyncDestinationConfigUpdate,
enterprisePkiSyncCheck,
getPkiSyncMaxCertificates,
getPkiSyncProviderCapabilities,
- listPkiSyncOptions
+ listPkiSyncOptions,
+ resolvePkiSyncDestinationConfigUpdate
} from "./pki-sync-fns";
import { PKI_SYNC_CONNECTION_MAP, PKI_SYNC_NAME_MAP } from "./pki-sync-maps";
import {
@@ -477,9 +477,13 @@ export const pkiSyncServiceFactory = ({
}
}
- if (destinationConfig) {
- assertPkiSyncDestinationConfigUpdate(pkiSync.destination, pkiSync.destinationConfig ?? {}, destinationConfig);
- }
+ const resolvedDestinationConfig = destinationConfig
+ ? resolvePkiSyncDestinationConfigUpdate(
+ pkiSync.destination as PkiSync,
+ pkiSync.destinationConfig ?? {},
+ destinationConfig
+ )
+ : undefined;
let effectiveConnection: { gatewayId?: string | null; gatewayPoolId?: string | null } | undefined;
if (connectionId && connectionId !== pkiSync.connectionId) {
@@ -510,7 +514,7 @@ export const pkiSyncServiceFactory = ({
}
const effectiveSyncOptions = (resolvedSyncOptions ?? pkiSync.syncOptions) as Record<string, unknown> | undefined;
- const effectiveDestinationConfig = (destinationConfig ?? pkiSync.destinationConfig) as
+ const effectiveDestinationConfig = (resolvedDestinationConfig ?? pkiSync.destinationConfig) as
| Record<string, unknown>
| undefined;
@@ -561,7 +565,7 @@ export const pkiSyncServiceFactory = ({
name,
description,
isAutoSyncEnabled,
- destinationConfig,
+ destinationConfig: resolvedDestinationConfig,
syncOptions: resolvedSyncOptions,
subscriberId,
connectionId,
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.mdx
index bd5d517a3e..6a5861ff5d 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/gcp-certificate-manager.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/gcp-certificate-manager.mdx
@@ -27,10 +27,14 @@ Upload certificates managed in Infisical to GCP Certificate Manager as self-mana
| Role | Needed for |
| --- | --- |
- | Certificate Manager Editor (`roles/certificatemanager.editor`) | Uploading and rotating certificates, and maintaining certificate map entries |
+ | Certificate Manager Editor (`roles/certificatemanager.editor`) | Uploading and rotating certificates, and creating 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 |
+ | Certificate Manager Owner (`roles/certificatemanager.owner`) | Anything that deletes: removing certificates, and replacing or removing certificate map entries |
+
+<Warning>
+ `roles/certificatemanager.editor` grants no delete permissions at all. Grant Owner if you enable certificate map binding, even with removal turned off: changing the hostname on a bound sync replaces the map entry, and switching or unbinding the map removes the old one. Both are deletes.
+</Warning>
<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.
@@ -148,7 +152,20 @@ GCP Certificate Manager resource IDs must start with a letter, contain only lowe
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.
+A compiled name longer than 63 characters is shortened: it keeps its first 54 characters and ends with a hyphen and 8 characters of a hash of the whole name. **The start of the name is what survives, and the end is replaced.** The hash is what keeps two certificates from ever collapsing onto one GCP certificate, so nothing depends on any particular placeholder surviving.
+
+Only `{{commonName}}` and `{{applicationName}}` can push a name over the limit, because every other placeholder has a fixed length that Infisical already checks when you save the sync.
+
+For example, with the schema `{{commonName}}-{{certificateId}}` and the common name `checkout-service-eu-west-1.payments.internal.example.com`:
+
+```
+compiled checkout-service-eu-west-1-payments-internal-example-com-550e8400e29b41d4a716446655440000
+in GCP checkout-service-eu-west-1-payments-internal-example-c-3e574b24
+```
+
+The certificate ID is gone entirely. A second certificate for the same common name keeps the same first 54 characters and differs only in the hash, so the two never collide.
+
+Put the identifier first if you want it visible in GCP, or use `{{shortCertificateId}}` to keep names short enough that they are never shortened at all.
## Labels
@@ -193,7 +210,18 @@ For a **global** certificate, a certificate map entry maps a hostname to the cer
**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.
+When disabled, a renewal or a name change creates a new GCP certificate under a new resource name. Whether the old certificate is deleted depends on **Remove Expired/Revoked Certificates**:
+
+- **Removal enabled**: Infisical deletes the old certificate. If a certificate map entry references it, Infisical repoints its own entry first. Anything else pointing at the old certificate has to be repointed manually, and GCP refuses to delete a certificate that is still referenced.
+- **Removal disabled**: the old certificate stays in your GCP project. Infisical never deletes it, and it is no longer tracked by the sync.
+
+<Note>
+ The sync form leaves removal off when you create a sync in the UI. The API leaves it **on** when the field is omitted, so a sync created with Terraform or a script deletes replaced certificates unless you set `canRemoveCertificates` to `false` explicitly.
+</Note>
+
+<Warning>
+ Turning off preserve-on-renewal while leaving removal disabled means every renewal adds a certificate to your GCP project and none are ever removed. GCP allows 1,000 self-managed certificates per project for global certificates and 100 per region. Either leave preserve-on-renewal on, or enable removal so the replaced certificates are cleaned up.
+</Warning>
## Partial Failures
diff --git a/docs/integrations/app-connections/gcp.mdx b/docs/integrations/app-connections/gcp.mdx
index d6d4e35413..c16d0e0bef 100644
--- a/docs/integrations/app-connections/gcp.mdx
+++ b/docs/integrations/app-connections/gcp.mdx
@@ -101,7 +101,7 @@ Infisical supports [service account impersonation](https://cloud.google.com/iam/
--project=PROJECT_ID
```
- Certificate Manager Owner is only needed if you enable certificate removal on a sync.
+ Certificate Manager Owner is needed if you enable certificate removal on a sync, or if you attach a sync to a certificate map. `roles/certificatemanager.editor` grants no delete permissions, and maintaining a map entry replaces or removes it.
</Tab>
</Tabs>
After configuring the appropriate roles, press "DONE".
diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
index 3cb794cbee..3307d4ef64 100644
--- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
@@ -173,7 +173,7 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }
const renderStep = () => {
switch (currentStep.key) {
case "destination":
- return <PkiSyncDestinationFields />;
+ return <PkiSyncDestinationFields isUpdate />;
case "options":
return (
<>
diff --git a/frontend/src/components/pki-syncs/forms/GcpCertificateManagerPkiSyncFields.tsx b/frontend/src/components/pki-syncs/forms/GcpCertificateManagerPkiSyncFields.tsx
index 21d6b5c1bb..86f0b2f4d4 100644
--- a/frontend/src/components/pki-syncs/forms/GcpCertificateManagerPkiSyncFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/GcpCertificateManagerPkiSyncFields.tsx
@@ -64,7 +64,11 @@ const LoadingRow = ({ label }: { label: string }) => (
</div>
);
-export const GcpCertificateManagerPkiSyncFields = () => {
+type Props = {
+ isUpdate?: boolean;
+};
+
+export const GcpCertificateManagerPkiSyncFields = ({ isUpdate }: Props) => {
const { control, setValue } = useFormContext<TGcpCertificateManagerForm>();
const connectionId = useWatch({ name: "connection.id", control });
@@ -77,6 +81,9 @@ export const GcpCertificateManagerPkiSyncFields = () => {
});
const isGlobal = location === GCP_CERTIFICATE_MANAGER_GLOBAL_LOCATION;
+ const immutableFieldHelpText = isUpdate
+ ? "A GCP certificate's project, location and scope are immutable, so this cannot be changed after the sync is created."
+ : undefined;
const isDefaultScope =
(scope ?? GcpCertificateManagerScope.Default) === GcpCertificateManagerScope.Default;
const canBindCertificateMap = isGlobal && isDefaultScope;
@@ -162,7 +169,7 @@ export const GcpCertificateManagerPkiSyncFields = () => {
setValue("destinationConfig.location", "");
setValue("destinationConfig.certificateMapBinding", undefined);
}}
- disabled={!connectionId || isLoadingProjects}
+ disabled={isUpdate || !connectionId || isLoadingProjects}
>
<SelectTrigger className="w-full" isError={Boolean(combinedError)}>
<SelectValue
@@ -178,6 +185,9 @@ export const GcpCertificateManagerPkiSyncFields = () => {
</SelectContent>
</Select>
)}
+ {immutableFieldHelpText && (
+ <FieldDescription>{immutableFieldHelpText}</FieldDescription>
+ )}
<FieldError errors={[combinedError]} />
</Field>
);
@@ -223,7 +233,7 @@ export const GcpCertificateManagerPkiSyncFields = () => {
}
}
}}
- disabled={!gcpProjectId || isLoadingLocations}
+ disabled={isUpdate || !gcpProjectId || isLoadingLocations}
>
<SelectTrigger className="w-full" isError={Boolean(combinedError)}>
<SelectValue
@@ -262,7 +272,7 @@ export const GcpCertificateManagerPkiSyncFields = () => {
setValue("destinationConfig.certificateMapBinding", undefined);
}
}}
- disabled={!location}
+ disabled={isUpdate || !location}
>
<SelectTrigger className="w-full" isError={Boolean(error)}>
<SelectValue placeholder="Select a scope" />
@@ -283,6 +293,7 @@ export const GcpCertificateManagerPkiSyncFields = () => {
(value as GcpCertificateManagerScope) ?? GcpCertificateManagerScope.Default
].description
}
+ {immutableFieldHelpText ? ` ${immutableFieldHelpText}` : ""}
</FieldDescription>
<FieldError errors={[error]} />
</Field>
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx
index 1cb8f0ae38..85454e3aa8 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncDestinationFields.tsx
@@ -17,7 +17,11 @@ import { NetScalerPkiSyncFields } from "./NetScalerPkiSyncFields";
import { NutanixPrismCentralPkiSyncFields } from "./NutanixPrismCentralPkiSyncFields";
import { WindowsServerPkiSyncFields } from "./WindowsServerPkiSyncFields";
-export const PkiSyncDestinationFields = () => {
+type Props = {
+ isUpdate?: boolean;
+};
+
+export const PkiSyncDestinationFields = ({ isUpdate }: Props) => {
const { watch } = useFormContext<TPkiSyncForm>();
const destination = watch("destination");
@@ -36,7 +40,7 @@ export const PkiSyncDestinationFields = () => {
case PkiSync.CloudflareCustomCertificate:
return <CloudflareCustomCertificatePkiSyncFields />;
case PkiSync.GcpCertificateManager:
- return <GcpCertificateManagerPkiSyncFields />;
+ return <GcpCertificateManagerPkiSyncFields isUpdate={isUpdate} />;
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.tsx
index 8ae570a18c..68cc1c3ca2 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/GcpCertificateManagerSyncOptions.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/GcpCertificateManagerSyncOptions.tsx
@@ -89,7 +89,7 @@ export const GcpCertificateManagerSyncOptions = () => {
<>
<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."
+ 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 under a new name, and the old one is only deleted if you also enable removal below. With removal off, replaced certificates stay in your GCP project and count against its limit."
/>
<Field className="mb-4">
<Field orientation="horizontal">