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
Address greptile comments
Carlos Monastyrski347781fddac1
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.tsindex 9b3f80cd93..a4f26dd7d4 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@@ -13,6 +13,8 @@ import { getGcpAccessToken } from "./gcp-certificate-manager-pki-sync-auth-fns";import {createGcpCertificateManagerClient,executeWithConcurrencyLimit,+ getGcpErrorStatus,+ getGcpHttpStatus,isCertificateInUseError,mapGcpError} from "./gcp-certificate-manager-pki-sync-client";@@ -62,6 +64,7 @@ type TUploadTarget = {pemPrivateKey: string;infisicalCertificateId?: string;renewedFromCertificateId?: string;+ renewedFromResourceName?: string;shouldPatch: boolean;};@@ -115,6 +118,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({gcpProjectId,certificateMapBinding,certificateResourceNames,+ retainResourceNames,userLabels}: {client: ReturnType<typeof createGcpCertificateManagerClient>;@@ -122,6 +126,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({gcpProjectId: string;certificateMapBinding: NonNullable<TGcpCertificateManagerPkiSyncConfig["certificateMapBinding"]>;certificateResourceNames: string[];+ retainResourceNames: string[];userLabels: TGcpCertificateManagerPkiSyncOptions["labels"];}) => {const { certificateMap, hostname } = certificateMapBinding;@@ -142,6 +147,13 @@ export const gcpCertificateManagerPkiSyncFactory = ({const existingEntry = entries.get(entryResourceName);+ const desiredResourceNames = Array.from(+ new Set([+ ...certificateResourceNames,+ ...retainResourceNames.filter((name) => existingEntry?.certificates?.includes(name))+ ])+ );+if (existingEntry && !isInfisicalManaged(existingEntry.labels)) {throw new PkiSyncError({shouldRetry: false,@@ -166,7 +178,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({await client.createCertificateMapEntry({certificateMap,entryId,- certificateResourceNames,+ certificateResourceNames: desiredResourceNames,hostname,labels: buildLabels(userLabels)});@@ -181,19 +193,19 @@ export const gcpCertificateManagerPkiSyncFactory = ({await client.createCertificateMapEntry({certificateMap,entryId,- certificateResourceNames,+ certificateResourceNames: desiredResourceNames,hostname,labels: buildLabels(userLabels)});return;}- if (sameCertificateSet(existingEntry.certificates, certificateResourceNames)) return;+ if (sameCertificateSet(existingEntry.certificates, desiredResourceNames)) return;await client.updateCertificateMapEntryCertificates({certificateMap,entryId,- certificateResourceNames,+ certificateResourceNames: desiredResourceNames,labels: buildLabels(userLabels)});} catch (error) {@@ -271,6 +283,8 @@ export const gcpCertificateManagerPkiSyncFactory = ({} catch (error) {if (error instanceof PkiSyncError) throw error;+ if (getGcpErrorStatus(error) === "NOT_FOUND" || getGcpHttpStatus(error) === 404) return;+if (isCertificateInUseError(error)) {throw new PkiSyncError({shouldRetry: false,@@ -393,6 +407,9 @@ export const gcpCertificateManagerPkiSyncFactory = ({pemPrivateKey: privateKey.trim(),infisicalCertificateId: certificateId,renewedFromCertificateId: renewedFromCertificateId ?? undefined,+ renewedFromResourceName: renewedFromCertificateId+ ? (existingSyncRecord?.externalIdentifier ?? undefined)+ : undefined,shouldPatch: Boolean(existing)}};@@ -417,6 +434,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({const uploadTargets: TUploadTarget[] = [];const activeResourceNames = new Set<string>();const trackedCertificateIds = new Set<string>();+ const retainResourceNames = new Set<string>();for (const [certName, entry] of Object.entries(certificateMap)) {if (entry.certificateId) trackedCertificateIds.add(entry.certificateId);@@ -433,13 +451,20 @@ export const gcpCertificateManagerPkiSyncFactory = ({if ("skipReason" in planned) {skippedCertificates.push({ name: certName, reason: planned.skipReason });+ const record = entry.certificateId ? syncRecordsByCertId.get(entry.certificateId) : undefined;+ if (record?.externalIdentifier) retainResourceNames.add(record.externalIdentifier);} else {activeResourceNames.add(planned.target.resourceName);uploadTargets.push(planned.target);}}- return { uploadTargets, skippedCertificates, activeResourceNames, trackedCertificateIds };+ return { uploadTargets, skippedCertificates, activeResourceNames, trackedCertificateIds, retainResourceNames };+ };++ const $servingResourceName = (target?: TUploadTarget) => {+ if (!target) return undefined;+ return target.shouldPatch ? target.resourceName : target.renewedFromResourceName;};const $uploadCertificate = async ({@@ -497,7 +522,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({]);}- if (target.renewedFromCertificateId) {+ if (target.renewedFromCertificateId && target.renewedFromResourceName === target.resourceName) {await certificateSyncDAL.removeCertificates(pkiSync.id, [target.renewedFromCertificateId]);}@@ -619,14 +644,15 @@ export const gcpCertificateManagerPkiSyncFactory = ({if (record.certificateId) syncRecordsByCertId.set(record.certificateId, record);});- const { uploadTargets, skippedCertificates, activeResourceNames, trackedCertificateIds } = await $planUploads({- certificateMap,- syncRecordsByCertId,- existingCertificates,- gcpProjectId,- location,- preserveItemOnRenewal: syncOptions?.preserveItemOnRenewal ?? true- });+ const { uploadTargets, skippedCertificates, activeResourceNames, trackedCertificateIds, retainResourceNames } =+ await $planUploads({+ certificateMap,+ syncRecordsByCertId,+ existingCertificates,+ gcpProjectId,+ location,+ preserveItemOnRenewal: syncOptions?.preserveItemOnRenewal ?? true+ });if (certificateMapBinding && uploadTargets.length > GCP_MAX_CERTIFICATES_PER_MAP_ENTRY) {throw new PkiSyncError({@@ -645,12 +671,17 @@ export const gcpCertificateManagerPkiSyncFactory = ({(result): result is PromiseFulfilledResult<TUploadTarget> => result.status === "fulfilled");- await $reapOrphanedMapEntries({- client,- pkiSync,- certificates: existingCertificates,- currentCertificateMap: certificateMapBinding?.certificateMap- });+ const failedUploads = 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"+ }));let failedMapEntry: string | undefined;if (certificateMapBinding && successfulUploads.length) {@@ -661,6 +692,10 @@ export const gcpCertificateManagerPkiSyncFactory = ({gcpProjectId,certificateMapBinding,certificateResourceNames: successfulUploads.map(({ value }) => value.resourceName),+ retainResourceNames: [+ ...retainResourceNames,+ ...failedUploads.flatMap(({ target }) => $servingResourceName(target) ?? [])+ ],userLabels});} catch (error) {@@ -672,32 +707,42 @@ export const gcpCertificateManagerPkiSyncFactory = ({}}- 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 mapEntryOutOfSync =+ Boolean(certificateMapBinding) &&+ (Boolean(failedMapEntry) || (uploadTargets.length > 0 && !successfulUploads.length));- 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 (mapEntryOutOfSync) {+ logger.warn(+ { syncId: pkiSync.id, certificateMap: certificateMapBinding?.certificateMap },+ "Skipping GCP certificate map entry cleanup because the entry could not be brought up to date"+ );+ } else {+ await $reapOrphanedMapEntries({+ client,+ pkiSync,+ certificates: existingCertificates,+ currentCertificateMap: certificateMapBinding?.certificateMap+ });+ }++ const { removed, failedRemovals } =+ canRemoveCertificates && !mapEntryOutOfSync+ ? 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: [] };if (failedUploads.length) {logger.error(@@ -708,7 +753,7 @@ export const gcpCertificateManagerPkiSyncFactory = ({const details: TPkiSyncSyncResult["details"] = {};if (skippedCertificates.length) details.skippedCertificates = skippedCertificates;- if (failedUploads.length) details.failedUploads = failedUploads;+ if (failedUploads.length) details.failedUploads = failedUploads.map(({ name, error }) => ({ name, error }));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}`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.tsindex e9414a441e..b0fd948e73 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@@ -130,6 +130,17 @@ describe("GCP Certificate Manager destinationConfig validation", () => {);});+ test("rejects a connection ID that is not a UUID, rather than failing in the DAL", () => {+ expect(+ CreateGcpCertificateManagerPkiSyncSchema.safeParse({+ name: "gcp-sync",+ connectionId: "not-a-uuid",+ destinationConfig: { gcpProjectId: "my-prod-project", location: "global" },+ syncOptions: { certificateNameSchema: "infisical-{{certificateId}}" }+ }).success+ ).toBe(false);+ });+test("rejects certificate map names GCP would refuse", () => {expect(parseConfig({ certificateMapBinding: { certificateMap: "Prod_Map" } }).success).toBe(false);});@@ -139,7 +150,7 @@ describe("GCP Certificate Manager create schema", () => {const createPayload = (overrides: Record<string, unknown>) =>CreateGcpCertificateManagerPkiSyncSchema.safeParse({name: "gcp-sync",- connectionId: "connection-id",+ connectionId: "33333333-3333-3333-3333-333333333333",destinationConfig: { gcpProjectId: "my-prod-project", location: "global" },syncOptions: { certificateNameSchema: "infisical-{{certificateId}}" },...overridesdiff --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.tsindex 94571949ae..c1af212332 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@@ -169,7 +169,7 @@ export const CreateGcpCertificateManagerPkiSyncSchema = zdestinationConfig: GcpCertificateManagerPkiSyncConfigSchema,syncOptions: GcpCertificateManagerPkiSyncOptionsSchema,subscriberId: z.string().nullish(),- connectionId: z.string(),+ connectionId: z.string().uuid(),projectId: z.string().trim().min(1).optional().describe(openApiHidden()),applicationId: z.string().uuid().optional(),certificateIds: z.array(z.string().uuid()).optional()@@ -194,7 +194,7 @@ export const UpdateGcpCertificateManagerPkiSyncSchema = z.object({destinationConfig: GcpCertificateManagerPkiSyncConfigSchema.optional(),syncOptions: GcpCertificateManagerPkiSyncOptionsSchema.optional(),subscriberId: z.string().nullish(),- connectionId: z.string().optional()+ connectionId: z.string().uuid().optional()});export const GcpCertificateManagerPkiSyncListItemSchema = z.object({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.mdxindex c879f6f39f..bd5d517a3e 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@@ -183,17 +183,25 @@ For a **global** certificate, a certificate map entry maps a hostname to the cer- **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.+<Warning>+ Every certificate in the entry must cover the hostname you bind it to through a **Subject Alternative Name**. GCP does not consult the Common Name, so a certificate whose Common Name is `app.example.com` but whose Subject Alternative Names do not include it is rejected with `does not cover map entry hostname`. A wildcard SAN of `*.example.com` covers `app.example.com`.++ For the same reason, keep Subject Alternative Names stable across renewals when an entry matches on hostname. Leave the hostname empty to serve the certificate as the map's primary entry, which has no coverage requirement.+</Warning>+## 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`.+## Partial Failures- For the same reason, keep Subject Alternative Names stable across renewals when an entry matches on hostname.-</Warning>+A sync run never takes a working certificate out of the serving path to reflect a failure elsewhere in the run.++- If one certificate fails to upload, or is skipped, the certificate map entry keeps the copy GCP is already serving for it. Only the certificates that did sync are updated.+- If the certificate map entry itself cannot be updated, the run reports the failure and leaves both the entry and the existing certificates alone. Nothing is deleted until the entry is current again, so a transient error does not become an outage.+- Changing the bound certificate map creates the entry in the new map before the entry in the old map is removed.## Supported Key Algorithms