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 PR comments
Carlos Monastyrski0a238689a0f7
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex ce62604785..f4e9720ab2 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -397,14 +397,15 @@ export type TKeyStoreFactory = {pgIncrementBy: (key: string, dto: { incr?: number; expiry?: string; tx?: Knex }) => Promise<number>;pgGetIntItem: (key: string, prefix?: string) => Promise<number | undefined>;// locks- acquireLock(- resources: string[],- duration: number,- settings?: Partial<Settings>- ): Promise<{ release: () => Promise<ExecutionResult> }>;+ acquireLock(resources: string[], duration: number, settings?: Partial<Settings>): Promise<TKeyStoreLock>;waitTillReady: ({ key, waitingCb, keyCheckCb, waitIteration, delay, jitter }: TWaitTillReady) => Promise<void>;};+export type TKeyStoreLock = {+ release: () => Promise<ExecutionResult>;+ extend?: (duration: number) => Promise<TKeyStoreLock>;+};+const pickPrimaryOrSecondaryRedis = (primary: Redis | Cluster, secondaries?: Array<Redis | Cluster>) => {if (!secondaries || !secondaries.length) return primary;const selectedReplica = secondaries[Math.floor(Math.random() * secondaries.length)];diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 18a195e8d2..a1fe3c8c06 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -3179,12 +3179,7 @@ export const AppConnections = {},PALO_ALTO_NETWORKS_LOOKUPS: {connectionId: "The ID of the Palo Alto Networks Connection to read from.",- template:- "The Panorama template to list SSL/TLS service profiles from. Leave it out when the connection points to a firewall.",- isPanorama: "Whether the connection points to a Panorama rather than a firewall.",- templates: "The names of the Panorama templates. Empty when the connection points to a firewall.",- profileName: "The name of the SSL/TLS service profile.",- profileVsys: "The virtual system the profile belongs to, or null for a shared profile."+ template: "The Panorama template to read from. Leave it out when the connection points to a firewall."}};@@ -4590,7 +4585,9 @@ export const PALO_ALTO_NETWORKS_PKI_SYNC_DESTINATION_CONFIG = {"Whether to push every template stack that contains the template to its firewalls after a commit. Applies to Panorama only.",sslTlsServiceProfileName: "The name of the SSL/TLS service profile to point at the synced certificate.",sslTlsServiceProfileVsys:- "The virtual system the SSL/TLS service profile belongs to. Leave it out for a shared profile."+ "The virtual system the SSL/TLS service profile belongs to. Leave it out for a shared profile.",+ replacementCertificateName:+ "The certificate on the device that the SSL/TLS service profile switches to before the synced certificate is deleted. Required when the removal would leave the profile without a certificate."};export const PKI_SYNC_FILTERS = {diff --git a/backend/src/server/routes/v1/app-connection-routers/palo-alto-networks-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/palo-alto-networks-connection-router.tsindex 5133388846..e65472aa07 100644--- a/backend/src/server/routes/v1/app-connection-routers/palo-alto-networks-connection-router.ts+++ b/backend/src/server/routes/v1/app-connection-routers/palo-alto-networks-connection-router.ts@@ -36,8 +36,8 @@ export const registerPaloAltoNetworksConnectionRouter = async (server: FastifyZo}),response: {200: z.object({- isPanorama: z.boolean().describe(AppConnections.PALO_ALTO_NETWORKS_LOOKUPS.isPanorama),- templates: z.string().array().describe(AppConnections.PALO_ALTO_NETWORKS_LOOKUPS.templates)+ isPanorama: z.boolean(),+ templates: z.string().array()})}},@@ -69,8 +69,8 @@ export const registerPaloAltoNetworksConnectionRouter = async (server: FastifyZo200: z.object({sslTlsServiceProfiles: z.object({- name: z.string().describe(AppConnections.PALO_ALTO_NETWORKS_LOOKUPS.profileName),- vsys: z.string().nullable().describe(AppConnections.PALO_ALTO_NETWORKS_LOOKUPS.profileVsys)+ name: z.string(),+ vsys: z.string().nullable()}).array()})@@ -85,4 +85,41 @@ export const registerPaloAltoNetworksConnectionRouter = async (server: FastifyZoreturn { sslTlsServiceProfiles };}});++ server.route({+ method: "GET",+ url: `/:connectionId/certificates`,+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "listPaloAltoNetworksCertificates",+ params: z.object({+ connectionId: z.string().uuid().describe(AppConnections.PALO_ALTO_NETWORKS_LOOKUPS.connectionId)+ }),+ querystring: z.object({+ template: PanOsObjectNameSchema("Template")+ .optional()+ .describe(AppConnections.PALO_ALTO_NETWORKS_LOOKUPS.template)+ }),+ response: {+ 200: z.object({+ certificates: z+ .object({+ name: z.string(),+ vsys: z.string().nullable()+ })+ .array()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const certificates = await server.services.appConnection.paloAltoNetworks.listCertificates(+ { connectionId: req.params.connectionId, template: req.query.template },+ req.permission+ );+ return { certificates };+ }+ });};diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.tsindex 3a7375dc34..6909784bdf 100644--- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts@@ -2,6 +2,7 @@ import { z } from "zod";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { ApiDocsTags } from "@app/lib/api-docs";+import { BadRequestError } from "@app/lib/errors";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { openApiHidden } from "@app/server/lib/schemas";import { getTelemetryDistinctId } from "@app/server/lib/telemetry";@@ -21,6 +22,7 @@ export const registerSyncPkiEndpoints = ({responseSchema,syncOptions,healthCheckTestSchema,+ removalOptionsSchema,enableOperationId = true}: {destination: PkiSync;@@ -47,7 +49,9 @@ export const registerSyncPkiEndpoints = ({isAutoSyncEnabled?: boolean;subscriberId?: string | null;filters?: TPkiSyncFilters | null;+ removalOptions?: Record<string, unknown>;}>;+ removalOptionsSchema?: z.AnyZodObject;healthCheckTestSchema?: z.ZodType<{connectionId: string;applicationId?: string;@@ -511,6 +515,9 @@ export const registerSyncPkiEndpoints = ({params: z.object({pkiSyncId: z.string()}),+ ...(removalOptionsSchema+ ? { body: z.object({ removalOptions: removalOptionsSchema.optional() }).optional() }+ : {}),response: {200: z.object({ message: z.string() })}@@ -518,10 +525,15 @@ export const registerSyncPkiEndpoints = ({onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),handler: async (req) => {const { pkiSyncId } = req.params;+ const { removalOptions } = (req.body as { removalOptions?: Record<string, unknown> } | undefined) ?? {};+ if (removalOptions && !removalOptionsSchema) {+ throw new BadRequestError({ message: `${destinationName} PKI syncs don't accept removal options.` });+ }const result = await server.services.pkiSync.triggerPkiSyncRemoveCertificatesById({- id: pkiSyncId+ id: pkiSyncId,+ removalOptions},req.permission);diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.tsindex 9b16dfac0b..33f0774c63 100644--- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts+++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts@@ -327,6 +327,7 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider, enableOpmatchedCount: z.number(),certificates: PkiSyncCertificateRefSchema.array(),toUnlink: PkiSyncCertificateRefSchema.array(),+ toUnlinkAtDestinationCount: z.number(),willRemoveFromDestination: z.boolean()})}diff --git a/backend/src/services/app-connection/palo-alto-networks/palo-alto-networks-connection-fns.ts b/backend/src/services/app-connection/palo-alto-networks/palo-alto-networks-connection-fns.tsindex 8c4ec77074..2fb31abdd3 100644--- a/backend/src/services/app-connection/palo-alto-networks/palo-alto-networks-connection-fns.ts+++ b/backend/src/services/app-connection/palo-alto-networks/palo-alto-networks-connection-fns.ts@@ -24,7 +24,7 @@ const PAN_OS_DEFAULT_PORT = 443;const PAN_OS_REQUEST_TIMEOUT_MS = 60_000;const PAN_OS_JOB_POLL_INTERVAL_MS = 3_000;const PAN_OS_JOB_TIMEOUT_MS = 15 * 60_000;-const NO_CHANGES_PATTERN = new RE2("no changes to commit", "i");+const NO_CHANGES_PATTERN = new RE2("no changes to commit|same as the previous commit", "i");const JOB_ID_PATTERN = new RE2("^\\d+$");export const PAN_OS_LOCALHOST_ENTRY = "entry[@name='localhost.localdomain']";@@ -44,7 +44,6 @@ type TPanOsXmlNode = Record<string, unknown>;type TPanOsResponse = {"@_status"?: string;- "@_code"?: string;result?: TPanOsXmlNode;msg?: unknown;};@@ -65,7 +64,7 @@ export class PanOsApiError extends Error {const collectText = (node: unknown): string[] => {if (node === undefined || node === null) return [];- if (typeof node === "string" || typeof node === "number") return [String(node).trim()].filter(Boolean);+ if (typeof node === "string") return [node.trim()].filter(Boolean);if (Array.isArray(node)) return node.flatMap(collectText);if (typeof node === "object") {return Object.entries(node)@@ -304,19 +303,36 @@ export const listSslTlsServiceProfiles = async (client: TPanOsClient, template?:return profiles;};+export const listCertificatesWithPrivateKey = async (client: TPanOsClient, template?: string) => {+ const root = getConfigRoot(template);+ const [sharedResult, vsysResult] = await Promise.all([+ client.getConfig(`${root}/shared/certificate`),+ client.getConfig(`${root}/devices/${PAN_OS_LOCALHOST_ENTRY}/vsys`)+ ]);+ const withPrivateKey = (certificates: unknown, vsys: string | null) =>+ getEntries(certificates)+ .filter((entry) => entry["private-key"] !== undefined)+ .map((entry) => ({ name: String(entry["@_name"]), vsys }));++ return [+ ...withPrivateKey(sharedResult.certificate, null),+ ...getEntries(vsysResult.vsys).flatMap((vsys) => withPrivateKey(vsys.certificate, String(vsys["@_name"])))+ ];+};+const UNTRUSTED_TLS_CODES = new Set(["DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT_LOCALLY",- "CERT_HAS_EXPIRED",- "ERR_TLS_CERT_ALTNAME_INVALID"+ "CERT_HAS_EXPIRED"]);const UNTRUSTED_TLS_PATTERN = new RE2(- "self[- ]signed certificate|unable to verify the first certificate|unable to get local issuer|certificate has expired|altnames",+ "self[- ]signed certificate|unable to verify the first certificate|unable to get local issuer|certificate has expired","i");+const HOSTNAME_MISMATCH_PATTERN = new RE2("altnames|does not match certificate", "i");const GATEWAY_TRANSPORT_PATTERN = new RE2("gateway mTLS", "i");const UNREACHABLE_PATTERN = new RE2([...RETRYABLE_NETWORK_ERRORS, "socket disconnected before secure TLS connection", "socket hang up"].join("|"),@@ -330,6 +346,9 @@ export const describePanOsError = (error: unknown) => {if (error instanceof GatewayTransportError || GATEWAY_TRANSPORT_PATTERN.test(detail)) {return "the gateway could not be reached. Check that the gateway is running and connected to its relay.";}+ if (code === "ERR_TLS_CERT_ALTNAME_INVALID" || HOSTNAME_MISMATCH_PATTERN.test(detail)) {+ return `the management interface's TLS certificate isn't issued to this hostname (${detail}). The PAN-OS default certificate is issued to the device's serial number. Connect with a name the certificate lists, install a different management certificate, or turn off Reject Unauthorized.`;+ }if ((code && UNTRUSTED_TLS_CODES.has(code)) || UNTRUSTED_TLS_PATTERN.test(detail)) {return `the management interface's TLS certificate is not trusted (${detail}). Add its CA certificate in the connection's SSL settings, or turn off Reject Unauthorized.`;}diff --git a/backend/src/services/app-connection/palo-alto-networks/palo-alto-networks-connection-service.ts b/backend/src/services/app-connection/palo-alto-networks/palo-alto-networks-connection-service.tsindex 97100b1742..e135fd78fd 100644--- a/backend/src/services/app-connection/palo-alto-networks/palo-alto-networks-connection-service.ts+++ b/backend/src/services/app-connection/palo-alto-networks/palo-alto-networks-connection-service.ts@@ -7,6 +7,7 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enumsimport {describePanOsError,isPanorama,+ listCertificatesWithPrivateKey,listPanoramaTemplates,listSslTlsServiceProfiles,TPanOsClient,@@ -55,5 +56,10 @@ export const paloAltoNetworksConnectionService = (listSslTlsServiceProfiles(client, template));- return { listTemplates, listSslTlsServiceProfiles: listProfiles };+ const listCertificates = async (+ { connectionId, template }: { connectionId: string; template?: string },+ actor: OrgServiceActor+ ) => withClient(connectionId, actor, "certificates", (client) => listCertificatesWithPrivateKey(client, template));++ return { listTemplates, listSslTlsServiceProfiles: listProfiles, listCertificates };};diff --git a/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-fns.test.ts b/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-fns.test.tsindex 787ceec2aa..8cd588a12f 100644--- a/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-fns.test.ts+++ b/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-fns.test.ts@@ -1,16 +1,53 @@-import { buildManagedCertNamePattern } from "./palo-alto-networks-pki-sync-fns";+import {+ assertPaloAltoNetworksUnlinkKeepsProfileCertificate,+ buildManagedCertNamePattern+} from "./palo-alto-networks-pki-sync-fns";const SHORT_ID = "3hFkQ9xZr2mVw8LpT0aBcD";describe("Palo Alto Networks buildManagedCertNamePattern (orphan cleanup detection)", () => {- test("defaults to the INF-{{shortCertificateId}} schema", () => {- const pattern = buildManagedCertNamePattern(undefined);+ test("matches names built from the INF-{{shortCertificateId}} schema", () => {+ const pattern = buildManagedCertNamePattern("INF-{{shortCertificateId}}");expect(pattern.test(`INF-${SHORT_ID}`)).toBe(true);expect(pattern.test("mgmt-cert")).toBe(false);});test("never treats the imported CA chain objects as managed leaf certificates", () => {- const pattern = buildManagedCertNamePattern(undefined);+ const pattern = buildManagedCertNamePattern("INF-{{shortCertificateId}}");expect(pattern.test("INF-CA-0123456789abcdef01234567")).toBe(false);});});++describe("Palo Alto Networks SSL/TLS profile unlink check", () => {+ const pkiSync = {+ syncOptions: { canRemoveCertificates: true },+ destinationConfig: { sslTlsServiceProfileName: "mgmt-profile" }+ };+ const check = (overrides: Partial<Parameters<typeof assertPaloAltoNetworksUnlinkKeepsProfileCertificate>[0]>) => () =>+ assertPaloAltoNetworksUnlinkKeepsProfileCertificate({+ pkiSync,+ remainingCertificateCount: 0,+ unlinkedAtDestinationCount: 1,+ ...overrides+ });++ test("rejects removing the profile's last certificate without a replacement", () => {+ expect(check({})).toThrow(/Choose a replacement certificate/);+ });++ test("allows it when a replacement certificate is given", () => {+ expect(check({ removalOptions: { replacementCertificateName: "backup-cert" } })).not.toThrow();+ });++ test("allows it when another certificate remains on the sync", () => {+ expect(check({ remainingCertificateCount: 1 })).not.toThrow();+ });++ test("allows it when nothing unlinked is on the device", () => {+ expect(check({ unlinkedAtDestinationCount: 0 })).not.toThrow();+ });++ test("allows it when the sync does not remove certificates from the device", () => {+ expect(check({ pkiSync: { ...pkiSync, syncOptions: { canRemoveCertificates: false } } })).not.toThrow();+ });+});diff --git a/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-fns.ts b/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-fns.tsindex dc0f3bc374..070d545cd3 100644--- a/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-fns.ts+++ b/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-fns.ts@@ -5,6 +5,7 @@ import RE2 from "re2";import { TCertificateSyncs } from "@app/db/schemas";import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { BadRequestError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import {describePanOsError,@@ -22,24 +23,25 @@ import { TCertificateDALFactory } from "@app/services/certificate/certificate-daimport { splitPemChain } from "@app/services/certificate/certificate-fns";import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";import { CertificateSyncStatus } from "@app/services/certificate-sync/certificate-sync-enums";-import { TCertificateMap } from "@app/services/pki-sync/pki-sync-types";+import { TCertificateMap, TPkiSyncRemovalOptions } from "@app/services/pki-sync/pki-sync-types";import {buildManagedCertificateNameRegexSource,certificateNameSchemaHasFreeTextPlaceholder,- compileCertificateNameSchema,SHORT_UUID_NAME_REGEX_FRAGMENT,UUID_NAME_REGEX_FRAGMENT} from "../pki-sync-certificate-name-fns";-import { PkiSync } from "../pki-sync-enums";import { PkiSyncError } from "../pki-sync-errors";import { TPkiSyncWithCredentials } from "../pki-sync-types";import {PALO_ALTO_NETWORKS_CA_CERTIFICATE_PREFIX,- PALO_ALTO_NETWORKS_PKI_SYNC_DESTINATIONS,- PALO_ALTO_NETWORKS_PKI_SYNC_LIST_OPTION+ PALO_ALTO_NETWORKS_PKI_SYNC_DESTINATIONS} from "./palo-alto-networks-pki-sync-constants";-import { TPaloAltoNetworksPkiSyncConfig, TPaloAltoNetworksPkiSyncOptions } from "./palo-alto-networks-pki-sync-types";+import {+ TPaloAltoNetworksPkiSyncConfig,+ TPaloAltoNetworksPkiSyncOptions,+ TPaloAltoNetworksSslTlsProfileRemovalOptions+} from "./palo-alto-networks-pki-sync-types";type TPaloAltoNetworksPkiSyncFactoryDeps = {certificateSyncDAL: Pick<@@ -58,6 +60,7 @@ type TPaloAltoNetworksPkiSyncFactoryDeps = {};const CERTIFICATE_ID_PLACEHOLDER = new RE2("\\{\\{(certificateId|shortCertificateId)\\}\\}");+const LEADING_ZEROS = new RE2("^0+");const DEPLOY_PENDING_FLAG = "panOsDeployPending";const REMOVE_PENDING_FLAG = "panOsRemovePending";const PASSPHRASE_VALUE_PATTERN = new RE2("value: \\S+", "g");@@ -67,9 +70,6 @@ const MAX_COMMIT_DESCRIPTION_LENGTH = 255;const hasSyncMetadataFlag = (record: TCertificateSyncs, flag: string) =>Boolean((record.syncMetadata as Record<string, unknown> | null)?.[flag]);-const hasDeployPending = (records: TCertificateSyncs[]) =>- records.some((record) => hasSyncMetadataFlag(record, DEPLOY_PENDING_FLAG));-const escapeXml = (value: string) =>value.replaceAll("&", "&")@@ -114,7 +114,7 @@ const assertDeviceMatchesConfig = async (client: TPanOsClient, config: TPaloAltoshouldRetry: false});}- if (panorama && config.template && !(await listPanoramaTemplates(client)).includes(config.template)) {+ if (panorama && !(await listPanoramaTemplates(client)).includes(config.template!)) {throw new PkiSyncError({message: `Template '${config.template}' was not found on the Panorama. Select an existing template, then sync again.`,shouldRetry: false@@ -287,15 +287,12 @@ const commitAndPush = async (}};-export const buildManagedCertNamePattern = (certificateNameSchema: string | undefined): RE2 => {- const pattern = buildManagedCertificateNameRegexSource(- certificateNameSchema ?? PALO_ALTO_NETWORKS_PKI_SYNC_LIST_OPTION.defaultCertificateNameSchema,- {- uuid: UUID_NAME_REGEX_FRAGMENT,- shortUuid: SHORT_UUID_NAME_REGEX_FRAGMENT,- freeText: "[a-zA-Z0-9_-]*"- }- );+export const buildManagedCertNamePattern = (certificateNameSchema: string): RE2 => {+ const pattern = buildManagedCertificateNameRegexSource(certificateNameSchema, {+ uuid: UUID_NAME_REGEX_FRAGMENT,+ shortUuid: SHORT_UUID_NAME_REGEX_FRAGMENT,+ freeText: "[a-zA-Z0-9_-]*"+ });return new RE2(`^${pattern}$`);};@@ -323,7 +320,7 @@ const planUploads = ({existingCertificates: Map<string, string | undefined>;removePendingCertificateIds: Set<string>;}) => {- const { preserveItemOnRenewal, certificateNameSchema } = pkiSync.syncOptions as TPaloAltoNetworksPkiSyncOptions;+ const { preserveItemOnRenewal } = pkiSync.syncOptions as TPaloAltoNetworksPkiSyncOptions;const plannedUploads: TPlannedUpload[] = [];const activeNames = new Set<string>();const skippedCertificates: Array<{ name: string; reason: string }> = [];@@ -367,17 +364,6 @@ const planUploads = ({oldCertificateIdToRemove = certificate?.renewedFromCertificateId ?? undefined;} else if (certificate?.renewedFromCertificateId && !preserveItemOnRenewal) {replacedName = renewedFromRecord?.externalIdentifier ?? directRecord?.externalIdentifier ?? undefined;- name = compileCertificateNameSchema(- certificateNameSchema ?? PALO_ALTO_NETWORKS_PKI_SYNC_LIST_OPTION.defaultCertificateNameSchema,- {- certificateId,- profileId: certData.profileId,- applicationId: pkiSync.applicationId,- applicationName: pkiSync.applicationName,- commonName: certData.commonName- },- PkiSync.PaloAltoNetworks- );} else if (directRecord?.externalIdentifier && existingCertificates.has(directRecord.externalIdentifier)) {name = directRecord.externalIdentifier;}@@ -449,6 +435,27 @@ export const paloAltoNetworksPkiSyncFactory = ({type TDeployPendingMarker = ReturnType<typeof createDeployPendingMarker>;+ const isIssuedByInfisical = async (+ client: TPanOsClient,+ config: TPaloAltoNetworksPkiSyncConfig,+ projectId: string,+ name: string+ ) => {+ const pem = getEntries(await client.getConfig(getCertificateEntryXpath(config, name)))[0]?.["public-key"];+ if (typeof pem !== "string") return false;+ let serial: string;+ try {+ serial = new crypto.X509Certificate(pem).serialNumber.toLowerCase().replace(LEADING_ZEROS, "");+ } catch {+ return false;+ }+ const matches = await certificateDAL.find({+ projectId,+ $in: { serialNumber: [serial, `0${serial}`, serial.padStart(40, "0")] }+ });+ return matches.length > 0;+ };+const findNamesOwnedByOtherSyncs = (pkiSync: TPkiSyncWithCredentials, names: string[]) =>certificateSyncDAL.findExternalIdentifiersInUse(names, {excludePkiSyncId: pkiSync.id,@@ -474,7 +481,7 @@ export const paloAltoNetworksPkiSyncFactory = ({hasDeviceChanges: boolean;deployPending: TDeployPendingMarker;}) => {- const isDeployPending = hasDeployPending(existingSyncRecords);+ const isDeployPending = existingSyncRecords.some((record) => hasSyncMetadataFlag(record, DEPLOY_PENDING_FLAG));if (hasDeviceChanges || isDeployPending) {await commitAndPush(client, config, { panorama, description });}@@ -486,7 +493,8 @@ export const paloAltoNetworksPkiSyncFactory = ({const importPlannedUploads = async ({client,config,- pkiSyncId,+ pkiSync,+ ownedNames,plannedUploads,existingCertificates,knownCaFingerprints,@@ -494,7 +502,8 @@ export const paloAltoNetworksPkiSyncFactory = ({}: {client: TPanOsClient;config: TPaloAltoNetworksPkiSyncConfig;- pkiSyncId: string;+ pkiSync: TPkiSyncWithCredentials;+ ownedNames: Set<string>;plannedUploads: TPlannedUpload[];existingCertificates: Map<string, string | undefined>;knownCaFingerprints: Set<string | undefined>;@@ -506,8 +515,20 @@ export const paloAltoNetworksPkiSyncFactory = ({for (const upload of plannedUploads) {try {+ const fingerprint = getFingerprint(upload.cert);+ if (+ existingCertificates.has(upload.name) &&+ existingCertificates.get(upload.name) !== fingerprint &&+ !ownedNames.has(upload.name) &&+ !(await isIssuedByInfisical(client, config, pkiSync.projectId, upload.name))+ ) {+ throw new PkiSyncError({+ message: `A certificate named '${upload.name}' already exists on the device and wasn't deployed by Infisical, so it was left unchanged. Change the certificate name schema so it doesn't match an existing certificate.`,+ shouldRetry: false+ });+ }if (upload.certificateId) {- await certificateSyncDAL.claimExternalIdentifier(pkiSyncId, upload.certificateId, upload.name);+ await certificateSyncDAL.claimExternalIdentifier(pkiSync.id, upload.certificateId, upload.name);}await deployPending.mark();@@ -520,7 +541,6 @@ export const paloAltoNetworksPkiSyncFactory = ({);hasDeviceChanges ||= importedCa;- const fingerprint = getFingerprint(upload.cert);if (!fingerprint || existingCertificates.get(upload.name) !== fingerprint) {await importKeyPair(client, config, upload.name, upload.cert, upload.privateKey);hasDeviceChanges = true;@@ -532,7 +552,7 @@ export const paloAltoNetworksPkiSyncFactory = ({failedUploads.push({ name: upload.mapKey, error: describePanOsError(error) });logger.error({ error },- `Palo Alto Networks PKI sync failed to import certificate [syncId=${pkiSyncId}] [name=${upload.name}]`+ `Palo Alto Networks PKI sync failed to import certificate [syncId=${pkiSync.id}] [name=${upload.name}]`);}}@@ -564,28 +584,24 @@ export const paloAltoNetworksPkiSyncFactory = ({const candidates = new Set(existingSyncRecords.map((record) => record.externalIdentifier)- .filter(- (name): name is string =>- Boolean(name) && !activeNames.has(name as string) && existingCertificates.has(name as string)- )+ .filter((name): name is string => !!name && !activeNames.has(name) && existingCertificates.has(name)));if (- CERTIFICATE_ID_PLACEHOLDER.test(- certificateNameSchema ?? PALO_ALTO_NETWORKS_PKI_SYNC_LIST_OPTION.defaultCertificateNameSchema- ) &&+ CERTIFICATE_ID_PLACEHOLDER.test(certificateNameSchema) &&!certificateNameSchemaHasFreeTextPlaceholder(certificateNameSchema)) {const managedPattern = buildManagedCertNamePattern(certificateNameSchema);- existingCertificates.forEach((_, name) => {- if (+ const untrackedMatches = [...existingCertificates.keys()].filter(+ (name) =>managedPattern.test(name) &&!activeNames.has(name) &&+ !candidates.has(name) &&!name.startsWith(PALO_ALTO_NETWORKS_CA_CERTIFICATE_PREFIX)- ) {- candidates.add(name);- }- });+ );+ for (const name of untrackedMatches) {+ if (await isIssuedByInfisical(client, config, pkiSync.projectId, name)) candidates.add(name);+ }}const ownedByOtherSync = await findNamesOwnedByOtherSyncs(pkiSync, [...candidates]);@@ -673,7 +689,10 @@ export const paloAltoNetworksPkiSyncFactory = ({const imports = await importPlannedUploads({client,config,- pkiSyncId: pkiSync.id,+ pkiSync,+ ownedNames: new Set(+ existingSyncRecords.map((record) => record.externalIdentifier).filter((name): name is string => !!name)+ ),plannedUploads,existingCertificates,knownCaFingerprints,@@ -752,8 +771,9 @@ export const paloAltoNetworksPkiSyncFactory = ({const removeCertificates = async (pkiSync: TPkiSyncWithCredentials,certificateNames: string[],- deps?: { certificateMap?: TCertificateMap }+ deps?: { certificateMap?: TCertificateMap; removalOptions?: TPkiSyncRemovalOptions }): Promise<void> => {+ const { replacementCertificateName } = (deps?.removalOptions ?? {}) as TPaloAltoNetworksSslTlsProfileRemovalOptions;const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id);const syncRecordsByCertId = new Map(existingSyncRecords.map((record) => [record.certificateId ?? "", record]));@@ -778,31 +798,65 @@ export const paloAltoNetworksPkiSyncFactory = ({const deferredCertificateIds = await withClient(pkiSync, async (client, panorama, config) => {const [existingCertificates, profileCertificate] = await Promise.all([listCertificates(client, config),- config.sslTlsServiceProfileName && replacementRecords.length ? getProfileCertificate(client, config) : undefined+ config.sslTlsServiceProfileName+ ? getProfileCertificate(client, config).catch((error: unknown) => {+ if (error instanceof PkiSyncError) return undefined;+ throw error;+ })+ : undefined]);const deployPending = createDeployPendingMarker(pkiSync.id);let hasDeviceChanges = false;const deferred = new Set<string>();+ const profileTargets = targets.filter((target) => target.externalIdentifier === profileCertificate);- if (targets.some((target) => target.externalIdentifier === profileCertificate)) {+ if (profileTargets.length) {const replacementOnDevice = replacementRecords.find((record) => record.externalIdentifier && existingCertificates.has(record.externalIdentifier));- if (replacementOnDevice) {+ let replacementName = replacementOnDevice?.externalIdentifier ?? undefined;++ if (replacementCertificateName) {+ const isReplacementVisible =+ existingCertificates.has(replacementCertificateName) ||+ (config.sslTlsServiceProfileVsys+ ? (await listCertificates(client, config, config.sslTlsServiceProfileVsys)).has(+ replacementCertificateName+ )+ : false);+ if (+ !isReplacementVisible ||+ targets.some((target) => target.externalIdentifier === replacementCertificateName)+ ) {+ throw new PkiSyncError({+ message: `Replacement certificate '${replacementCertificateName}' isn't on the device or is being removed. Choose another one for SSL/TLS service profile '${config.sslTlsServiceProfileName}'.`,+ shouldRetry: false+ });+ }+ replacementName = replacementCertificateName;+ }++ if (replacementName) {await deployPending.mark();await client.editConfig(`${getProfileXpath(config)}/certificate`,- `<certificate>${replacementOnDevice.externalIdentifier}</certificate>`+ `<certificate>${replacementName}</certificate>`);hasDeviceChanges = true;- await certificateSyncDAL.clearSyncMetadataFlag(pkiSync.id, REMOVE_PENDING_FLAG, undefined, [- replacementOnDevice.certificateId as string- ]);- } else {- targets- .filter((target) => target.externalIdentifier === profileCertificate)- .forEach((target) => deferred.add(target.certificateId));+ const replacementRecord = replacementRecords.find((record) => record.externalIdentifier === replacementName);+ if (replacementRecord) {+ await certificateSyncDAL.clearSyncMetadataFlag(pkiSync.id, REMOVE_PENDING_FLAG, undefined, [+ replacementRecord.certificateId as string+ ]);+ }+ } else if (replacementRecords.length) {+ profileTargets.forEach((target) => deferred.add(target.certificateId));await certificateSyncDAL.setSyncMetadataFlag(pkiSync.id, REMOVE_PENDING_FLAG, [...deferred]);+ } else {+ throw new PkiSyncError({+ message: `SSL/TLS service profile '${config.sslTlsServiceProfileName}' still uses certificate '${profileCertificate}', and PAN-OS won't leave a profile without a certificate. Remove the certificate again and choose a replacement certificate for the profile, or switch the profile to another certificate on the device first.`,+ shouldRetry: false+ });}}@@ -850,3 +904,30 @@ export const paloAltoNetworksPkiSyncFactory = ({return { syncCertificates, removeCertificates, testReachability };};++export const assertPaloAltoNetworksUnlinkKeepsProfileCertificate = ({+ pkiSync,+ remainingCertificateCount,+ unlinkedAtDestinationCount,+ removalOptions+}: {+ pkiSync: { syncOptions: unknown; destinationConfig: unknown };+ remainingCertificateCount: number;+ unlinkedAtDestinationCount: number;+ removalOptions?: TPkiSyncRemovalOptions;+}) => {+ const { canRemoveCertificates } = pkiSync.syncOptions as TPaloAltoNetworksPkiSyncOptions;+ const { sslTlsServiceProfileName } = pkiSync.destinationConfig as TPaloAltoNetworksPkiSyncConfig;+ const { replacementCertificateName } = (removalOptions ?? {}) as TPaloAltoNetworksSslTlsProfileRemovalOptions;+ if (+ !canRemoveCertificates ||+ unlinkedAtDestinationCount === 0 ||+ remainingCertificateCount > 0 ||+ replacementCertificateName+ )+ return;++ throw new BadRequestError({+ message: `This change deletes the certificate that SSL/TLS service profile '${sslTlsServiceProfileName}' uses, and PAN-OS won't leave a profile without a certificate. Choose a replacement certificate, or select another certificate order for the sync.`+ });+};diff --git a/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-schemas.test.ts b/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-schemas.test.tsindex 8d4fac51fc..cad7029c1b 100644--- a/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-schemas.test.ts+++ b/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-schemas.test.ts@@ -1,7 +1,8 @@import {PaloAltoNetworksPkiSyncConfigSchema,PaloAltoNetworksPkiSyncOptionsSchema,- PaloAltoNetworksSslTlsProfilePkiSyncConfigSchema+ PaloAltoNetworksSslTlsProfilePkiSyncConfigSchema,+ PaloAltoNetworksSslTlsProfileRemovalOptionsSchema} from "./palo-alto-networks-pki-sync-schemas";const parseNameSchema = (certificateNameSchema: string) =>@@ -46,3 +47,18 @@ describe("Palo Alto Networks destination config validation", () => {).toBe(false);});});++describe("Palo Alto Networks SSL/TLS profile removal options validation", () => {+ const parse = (value: unknown) => PaloAltoNetworksSslTlsProfileRemovalOptionsSchema.safeParse(value).success;++ test("accepts no replacement and a valid certificate name", () => {+ expect(parse({})).toBe(true);+ expect(parse({ replacementCertificateName: "backup-cert" })).toBe(true);+ });++ test("rejects unknown keys and names PAN-OS would not accept", () => {+ expect(parse({ replacementCertificate: "backup-cert" })).toBe(false);+ expect(parse({ replacementCertificateName: "a<b/>" })).toBe(false);+ expect(parse({ replacementCertificateName: "x".repeat(64) })).toBe(false);+ });+});diff --git a/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-schemas.ts b/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-schemas.tsindex f01567ea31..ea7cb44092 100644--- a/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-schemas.ts@@ -32,6 +32,14 @@ export const PaloAltoNetworksSslTlsProfilePkiSyncConfigSchema = PaloAltoNetworks.describe(PALO_ALTO_NETWORKS_PKI_SYNC_DESTINATION_CONFIG.sslTlsServiceProfileVsys)});+export const PaloAltoNetworksSslTlsProfileRemovalOptionsSchema = z+ .object({+ replacementCertificateName: PanOsObjectNameSchema("Replacement certificate")+ .optional()+ .describe(PALO_ALTO_NETWORKS_PKI_SYNC_DESTINATION_CONFIG.replacementCertificateName)+ })+ .strict();+const ANY_NAME_PLACEHOLDER = new RE2("\\{\\{\\w+\\}\\}");const CERTIFICATE_NAME_PLACEHOLDER = new RE2("\\{\\{(certificateId|shortCertificateId|commonName)\\}\\}");@@ -45,9 +53,7 @@ export const PaloAltoNetworksPkiSyncOptionsSchema = BasePkiSyncOptionsSchema.extconst PaloAltoNetworksMultiCertificatePkiSyncOptionsSchema = PaloAltoNetworksPkiSyncOptionsSchema.refine(({ certificateNameSchema }) =>- !certificateNameSchema ||- !ANY_NAME_PLACEHOLDER.test(certificateNameSchema) ||- CERTIFICATE_NAME_PLACEHOLDER.test(certificateNameSchema),+ !ANY_NAME_PLACEHOLDER.test(certificateNameSchema) || CERTIFICATE_NAME_PLACEHOLDER.test(certificateNameSchema),{message:"Certificate name schema must include {{shortCertificateId}} or {{commonName}} so each certificate gets its own name, or use no placeholder for a single certificate.",@@ -62,8 +68,10 @@ const buildPaloAltoNetworksPkiSyncSchemas = <>(destination: TDestination,destinationConfig: TConfig,- inputSyncOptions: TInputOptions+ inputSyncOptions: TInputOptions,+ removalOptionsSchema?: z.AnyZodObject) => ({+ removalOptionsSchema,responseSchema: PkiSyncSchema.extend({destination: z.literal(destination),destinationConfig,@@ -90,7 +98,8 @@ const buildPaloAltoNetworksPkiSyncSchemas = <syncOptions: inputSyncOptions.optional(),subscriberId: z.string().uuid().nullish(),connectionId: z.string().uuid().optional(),- filters: UpdatePkiSyncFiltersField+ filters: UpdatePkiSyncFiltersField,+ removalOptions: (removalOptionsSchema ?? z.object({}).strict()).optional()})});@@ -103,5 +112,6 @@ export const PaloAltoNetworksPkiSyncSchemas = buildPaloAltoNetworksPkiSyncSchemaexport const PaloAltoNetworksSslTlsProfilePkiSyncSchemas = buildPaloAltoNetworksPkiSyncSchemas(PkiSync.PaloAltoNetworksSslTlsProfile,PaloAltoNetworksSslTlsProfilePkiSyncConfigSchema,- PaloAltoNetworksPkiSyncOptionsSchema+ PaloAltoNetworksPkiSyncOptionsSchema,+ PaloAltoNetworksSslTlsProfileRemovalOptionsSchema);diff --git a/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-types.ts b/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-types.tsindex 766bdb42fc..3bc8d8525c 100644--- a/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-types.ts+++ b/backend/src/services/pki-sync/palo-alto-networks/palo-alto-networks-pki-sync-types.ts@@ -3,7 +3,8 @@ import { z } from "zod";import {PaloAltoNetworksPkiSyncConfigSchema,PaloAltoNetworksPkiSyncOptionsSchema,- PaloAltoNetworksSslTlsProfilePkiSyncConfigSchema+ PaloAltoNetworksSslTlsProfilePkiSyncConfigSchema,+ PaloAltoNetworksSslTlsProfileRemovalOptionsSchema} from "./palo-alto-networks-pki-sync-schemas";export type TPaloAltoNetworksPkiSyncOptions = z.infer<typeof PaloAltoNetworksPkiSyncOptionsSchema>;@@ -15,3 +16,7 @@ export type TPaloAltoNetworksPkiSyncConfig = z.infer<typeof PaloAltoNetworksPkiS"sslTlsServiceProfileName" | "sslTlsServiceProfileVsys">>;++export type TPaloAltoNetworksSslTlsProfileRemovalOptions = z.infer<+ typeof PaloAltoNetworksSslTlsProfileRemovalOptionsSchema+>;diff --git a/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.ts b/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.tsindex b6c31f87e3..4c41aba33f 100644--- a/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-filter-reconcile-fns.ts@@ -11,11 +11,12 @@ import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-syncimport { TPkiApplicationDALFactory } from "../pki-application/pki-application-dal";import { PkiSync } from "./pki-sync-enums";import { hasAnyPkiSyncFilter } from "./pki-sync-filter-fns";-import { assertPkiSyncCanHoldCertificateCount } from "./pki-sync-fns";+import { assertPkiSyncCanHoldCertificateCount, getPkiSyncUnlinkAssertion } from "./pki-sync-fns";import {TPkiSyncCertificateDiff,TPkiSyncCertificateRef,TPkiSyncFilters,+ TPkiSyncRemovalOptions,TQueuePkiSyncRemoveCertificatesByIdDTO,TQueuePkiSyncSyncCertificatesByIdDTO} from "./pki-sync-types";@@ -86,6 +87,53 @@ const getPkiSyncLinkDestinationTargets = (record: {return [...(record.externalIdentifier ? [record.externalIdentifier] : []), ...files];};+export const findPkiSyncUnlinkIdsAtDestination = async (+ pkiSyncId: string,+ unlinkIds: Set<string>,+ certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findByPkiSyncId" | "primaryNode">+) => {+ if (!unlinkIds.size) return [];++ const linkRecords = await certificateSyncDAL.findByPkiSyncId(pkiSyncId, certificateSyncDAL.primaryNode());++ const destinationTargetsStillHeld = new Set(+ linkRecords+ .filter((record) => record.certificateId && !unlinkIds.has(record.certificateId))+ .flatMap((record) => getPkiSyncLinkDestinationTargets(record))+ );++ return linkRecords+ .filter((record) => {+ if (!record.certificateId || !unlinkIds.has(record.certificateId)) return false;++ const targets = getPkiSyncLinkDestinationTargets(record);+ return targets.length > 0 && targets.every((target) => !destinationTargetsStillHeld.has(target));+ })+ .map((record) => record.certificateId);+};++export const assertPkiSyncUnlinkAllowed = async (+ pkiSync: TPkiSyncReconcileTarget,+ diff: TPkiSyncCertificateDiff,+ certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findByPkiSyncId" | "primaryNode">,+ removalOptions?: TPkiSyncRemovalOptions+) => {+ const assertion = getPkiSyncUnlinkAssertion(pkiSync.destination as PkiSync);+ if (!assertion || !diff.toUnlink.length) return;++ const idsAtDestination = await findPkiSyncUnlinkIdsAtDestination(+ pkiSync.id,+ new Set(diff.toUnlink.map((certificate) => certificate.id)),+ certificateSyncDAL+ );+ assertion({+ pkiSync,+ remainingCertificateCount: diff.matched.length,+ unlinkedAtDestinationCount: idsAtDestination.length,+ removalOptions+ });+};+export const describePkiSyncApplication = async (applicationId: string | null | undefined,pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">@@ -142,7 +190,8 @@ export const applyPkiSyncCertificateDiff = async (diff: TPkiSyncCertificateDiff,deps: TPkiSyncFilterReconcileDeps,auditLogInfo?: AuditLogInfo,- writeFilters?: (tx: Knex) => Promise<void>+ writeFilters?: (tx: Knex) => Promise<void>,+ removalOptions?: TPkiSyncRemovalOptions): Promise<{ linked: TPkiSyncCertificateRef[]; unlinked: TPkiSyncCertificateRef[] }> => {const { certificateSyncDAL, pkiSyncQueue, auditLogService, pkiApplicationDAL } = deps;const { toLink, toUnlink } = diff;@@ -152,25 +201,9 @@ export const applyPkiSyncCertificateDiff = async ((pkiSync.syncOptions as { canRemoveCertificates?: boolean } | undefined)?.canRemoveCertificates);- const linkRecords =- canRemoveCertificates && unlinkIds.size- ? await certificateSyncDAL.findByPkiSyncId(pkiSync.id, certificateSyncDAL.primaryNode())- : [];-- const destinationTargetsStillHeld = new Set(- linkRecords- .filter((record) => record.certificateId && !unlinkIds.has(record.certificateId))- .flatMap((record) => getPkiSyncLinkDestinationTargets(record))- );-- const idsAtDestination = linkRecords- .filter((record) => {- if (!record.certificateId || !unlinkIds.has(record.certificateId)) return false;-- const targets = getPkiSyncLinkDestinationTargets(record);- return targets.length > 0 && targets.every((target) => !destinationTargetsStillHeld.has(target));- })- .map((record) => record.certificateId);+ const idsAtDestination = canRemoveCertificates+ ? await findPkiSyncUnlinkIdsAtDestination(pkiSync.id, unlinkIds, certificateSyncDAL)+ : [];const idsOnlyLinked = [...unlinkIds].filter((id) => !idsAtDestination.includes(id));@@ -216,7 +249,8 @@ export const applyPkiSyncCertificateDiff = async (if (idsAtDestination.length > 0) {await pkiSyncQueue.queuePkiSyncRemoveCertificatesById({syncId: pkiSync.id,- certificateIds: idsAtDestination+ certificateIds: idsAtDestination,+ removalOptions});}diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.tsindex 7498d4111e..b73bce75a7 100644--- a/backend/src/services/pki-sync/pki-sync-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-fns.ts@@ -51,7 +51,10 @@ import {PALO_ALTO_NETWORKS_PKI_SYNC_LIST_OPTION,PALO_ALTO_NETWORKS_SSL_TLS_PROFILE_PKI_SYNC_LIST_OPTION} from "./palo-alto-networks/palo-alto-networks-pki-sync-constants";-import { paloAltoNetworksPkiSyncFactory } from "./palo-alto-networks/palo-alto-networks-pki-sync-fns";+import {+ assertPaloAltoNetworksUnlinkKeepsProfileCertificate,+ paloAltoNetworksPkiSyncFactory+} from "./palo-alto-networks/palo-alto-networks-pki-sync-fns";import {buildManagedCertificateNameRegexSource,certificateNameSchemaAllowsMultipleCertificates,@@ -75,6 +78,7 @@ import {TCertificateMap,THealthCheckTarget,TPkiSyncFilters,+ TPkiSyncRemovalOptions,TPkiSyncSyncResult,TPkiSyncWithCredentials} from "./pki-sync-types";@@ -134,10 +138,21 @@ export const listPkiSyncOptions = () => {.sort((a, b) => a.name.localeCompare(b.name));};-const CONNECTION_SERIALISED_PKI_SYNC_DESTINATIONS = new Set<PkiSync>(PALO_ALTO_NETWORKS_PKI_SYNC_DESTINATIONS);-export const isPkiSyncSerialisedPerConnection = (destination: PkiSync) =>- CONNECTION_SERIALISED_PKI_SYNC_DESTINATIONS.has(destination);+ PALO_ALTO_NETWORKS_PKI_SYNC_DESTINATIONS.includes(destination);++type TPkiSyncUnlinkAssertion = (args: {+ pkiSync: { syncOptions: unknown; destinationConfig: unknown };+ remainingCertificateCount: number;+ unlinkedAtDestinationCount: number;+ removalOptions?: TPkiSyncRemovalOptions;+}) => void;++const PKI_SYNC_UNLINK_ASSERTIONS: Partial<Record<PkiSync, TPkiSyncUnlinkAssertion>> = {+ [PkiSync.PaloAltoNetworksSslTlsProfile]: assertPaloAltoNetworksUnlinkKeepsProfileCertificate+};++export const getPkiSyncUnlinkAssertion = (destination: PkiSync) => PKI_SYNC_UNLINK_ASSERTIONS[destination];export const getPkiSyncProviderCapabilities = (destination: PkiSync) => {const providerOption = PKI_SYNC_LIST_OPTIONS[destination];@@ -556,6 +571,7 @@ export const PkiSyncFns = {certificateSyncDAL: TCertificateSyncDALFactory;certificateDAL: TCertificateDALFactory;certificateMap: TCertificateMap;+ removalOptions?: TPkiSyncRemovalOptions;gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId" | "getGatewayById">;gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;@@ -662,7 +678,8 @@ export const PkiSyncFns = {gatewayPoolService: dependencies.gatewayPoolService});await paloAltoNetworksPkiSync.removeCertificates(pkiSync, certificateNames, {- certificateMap: dependencies.certificateMap+ certificateMap: dependencies.certificateMap,+ removalOptions: dependencies.removalOptions});break;}diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.tsindex f7f4298162..2f09b7d92a 100644--- a/backend/src/services/pki-sync/pki-sync-queue.ts+++ b/backend/src/services/pki-sync/pki-sync-queue.ts@@ -6,7 +6,7 @@ import { randomUUID } from "crypto";import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { KeyStorePrefixes, TKeyStoreFactory, TKeyStoreLock } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { logger } from "@app/lib/logger";import { highCardinalityMeter } from "@app/lib/telemetry/metrics";@@ -106,6 +106,7 @@ type PkiSyncActionJob = Job<const JITTER_MS = 10 * 1000;const HOST_SERIALISATION_LOCK_TTL_MS = 5 * 60 * 1000;+const PKI_SYNC_LOCK_TTL_MS = 5 * 60 * 1000;const REQUEUE_MS = 30 * 1000;const REQUEUE_LIMIT = 30;@@ -619,7 +620,7 @@ export const pkiSyncQueueFactory = ({const $handleRemoveCertificatesJob = async (job: TPkiSyncRemoveCertificatesDTO, pkiSync: TPkiSyncRaw) => {const {- data: { syncId, auditLogInfo, deleteSyncOnComplete, certificateIds: certificateIdsToRemove }+ data: { syncId, auditLogInfo, deleteSyncOnComplete, certificateIds: certificateIdsToRemove, removalOptions }} = job;await pkiSyncDAL.updateById(syncId, {@@ -657,6 +658,7 @@ export const pkiSyncQueueFactory = ({certificateSyncDAL,certificateDAL,certificateMap,+ removalOptions,gatewayV2Service,gatewayPoolService,keyStore@@ -726,6 +728,25 @@ export const pkiSyncQueueFactory = ({}};+ const $keepLocksAlive = (syncId: string, locks: Array<TKeyStoreLock | null>) => {+ let held = locks.filter((lock): lock is TKeyStoreLock => Boolean(lock));+ const timer = setInterval(() => {+ void Promise.all(+ held.map((current) =>+ current.extend+ ? current.extend(PKI_SYNC_LOCK_TTL_MS).catch((error: unknown) => {+ logger.warn(error, `Failed to extend PKI sync lock [syncId=${syncId}]`);+ return current;+ })+ : Promise.resolve(current)+ )+ ).then((extended) => {+ held = extended;+ });+ }, PKI_SYNC_LOCK_TTL_MS / 4);+ return { stop: () => clearInterval(timer) };+ };+const $handleAcquireLockFailure = async (job: PkiSyncActionJob) => {const { syncId } = job.data;@@ -835,8 +856,7 @@ export const pkiSyncQueueFactory = ({const needsHostSerialisation =(needsConnectionSlot && getPkiSyncProviderCapabilities(pkiSync.destination).canRunHealthCheckCommand) ||- (isPkiSyncSerialisedPerConnection(pkiSync.destination) &&- (job.name === QueueJobs.PkiSyncSyncCertificates || job.name === QueueJobs.PkiSyncRemoveCertificates));+ isPkiSyncSerialisedPerConnection(pkiSync.destination);const targetHost = getPkiSyncTargetHost(pkiSync.destinationConfig);@@ -870,7 +890,7 @@ export const pkiSyncQueueFactory = ({lock = await keyStore.acquireLock([KeyStorePrefixes.PkiSyncLock(syncId)],// PKI syncs can take excessive amounts of time so we need to keep it locked- 5 * 60 * 1000+ PKI_SYNC_LOCK_TTL_MS);} catch (e) {if (needsConnectionSlot) await $releaseConnectionConcurrency(connectionId, targetHost);@@ -880,6 +900,10 @@ export const pkiSyncQueueFactory = ({return;}+ const keepAlive = isPkiSyncSerialisedPerConnection(pkiSync.destination)+ ? $keepLocksAlive(syncId, [lock, connectionLock])+ : undefined;+try {switch (job.name) {case QueueJobs.PkiSyncSyncCertificates: {@@ -896,6 +920,7 @@ export const pkiSyncQueueFactory = ({throw new Error(`Unhandled PKI Sync Job ${String(job.name)}`);}} finally {+ keepAlive?.stop();if (needsConnectionSlot) await $releaseConnectionConcurrency(connectionId, targetHost);await Promise.allSettled([lock.release(), connectionLock?.release()]);diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.tsindex 1afb93ed7b..07f773b3c2 100644--- a/backend/src/services/pki-sync/pki-sync-service.ts+++ b/backend/src/services/pki-sync/pki-sync-service.ts@@ -49,7 +49,9 @@ import { hasAnyPkiSyncFilter, PKI_SYNC_FILTER_KINDS, PKI_SYNC_PREVIEW_PAGE_SIZEimport {applyPkiSyncCertificateDiff,assertPkiSyncCanHoldMatchedCertificates,+ assertPkiSyncUnlinkAllowed,computePkiSyncCertificateDiff,+ findPkiSyncUnlinkIdsAtDestination,TPkiSyncReconcileTarget,withPkiSyncFilterLock} from "./pki-sync-filter-reconcile-fns";@@ -58,6 +60,7 @@ import {assertPkiSyncCertificateCapsAllowCount,assertPkiSyncLicense,getPkiSyncProviderCapabilities,+ getPkiSyncUnlinkAssertion,listPkiSyncOptions,resolvePkiSyncDestinationConfigUpdate} from "./pki-sync-fns";@@ -96,6 +99,7 @@ import {TPkiSyncFilterPreview,TPkiSyncFilters,TPkiSyncRaw,+ TPkiSyncRemovalOptions,TPreviewPkiSyncFiltersDTO,TRemoveCertificatesFromPkiSyncDTO,TSearchPkiSyncCertificateOrdersDTO,@@ -338,10 +342,8 @@ export const pkiSyncServiceFactory = ({connection: { id: string; app: AppConnection };destinationConfig: Record<string, unknown> | null | undefined;}) => {- if (connection.app !== AppConnection.PaloAltoNetworks) {- if (connection.app !== AppConnection.LDAP) return;- if (!getPkiSyncTargetHost(destinationConfig)) return;- }+ if (connection.app !== AppConnection.LDAP && connection.app !== AppConnection.PaloAltoNetworks) return;+ if (connection.app === AppConnection.LDAP && !getPkiSyncTargetHost(destinationConfig)) return;await pkiSyncHealthCheckQueue.testTargetHostReachable({destination,@@ -623,16 +625,22 @@ export const pkiSyncServiceFactory = ({const $reconcileFilters = async (pkiSync: TPkiSyncReconcileTarget,filters: TPkiSyncFilters | null | undefined,- opts: { auditLogInfo?: AuditLogInfo; writeFilters?: (tx: Knex) => Promise<void> } = {}+ opts: {+ auditLogInfo?: AuditLogInfo;+ writeFilters?: (tx: Knex) => Promise<void>;+ removalOptions?: TPkiSyncRemovalOptions;+ } = {}): Promise<{ linked: TPkiSyncCertificateRef[]; unlinked: TPkiSyncCertificateRef[] }> => {const diff = await computePkiSyncCertificateDiff(pkiSync, filters, { certificateDAL, certificateSyncDAL });assertPkiSyncCanHoldMatchedCertificates(pkiSync, diff.matched.length);+ await assertPkiSyncUnlinkAllowed(pkiSync, diff, certificateSyncDAL, opts.removalOptions);return applyPkiSyncCertificateDiff(pkiSync,diff,{ certificateDAL, certificateSyncDAL, pkiSyncQueue, auditLogService, pkiApplicationDAL },opts.auditLogInfo,- opts.writeFilters+ opts.writeFilters,+ opts.removalOptions);};@@ -811,6 +819,7 @@ export const pkiSyncServiceFactory = ({connectionId,filters,credentials,+ removalOptions,auditLogInfo}: Omit<TUpdatePkiSyncDTO, "projectId">,actor: OrgServiceActor@@ -1060,6 +1069,7 @@ export const pkiSyncServiceFactory = ({await $reconcileFilters(target, filters, {auditLogInfo,+ removalOptions,writeFilters: async (tx) => {await pkiSyncDAL.updateById(id, update, tx);}@@ -1452,7 +1462,7 @@ export const pkiSyncServiceFactory = ({};const triggerPkiSyncRemoveCertificatesById = async (- { id }: Omit<TTriggerPkiSyncRemoveCertificatesByIdDTO, "auditLogInfo" | "projectId">,+ { id, removalOptions }: Omit<TTriggerPkiSyncRemoveCertificatesByIdDTO, "auditLogInfo" | "projectId">,actor: OrgServiceActor) => {const pkiSync = await pkiSyncDAL.findById(id);@@ -1479,7 +1489,7 @@ export const pkiSyncServiceFactory = ({actor);- await pkiSyncQueue.queuePkiSyncRemoveCertificatesById({ syncId: id });+ await pkiSyncQueue.queuePkiSyncRemoveCertificatesById({ syncId: id, removalOptions });return { message: "PKI sync remove job added to queue successfully" };};@@ -1580,6 +1590,15 @@ export const pkiSyncServiceFactory = ({const canRemoveCertificates = Boolean((pkiSync.syncOptions as { canRemoveCertificates?: boolean } | null)?.canRemoveCertificates);+ const toUnlinkAtDestinationCount = getPkiSyncUnlinkAssertion(pkiSync.destination as PkiSync)+ ? (+ await findPkiSyncUnlinkIdsAtDestination(+ pkiSync.id,+ new Set(diff.toUnlink.map((certificate) => certificate.id)),+ certificateSyncDAL+ )+ ).length+ : 0;const permissionFilters = pkiSync.applicationId? await $certificateReadFilters(pkiSync.projectId, pkiSync.applicationId, actor)@@ -1590,6 +1609,7 @@ export const pkiSyncServiceFactory = ({matchedCount: diff.matched.length,certificates: diff.matched.slice(offset, offset + limit),toUnlink: diff.toUnlink,+ toUnlinkAtDestinationCount,willRemoveFromDestination: canRemoveCertificates && diff.toUnlink.length > 0};}@@ -1612,6 +1632,7 @@ export const pkiSyncServiceFactory = ({matchedCount,certificates,toUnlink: diff.toUnlink.filter((certificate) => readableUnlinkIdSet.has(certificate.id)),+ toUnlinkAtDestinationCount,willRemoveFromDestination: canRemoveCertificates && diff.toUnlink.length > 0};}@@ -1636,7 +1657,13 @@ export const pkiSyncServiceFactory = ({await $assertFilterProfilesInApplication(filters, applicationId);if (!hasAnyPkiSyncFilter(filters)) {- return { matchedCount: 0, certificates: [], toUnlink: [], willRemoveFromDestination: false };+ return {+ matchedCount: 0,+ certificates: [],+ toUnlink: [],+ toUnlinkAtDestinationCount: 0,+ willRemoveFromDestination: false+ };}const scope = { projectId: application.projectId, applicationId };@@ -1651,6 +1678,7 @@ export const pkiSyncServiceFactory = ({matchedCount,certificates,toUnlink: [],+ toUnlinkAtDestinationCount: 0,willRemoveFromDestination: false};};diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.tsindex 97766a8bbc..c623fc24ea 100644--- a/backend/src/services/pki-sync/pki-sync-types.ts+++ b/backend/src/services/pki-sync/pki-sync-types.ts@@ -184,6 +184,7 @@ export type TUpdatePkiSyncDTO = {connectionId?: string;filters?: TPkiSyncFilters | null;credentials?: { exportPassword?: string };+ removalOptions?: TPkiSyncRemovalOptions;auditLogInfo: AuditLogInfo;resourceInternalMetadata?: ResourceMetadataDTO;};@@ -224,6 +225,7 @@ export type TTriggerPkiSyncRemoveCertificatesByIdDTO = {id: string;projectId?: string;auditLogInfo: AuditLogInfo;+ removalOptions?: TPkiSyncRemovalOptions;};export type TPreviewPkiSyncFiltersDTO = {@@ -251,6 +253,7 @@ export type TPkiSyncFilterPreview = {matchedCount: number;certificates: TPkiSyncCertificateRef[];toUnlink: TPkiSyncCertificateRef[];+ toUnlinkAtDestinationCount: number;willRemoveFromDestination: boolean;};@@ -336,11 +339,14 @@ export type TQueuePkiSyncRunHealthCheckByIdDTO = {syncId: string;};+export type TPkiSyncRemovalOptions = Record<string, unknown>;+export type TQueuePkiSyncRemoveCertificatesByIdDTO = {syncId: string;auditLogInfo?: AuditLogInfo;deleteSyncOnComplete?: boolean;certificateIds?: string[];+ removalOptions?: TPkiSyncRemovalOptions;failedToAcquireLockCount?: number;};diff --git a/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt b/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txtindex 062cedf999..1edef5258b 100644--- a/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt+++ b/docs/.vale/styles/config/vocabularies/Infisical/canonical/accept.txt@@ -312,7 +312,6 @@ Palo Alto NetworksAltoPAN-OSPanorama-vsysF5BIG-IPiControldiff --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 6a1e308484..79ec24c428 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@@ -211,7 +211,7 @@ 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 under a new resource name. Whether the old certificate is deleted depends on **Allow to remove certificates from destination**:+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 certificates from destination**:- **Removal enabled**: Infisical deletes the old certificate. If a certificate map entry references it, Infisical moves its own entry to the new certificate first. Anything else pointing at the old certificate has to be updated by hand, 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's no longer tracked by the sync.diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdxindex ca938c3ac1..9865534251 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx@@ -151,7 +151,7 @@ Matching is exact, and a certificate has to match every filter you set. Two filt### Dropping a certificate can delete it at the destination-A certificate that leaves a sync is deleted from the destination when **Allow to remove certificates from destination** is enabled, whether it left because it was deleted, because it stopped being active, or because a filter changed.+A certificate that leaves a sync is deleted from the destination when **Remove certificates from destination** is enabled, whether it left because it was deleted, because it stopped being active, or because a filter changed.So a filter edit can be destructive. A load balancer serving a certificate loses it the moment that certificate stops matching. Before you save, Infisical lists the certificates the change would drop and asks you to confirm.@@ -159,7 +159,7 @@ So a filter edit can be destructive. A load balancer serving a certificate loses| Option | Description ||--------|-------------|-| **Allow to remove certificates from destination** | Delete a certificate from the destination once it leaves this sync |+| **Remove certificates from destination** | Delete a certificate from the destination once it leaves this sync || **Include Root CA** | Include the root CA certificate in the chain || **Certificate naming** | Customize how certificates are named in the destination via the Certificate Name Schema (default: `Infisical-{{certificateId}}`) |diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks-ssl-tls-profile.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks-ssl-tls-profile.mdxindex ef84b5accd..61188e6715 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks-ssl-tls-profile.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks-ssl-tls-profile.mdx@@ -1,10 +1,10 @@---title: "Palo Alto Networks SSL/TLS profile"sidebarTitle: "Palo Alto Networks SSL/TLS profile"-description: "Deploy a certificate to a PAN-OS firewall or Panorama template and point an SSL/TLS service profile at it."+description: "Deploy a certificate to a PAN-OS firewall or Panorama template and set it on an SSL/TLS service profile."----A Palo Alto Networks SSL/TLS Profile sync deploys one certificate to a PAN-OS firewall or a Panorama template, then points an existing SSL/TLS service profile at that certificate. Use this sync for a service that reads its certificate from an SSL/TLS service profile, such as the management web interface or a GlobalProtect portal.+A Palo Alto Networks SSL/TLS Profile sync deploys one certificate to a PAN-OS firewall or a Panorama template, then sets it as the certificate of an existing SSL/TLS service profile. Use it for services that take their certificate from a profile, such as the management web interface or a GlobalProtect portal.To deploy several certificates without changing a profile, use a [Palo Alto Networks sync](/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks) instead.@@ -31,13 +31,13 @@ To deploy several certificates without changing a profile, use a [Palo Alto Netw- **Palo Alto Networks Connection**: the connection to the firewall or Panorama- **Template** (Panorama only): the template to import the certificate into- - **SSL/TLS Service Profile**: the profile to point at the synced certificate+ - **SSL/TLS Service Profile**: the profile that uses the synced certificate- **Push to Devices** (Panorama only): whether the sync pushes the committed changes to firewalls (on by default)</Step><Step>Configure the sync options, then select **Continue**:- - **Allow to remove certificates from destination**: delete the old certificate from the device when it's replaced or no longer active in Infisical+ - **Remove certificates from destination**: delete the old certificate from the device when it's replaced or no longer active in Infisical- **Preserve certificate on renewal**: replace the certificate in place when it's renewed (see [Certificate renewal](#certificate-renewal))- **Certificate name schema**: the name of the certificate object on the device, up to 31 characters (use `{{shortCertificateId}}` rather than `{{certificateId}}`, which is too long)- **Auto-sync on change**: sync the certificate as soon as it's issued or renewed@@ -126,29 +126,22 @@ To deploy several certificates without changing a profile, use a [Palo Alto Netw## How it works-Each time it runs, the sync imports the certificate the same way a [Palo Alto Networks sync](/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks#how-it-works) does, then points the SSL/TLS service profile at it. The sync doesn't create the profile or change its other settings.+Each time it runs, the sync imports the certificate the same way a [Palo Alto Networks sync](/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks#how-it-works) does, then sets it as the profile's certificate. The sync doesn't create the profile or change its other settings.## Certificate renewalWhen the certificate is renewed, the result depends on **Preserve certificate on renewal**:- **On (default)**: the sync replaces the certificate object in place, so the profile keeps using it-- **Off**: the sync creates a new certificate object, points the profile at it, and deletes the old one only if **Allow to remove certificates from destination** is on+- **Off**: the sync creates a new certificate object, switches the profile to it, and deletes the old one only if **Remove certificates from destination** is on## Removing the certificate-PAN-OS doesn't let the sync delete the certificate while the profile uses it. If you change the sync's certificate order, the sync points the profile at the new certificate before it deletes the old one.+PAN-OS won't delete a certificate that a profile still uses. When you switch the sync to another certificate order, the sync moves the profile to the new certificate first, then deletes the old one.-To remove the certificate without replacing it:+To remove the certificate without switching orders, pick a **Replacement Certificate** from the device. The field appears in **Remove Certificates**, and when you save an edit that drops the certificate. The sync moves the profile to the replacement, then deletes the synced certificate. Through the API, pass `removalOptions.replacementCertificateName` to the [Remove certificates](/api-reference/endpoints/pki/syncs/palo-alto-networks-ssl-tls-profile/remove-certificates) or [Update](/api-reference/endpoints/pki/syncs/palo-alto-networks-ssl-tls-profile/update) endpoint.-<Steps>- <Step>- On the device, point the SSL/TLS service profile at another certificate, then commit the change.- </Step>- <Step>- Use the [Remove certificates from Palo Alto Networks SSL/TLS Profile](/api-reference/endpoints/pki/syncs/palo-alto-networks-ssl-tls-profile/remove-certificates) endpoint.- </Step>-</Steps>+Without a replacement, the edit isn't saved and **Remove Certificates** fails. The certificate stays on the device.## Manual sync@@ -157,10 +150,7 @@ To sync on demand, use the [Sync certificates to Palo Alto Networks SSL/TLS Prof## FAQ<AccordionGroup>- <Accordion title="Why can this sync hold only one certificate?">- An SSL/TLS service profile uses one certificate at a time. To deploy more certificates to the same device, create a [Palo Alto Networks sync](/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks).- </Accordion>- <Accordion title="Can I point several profiles at the same certificate?">+ <Accordion title="Can several profiles use the same certificate?">Yes. Each sync updates one profile, so create one sync for each profile.</Accordion></AccordionGroup>diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks.mdxindex 2c5f781212..3e0a895784 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks.mdx@@ -6,7 +6,7 @@ description: "Deploy certificates to the certificate store of PAN-OS firewalls aA Palo Alto Networks sync imports certificates and their private keys into the certificate store of a PAN-OS firewall or a Panorama template, then commits the change.-If a service on the device needs to use the certificate, such as the management web interface or a GlobalProtect portal, use a [Palo Alto Networks SSL/TLS Profile sync](/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks-ssl-tls-profile) instead. That sync also points an SSL/TLS service profile at the certificate.+For a certificate that a service on the device uses, such as the management web interface or a GlobalProtect portal, use a [Palo Alto Networks SSL/TLS Profile sync](/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks-ssl-tls-profile) instead. It also sets the certificate on the service's SSL/TLS service profile.## Prerequisites@@ -35,7 +35,7 @@ If a service on the device needs to use the certificate, such as the management<Step>Configure the sync options, then select **Continue**:- - **Allow to remove certificates from destination**: delete a certificate from the device when it's no longer active in Infisical+ - **Remove certificates from destination**: delete a certificate from the device when it's no longer active in Infisical- **Preserve certificate on renewal**: replace the certificate in place when it's renewed (see [Certificate renewal](#certificate-renewal))- **Certificate name schema**: the name of each certificate object on the device, up to 31 characters (use `{{shortCertificateId}}` rather than `{{certificateId}}`, which is too long; see [Certificate name schema](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-name-schema))- **Auto-sync on change**: sync certificates as soon as they're issued or renewed@@ -134,11 +134,11 @@ Each time it runs, the sync:When a certificate is renewed, the result depends on **Preserve certificate on renewal**:- **On (default)**: the sync replaces the certificate object in place, so anything that references it by name uses the renewed certificate-- **Off**: the sync creates a new certificate object, and deletes the old one only if **Allow to remove certificates from destination** is on+- **Off**: the sync creates a new certificate object, and deletes the old one only if **Remove certificates from destination** is on## Removing certificates-If **Allow to remove certificates from destination** is on, the sync deletes the certificate object of a certificate that's no longer active in Infisical. The CA certificate objects stay on the device.+If **Remove certificates from destination** is on, the sync deletes the certificate object of a certificate that's no longer active in Infisical. The CA certificate objects stay on the device.PAN-OS doesn't delete a certificate that's still in use, such as by an SSL/TLS service profile. If that happens, the sync shows the PAN-OS error. Remove the reference on the device, then sync again.@@ -158,7 +158,7 @@ To remove certificates on demand, use the [Remove certificates from Palo Alto Ne<CardGroup cols={2}><Card title="Palo Alto Networks SSL/TLS profile" icon="lock" href="/documentation/platform/pki/applications/certificate-syncs/palo-alto-networks-ssl-tls-profile">- Point an SSL/TLS service profile at a synced certificate.+ Use a synced certificate in an SSL/TLS service profile.</Card><Card title="Renewal" icon="rotate-cw" href="/documentation/platform/pki/applications/certificate-renewal">Renew a certificate, and change its details as part of the renewal.diff --git a/docs/integrations/app-connections/palo-alto-networks.mdx b/docs/integrations/app-connections/palo-alto-networks.mdxindex 2de0b27503..7e1abbb706 100644--- a/docs/integrations/app-connections/palo-alto-networks.mdx+++ b/docs/integrations/app-connections/palo-alto-networks.mdx@@ -4,7 +4,7 @@ sidebarTitle: "Palo Alto Networks"description: "Learn how to configure a Palo Alto Networks connection for Infisical."----A Palo Alto Networks connection authenticates Infisical to a PAN-OS firewall or a Panorama with the username and password of a PAN-OS administrator, so [Palo Alto Networks certificate syncs](/documentation/platform/pki/applications/certificate-syncs/overview) can import certificates and commit the changes. The same connection form works for both device types, and each sync detects whether the device is a firewall or a Panorama.+A Palo Alto Networks connection authenticates Infisical to a PAN-OS firewall or a Panorama with the username and password of a PAN-OS administrator, so [Palo Alto Networks certificate syncs](/documentation/platform/pki/applications/certificate-syncs/overview) can import certificates and commit the changes.<Note>This guide only authenticates Infisical with your Palo Alto Networks device. Once the app connection is ready, you can [use it to set up integrations](#step-3-configure-integrations).diff --git a/frontend/src/components/pki-syncs/PaloAltoNetworksRemovalOptionsFields.tsx b/frontend/src/components/pki-syncs/PaloAltoNetworksRemovalOptionsFields.tsxnew file mode 100644index 0000000000..ad806c98e8--- /dev/null+++ b/frontend/src/components/pki-syncs/PaloAltoNetworksRemovalOptionsFields.tsx@@ -0,0 +1,69 @@+import { Field, FieldDescription, FieldLabel, FilterableSelect } from "@app/components/v3";+import { getPaloAltoNetworksProfileLabel } from "@app/helpers/pkiSyncs";+import {+ TPaloAltoNetworksCertificate,+ usePaloAltoNetworksConnectionListCertificates+} from "@app/hooks/api/appConnections/palo-alto-networks";+import { TPkiSyncRemovalOptions, useListPkiSyncCertificates } from "@app/hooks/api/pkiSyncs";+import { TPaloAltoNetworksSslTlsProfilePkiSync } from "@app/hooks/api/pkiSyncs/types";++type Props = {+ syncId: string;+ connectionId: string;+ destinationConfig: TPaloAltoNetworksSslTlsProfilePkiSync["destinationConfig"];+ value: TPkiSyncRemovalOptions;+ onChange: (value: TPkiSyncRemovalOptions) => void;+};++export const PaloAltoNetworksRemovalOptionsFields = ({+ syncId,+ connectionId,+ destinationConfig,+ value,+ onChange+}: Props) => {+ const { data: certificates = [], isPending } = usePaloAltoNetworksConnectionListCertificates(+ connectionId,+ destinationConfig.template+ );+ const { data: syncCertificates, isPending: isSyncCertificatesPending } =+ useListPkiSyncCertificates(syncId, { limit: 100 });+ const syncCertificateNames = new Set(+ syncCertificates?.certificates.map((certificate) => certificate.externalIdentifier)+ );+ const options = certificates.filter(+ (certificate) =>+ (certificate.vsys === null ||+ certificate.vsys === destinationConfig.sslTlsServiceProfileVsys) &&+ !(certificate.vsys === null && syncCertificateNames.has(certificate.name))+ );+ const replacementCertificateName = value.replacementCertificateName as string | undefined;+ const selected = options.find((certificate) => certificate.name === replacementCertificateName);++ return (+ <Field>+ <FieldLabel>Replacement Certificate</FieldLabel>+ <FilterableSelect+ isClearable+ isLoading={isPending || isSyncCertificatesPending}+ options={options}+ value={selected ?? null}+ onChange={(option) =>+ onChange({+ ...value,+ replacementCertificateName: (option as TPaloAltoNetworksCertificate | null)?.name+ })+ }+ getOptionLabel={(option) =>+ getPaloAltoNetworksProfileLabel(option as TPaloAltoNetworksCertificate)+ }+ getOptionValue={(option) => (option as TPaloAltoNetworksCertificate).name}+ placeholder="Select a certificate on the device"+ />+ <FieldDescription>+ The SSL/TLS service profile can't be left without a certificate. Choose the one it+ should switch to.+ </FieldDescription>+ </Field>+ );+};diff --git a/frontend/src/components/pki-syncs/PkiSyncRemovalOptionsFields.tsx b/frontend/src/components/pki-syncs/PkiSyncRemovalOptionsFields.tsxnew file mode 100644index 0000000000..17ba523550--- /dev/null+++ b/frontend/src/components/pki-syncs/PkiSyncRemovalOptionsFields.tsx@@ -0,0 +1,42 @@+import { PkiSync, TPkiSync, TPkiSyncRemovalOptions } from "@app/hooks/api/pkiSyncs";++import { PaloAltoNetworksRemovalOptionsFields } from "./PaloAltoNetworksRemovalOptionsFields";++type Props = {+ pkiSync: TPkiSync;+ value: TPkiSyncRemovalOptions;+ onChange: (value: TPkiSyncRemovalOptions) => void;+};++export const hasPkiSyncRemovalOptions = (destination: PkiSync) =>+ destination === PkiSync.PaloAltoNetworksSslTlsProfile;++export const arePkiSyncRemovalOptionsComplete = (+ destination: PkiSync,+ { remainingCertificateCount }: { remainingCertificateCount: number },+ value: TPkiSyncRemovalOptions+) => {+ switch (destination) {+ case PkiSync.PaloAltoNetworksSslTlsProfile:+ return remainingCertificateCount > 0 || Boolean(value.replacementCertificateName);+ default:+ return true;+ }+};++export const PkiSyncRemovalOptionsFields = ({ pkiSync, value, onChange }: Props) => {+ switch (pkiSync.destination) {+ case PkiSync.PaloAltoNetworksSslTlsProfile:+ return (+ <PaloAltoNetworksRemovalOptionsFields+ syncId={pkiSync.id}+ connectionId={pkiSync.connection.id}+ destinationConfig={pkiSync.destinationConfig}+ value={value}+ onChange={onChange}+ />+ );+ default:+ return null;+ }+};diff --git a/frontend/src/components/pki-syncs/PkiSyncRemoveCertificatesModal.tsx b/frontend/src/components/pki-syncs/PkiSyncRemoveCertificatesModal.tsxindex f3f871f35e..7403928e78 100644--- a/frontend/src/components/pki-syncs/PkiSyncRemoveCertificatesModal.tsx+++ b/frontend/src/components/pki-syncs/PkiSyncRemoveCertificatesModal.tsx@@ -1,3 +1,4 @@+import { useEffect, useState } from "react";import { EraserIcon } from "lucide-react";import { createNotification } from "@app/components/notifications";@@ -13,7 +14,16 @@ import {AlertDialogTitle} from "@app/components/v3";import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";-import { TPkiSync, useTriggerPkiSyncRemoveCertificates } from "@app/hooks/api/pkiSyncs";+import {+ TPkiSync,+ TPkiSyncRemovalOptions,+ useTriggerPkiSyncRemoveCertificates+} from "@app/hooks/api/pkiSyncs";++import {+ hasPkiSyncRemovalOptions,+ PkiSyncRemovalOptionsFields+} from "./PkiSyncRemovalOptionsFields";type Props = {pkiSync?: TPkiSync;@@ -23,6 +33,11 @@ type Props = {export const PkiSyncRemoveCertificatesModal = ({ isOpen, onOpenChange, pkiSync }: Props) => {const triggerRemoveCertificates = useTriggerPkiSyncRemoveCertificates();+ const [removalOptions, setRemovalOptions] = useState<TPkiSyncRemovalOptions>({});++ useEffect(() => {+ if (isOpen) setRemovalOptions({});+ }, [isOpen]);if (!pkiSync) return null;@@ -33,7 +48,8 @@ export const PkiSyncRemoveCertificatesModal = ({ isOpen, onOpenChange, pkiSync }await triggerRemoveCertificates.mutateAsync({syncId,destination,- projectId+ projectId,+ ...(hasPkiSyncRemovalOptions(destination) ? { removalOptions } : {})});createNotification({@@ -47,15 +63,24 @@ export const PkiSyncRemoveCertificatesModal = ({ isOpen, onOpenChange, pkiSync }return (<AlertDialog open={isOpen} onOpenChange={onOpenChange}><AlertDialogContent>- <AlertDialogHeader>- <AlertDialogMedia>+ <AlertDialogHeader className="sm:grid-rows-[auto]!">+ <AlertDialogMedia className="mb-0 sm:row-span-1!"><EraserIcon /></AlertDialogMedia><AlertDialogTitle>Remove synced certificates from {destinationName}?</AlertDialogTitle>- <AlertDialogDescription>- This removes the certificates synced by Infisical from this {destinationName}{" "}- destination. Certificates you manage manually there are not affected.+ <AlertDialogDescription className="sm:col-span-2">+ This deletes the certificates the sync added to {destinationName}. Certificates added+ there any other way stay.</AlertDialogDescription>+ {isOpen && hasPkiSyncRemovalOptions(destination) && (+ <div className="mt-2 w-full text-wrap sm:col-span-2">+ <PkiSyncRemovalOptionsFields+ pkiSync={pkiSync}+ value={removalOptions}+ onChange={setRemovalOptions}+ />+ </div>+ )}</AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel>diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsxindex eb978a7b49..de8bf6250c 100644--- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx+++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx@@ -35,6 +35,7 @@ import { usePaloAltoNetworksConnectionListTemplates } from "@app/hooks/api/appCoimport {PkiSync,TPkiSync,+ TPkiSyncRemovalOptions,useCanSetHealthCheckCommand,useCanSetPostSyncCommand,usePkiSyncOption,@@ -43,6 +44,11 @@ import {} from "@app/hooks/api/pkiSyncs";import { TPkiSyncFilterPreview } from "@app/hooks/api/pkiSyncs/types";+import {+ arePkiSyncRemovalOptionsComplete,+ hasPkiSyncRemovalOptions,+ PkiSyncRemovalOptionsFields+} from "../PkiSyncRemovalOptionsFields";import {isPaloAltoNetworksTemplateMissing,PALO_ALTO_NETWORKS_TEMPLATE_REQUIRED_MESSAGE@@ -242,7 +248,6 @@ export const EditPkiSyncForm = ({const {handleSubmit,control,- getValues,setError,formState: { isSubmitting, isDirty }} = formMethods;@@ -252,6 +257,7 @@ export const EditPkiSyncForm = ({});const previewFilters = usePreviewPkiSyncFilters();+ const [unlinkRemovalOptions, setUnlinkRemovalOptions] = useState<TPkiSyncRemovalOptions>({});const [pendingUnlink, setPendingUnlink] = useState<{preview: TPkiSyncFilterPreview;formData: TUpdatePkiSyncForm;@@ -261,7 +267,10 @@ export const EditPkiSyncForm = ({onDirtyChange?.(isDirty);}, [isDirty, onDirtyChange]);- const applyUpdate = async ({ connection, ...formData }: TUpdatePkiSyncForm) => {+ const applyUpdate = async (+ { connection, ...formData }: TUpdatePkiSyncForm,+ removalOptions?: TPkiSyncRemovalOptions+ ) => {const hasNewExportPassword = Boolean((formData as { credentials?: { exportPassword?: string } }).credentials?.exportPassword);@@ -272,7 +281,8 @@ export const EditPkiSyncForm = ({...(hasNewExportPassword ? {} : { credentials: undefined }),connectionId: connection.id,projectId: pkiSync.projectId,- destination: pkiSync.destination+ destination: pkiSync.destination,+ ...(removalOptions ? { removalOptions } : {})});createNotification({@@ -290,7 +300,7 @@ export const EditPkiSyncForm = ({isPaloAltoNetworksPkiSync(pkiSync.destination) &&isPaloAltoNetworksTemplateMissing(paloAltoNetworksDevice?.isPanorama,- getValues("destinationConfig")+ formData.destinationConfig)) {setError("destinationConfig.template" as FieldPath<TUpdatePkiSyncForm>, {@@ -312,6 +322,7 @@ export const EditPkiSyncForm = ({});if (preview.toUnlink.length > 0) {+ setUnlinkRemovalOptions({});setPendingUnlink({ preview, formData });return;}@@ -323,6 +334,23 @@ export const EditPkiSyncForm = ({await applyUpdate(formData);};+ const needsUnlinkRemovalOptions = Boolean(+ pendingUnlink &&+ hasPkiSyncRemovalOptions(pkiSync.destination) &&+ (pendingUnlink.formData.syncOptions as { canRemoveCertificates?: boolean } | undefined)+ ?.canRemoveCertificates &&+ pendingUnlink.preview.toUnlinkAtDestinationCount > 0+ );++ const areUnlinkRemovalOptionsComplete =+ !pendingUnlink ||+ !needsUnlinkRemovalOptions ||+ arePkiSyncRemovalOptionsComplete(+ pkiSync.destination,+ { remainingCertificateCount: pendingUnlink.preview.matchedCount },+ unlinkRemovalOptions+ );+const currentStep = steps[selectedStepIndex];const renderStep = () => {@@ -496,15 +524,15 @@ export const EditPkiSyncForm = ({}}><AlertDialogContent>- <AlertDialogHeader>- <AlertDialogMedia>+ <AlertDialogHeader className="sm:grid-rows-[auto]!">+ <AlertDialogMedia className="mb-0 sm:row-span-1!"><AlertTriangleIcon className="text-warning" /></AlertDialogMedia><AlertDialogTitle>{pendingUnlink?.preview.toUnlink.length} certificate{pendingUnlink?.preview.toUnlink.length === 1 ? "" : "s"} will no longer be synced</AlertDialogTitle>- <AlertDialogDescription asChild>+ <AlertDialogDescription asChild className="sm:col-span-2"><div className="flex flex-col gap-2"><p>These certificates no longer match the filters, so this sync will stop holding@@ -525,17 +553,32 @@ export const EditPkiSyncForm = ({)}</div></AlertDialogDescription>+ {needsUnlinkRemovalOptions && (+ <div className="mt-2 w-full text-wrap sm:col-span-2">+ <PkiSyncRemovalOptionsFields+ pkiSync={pkiSync}+ value={unlinkRemovalOptions}+ onChange={setUnlinkRemovalOptions}+ />+ </div>+ )}</AlertDialogHeader><AlertDialogFooter><AlertDialogCancel isDisabled={isSubmitting}>Cancel</AlertDialogCancel><AlertDialogActionvariant="danger"isPending={isSubmitting}+ isDisabled={!areUnlinkRemovalOptionsComplete}onClick={(event) => {event.preventDefault();const pending = pendingUnlink;setPendingUnlink(null);- if (pending) applyUpdate(pending.formData).catch(() => {});+ if (pending) {+ applyUpdate(+ pending.formData,+ needsUnlinkRemovalOptions ? unlinkRemovalOptions : undefined+ ).catch(() => {});+ }}}>Save changesdiff --git a/frontend/src/components/pki-syncs/forms/PaloAltoNetworksPkiSyncFields.tsx b/frontend/src/components/pki-syncs/forms/PaloAltoNetworksPkiSyncFields.tsxindex c2f00e26f5..44db1685fd 100644--- a/frontend/src/components/pki-syncs/forms/PaloAltoNetworksPkiSyncFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PaloAltoNetworksPkiSyncFields.tsx@@ -11,6 +11,7 @@ import {FieldLabel,FilterableSelect,Label,+ Spinner,Toggle,Tooltip,TooltipContent,@@ -86,7 +87,7 @@ export const PaloAltoNetworksPkiSyncFields = ({let profilePlaceholder = "Select an SSL/TLS service profile";if (!connectionId) profilePlaceholder = "Select a connection first";- else if (isDetectingDevice) profilePlaceholder = "Detecting device type...";+ else if (isDetectingDevice) profilePlaceholder = "Loading...";else if (isPanorama && !template) profilePlaceholder = "Select a template first";const deviceError =@@ -118,7 +119,20 @@ export const PaloAltoNetworksPkiSyncFields = ({clearProfile();}}/>- {deviceError && <FieldError className="-mt-2 mb-4" errors={[deviceError]} />}+ {deviceError && <FieldError className="mb-4" errors={[deviceError]} />}+ {connectionId && isDetectingDevice && (+ <FieldDescription className="mb-4 flex items-center gap-2">+ <Spinner size="xs" />+ Detecting device type...+ </FieldDescription>+ )}+ {connectionId && templatesData && (+ <FieldDescription className="mb-4">+ {templatesData.isPanorama+ ? "Palo Alto Networks Panorama: Certificates are imported into the selected template."+ : "Palo Alto Networks Firewall: Certificates are imported into the shared certificate store."}+ </FieldDescription>+ )}{isPanorama && (<Controllername="destinationConfig.template"diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsxindex f5a5c9dda6..fd061d59f7 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx@@ -68,7 +68,7 @@ export const PkiSyncOptionsFields = ({ destination, isUpdate }: Props) => {<SyncSwitchFieldname="syncOptions.canRemoveCertificates"id="can-remove-certificates"- label="Allow to remove certificates from destination"+ label="Remove certificates from destination"description={<>When enabled, Infisical deletes a certificate from the destination once this syncdiff --git a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsxindex 345d3269a2..7f0403290b 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx@@ -14,7 +14,9 @@ import {import { useProject } from "@app/context";import {BOOLEAN_SYNC_OPTION_FIELDS,+ getPaloAltoNetworksProfileLabel,getUnusedExportOptionKeys,+ isPaloAltoNetworksPkiSync,KEY_VALUE_SYNC_OPTION_FIELDS,PKI_SYNC_MAP,VALUE_SYNC_OPTION_FIELDS@@ -26,7 +28,10 @@ import {usePkiSyncOption,usePkiSyncPreviewCertificates} from "@app/hooks/api/pkiSyncs";-import { TPkiSyncFilters } from "@app/hooks/api/pkiSyncs/types";+import {+ TPaloAltoNetworksSslTlsProfilePkiSync,+ TPkiSyncFilters+} from "@app/hooks/api/pkiSyncs/types";import { TPkiSyncForm } from "./schemas/pki-sync-schema";import { buildOrderNameMap, getPkiSyncCertificateCap, hasAnyFilter } from "./pki-sync-filter-fns";@@ -45,6 +50,40 @@ const ReviewFieldLabel = ({ label, children }: { label: string; children?: React</div>);+type TPaloAltoNetworksReviewConfig = Partial<+ TPaloAltoNetworksSslTlsProfilePkiSync["destinationConfig"]+>;++const PaloAltoNetworksReviewFields = ({+ destinationConfig+}: {+ destinationConfig: TPaloAltoNetworksReviewConfig;+}) => (+ <>+ <ReviewFieldLabel label="Device Type">+ {destinationConfig.template ? "Panorama" : "Firewall"}+ </ReviewFieldLabel>+ {destinationConfig.template && (+ <>+ <ReviewFieldLabel label="Template">{destinationConfig.template}</ReviewFieldLabel>+ <ReviewFieldLabel label="Push to Devices">+ <Badge variant={destinationConfig.pushToDevices === false ? "danger" : "success"}>+ {destinationConfig.pushToDevices === false ? "Disabled" : "Enabled"}+ </Badge>+ </ReviewFieldLabel>+ </>+ )}+ {destinationConfig.sslTlsServiceProfileName && (+ <ReviewFieldLabel label="SSL/TLS Service Profile">+ {getPaloAltoNetworksProfileLabel({+ name: destinationConfig.sslTlsServiceProfileName,+ vsys: destinationConfig.sslTlsServiceProfileVsys+ })}+ </ReviewFieldLabel>+ )}+ </>+);+type Props = {applicationId?: string;};@@ -188,6 +227,11 @@ export const PkiSyncReviewFields = ({ applicationId }: Props = {}) => {destinationConfig.sslEnabled && (<ReviewFieldLabel label="WinRM Transport">HTTPS</ReviewFieldLabel>)}+ {isPaloAltoNetworksPkiSync(destination) && destinationConfig && (+ <PaloAltoNetworksReviewFields+ destinationConfig={destinationConfig as TPaloAltoNetworksReviewConfig}+ />+ )}</div></div><div className="flex flex-col gap-3">diff --git a/frontend/src/helpers/pkiSyncs.ts b/frontend/src/helpers/pkiSyncs.tsindex 46ad6b5c5e..4112de53fa 100644--- a/frontend/src/helpers/pkiSyncs.ts+++ b/frontend/src/helpers/pkiSyncs.ts@@ -164,7 +164,7 @@ export const getPkiSyncConnectionApps = (destination: PkiSync): AppConnection[]];export const BOOLEAN_SYNC_OPTION_FIELDS = [- { key: "canRemoveCertificates", label: "Allow to remove certificates from destination" },+ { key: "canRemoveCertificates", label: "Remove certificates from destination" },{ key: "canImportCertificates", label: "Import Certificates" },{ key: "includeRootCa", label: "Include Root CA in Chain" },{ key: "preserveArn", label: "Preserve ARN on Renewal" },diff --git a/frontend/src/hooks/api/appConnections/palo-alto-networks/queries.tsx b/frontend/src/hooks/api/appConnections/palo-alto-networks/queries.tsxindex 59374a6b86..c45933a2c3 100644--- a/frontend/src/hooks/api/appConnections/palo-alto-networks/queries.tsx+++ b/frontend/src/hooks/api/appConnections/palo-alto-networks/queries.tsx@@ -26,7 +26,9 @@ const paloAltoNetworksConnectionKeys = {"ssl-tls-service-profiles",connectionId,template- ] as const+ ] as const,+ listCertificates: (connectionId: string, template?: string) =>+ [...paloAltoNetworksConnectionKeys.all, "certificates", connectionId, template] as const};export const usePaloAltoNetworksConnectionListTemplates = (@@ -51,7 +53,6 @@ export const usePaloAltoNetworksConnectionListTemplates = (return data;},staleTime: DEVICE_LOOKUP_STALE_TIME_MS,- refetchOnWindowFocus: false,...options,enabled: Boolean(connectionId) && (options?.enabled ?? true)});@@ -82,8 +83,31 @@ export const usePaloAltoNetworksConnectionListSslTlsServiceProfiles = (return data.sslTlsServiceProfiles;},staleTime: DEVICE_LOOKUP_STALE_TIME_MS,- refetchOnWindowFocus: false,...options,enabled: Boolean(connectionId) && (options?.enabled ?? true)});};++export type TPaloAltoNetworksCertificate = {+ name: string;+ vsys: string | null;+};++export const usePaloAltoNetworksConnectionListCertificates = (+ connectionId: string,+ template?: string+) => {+ return useQuery({+ queryKey: paloAltoNetworksConnectionKeys.listCertificates(connectionId, template),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ certificates: TPaloAltoNetworksCertificate[] }>(+ `/api/v1/app-connections/palo-alto-networks/${connectionId}/certificates`,+ { params: template ? { template } : {} }+ );++ return data.certificates;+ },+ staleTime: DEVICE_LOOKUP_STALE_TIME_MS,+ enabled: Boolean(connectionId)+ });+};diff --git a/frontend/src/hooks/api/pkiSyncs/mutations.tsx b/frontend/src/hooks/api/pkiSyncs/mutations.tsxindex ef8c6abbf1..b739a13e8e 100644--- a/frontend/src/hooks/api/pkiSyncs/mutations.tsx+++ b/frontend/src/hooks/api/pkiSyncs/mutations.tsx@@ -256,9 +256,14 @@ export const useTriggerPkiSyncImportCertificates = () => {export const useTriggerPkiSyncRemoveCertificates = () => {const queryClient = useQueryClient();return useMutation({- mutationFn: async ({ syncId, destination }: TTriggerPkiSyncRemoveCertificatesDTO) => {+ mutationFn: async ({+ syncId,+ destination,+ removalOptions+ }: TTriggerPkiSyncRemoveCertificatesDTO) => {const { data } = await apiRequest.post(- `/api/v1/cert-manager/syncs/${destination}/${syncId}/remove-certificates`+ `/api/v1/cert-manager/syncs/${destination}/${syncId}/remove-certificates`,+ removalOptions ? { removalOptions } : undefined);return data;diff --git a/frontend/src/hooks/api/pkiSyncs/types/common.ts b/frontend/src/hooks/api/pkiSyncs/types/common.tsindex e930b5951f..710e504ef3 100644--- a/frontend/src/hooks/api/pkiSyncs/types/common.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/common.ts@@ -128,5 +128,6 @@ export type TPkiSyncFilterPreview = {matchedCount: number;certificates: TPkiSyncPreviewCertificate[];toUnlink: { id: string; commonName: string; altNames?: string | null }[];+ toUnlinkAtDestinationCount: number;willRemoveFromDestination: boolean;};diff --git a/frontend/src/hooks/api/pkiSyncs/types/index.ts b/frontend/src/hooks/api/pkiSyncs/types/index.tsindex cf1d52b918..b1e7aaff27 100644--- a/frontend/src/hooks/api/pkiSyncs/types/index.ts+++ b/frontend/src/hooks/api/pkiSyncs/types/index.ts@@ -134,9 +134,12 @@ export type TCreatePkiSyncDTO = TCreatePkiSyncDTOBase & {};};+export type TPkiSyncRemovalOptions = Record<string, unknown>;+export type TUpdatePkiSyncDTO = Partial<Omit<TCreatePkiSyncDTO, "projectId">> & {syncId: string;projectId: string;+ removalOptions?: TPkiSyncRemovalOptions;};export type TDeletePkiSyncDTO = {@@ -161,6 +164,7 @@ export type TTriggerPkiSyncRemoveCertificatesDTO = {syncId: string;destination: PkiSync;projectId: string;+ removalOptions?: TPkiSyncRemovalOptions;};export * from "./aws-certificate-manager-sync";diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsxindex aa6c610d1b..4e8a68f30a 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx@@ -2,6 +2,7 @@ import { useMemo, useState } from "react";import {CheckCircle2Icon,CircleHelpIcon,+ ClockIcon,EllipsisIcon,HistoryIcon,PencilIcon,@@ -71,8 +72,8 @@ const getSyncStatusVariant = (status?: CertificateSyncStatus | null) => {const getSyncStatusIcon = (status?: CertificateSyncStatus | null) => {if (status === CertificateSyncStatus.Succeeded) return <CheckCircle2Icon />;if (status === CertificateSyncStatus.Failed) return <TriangleAlertIcon />;- if (status === CertificateSyncStatus.Running || status === CertificateSyncStatus.Pending)- return <RotateCwIcon />;+ if (status === CertificateSyncStatus.Running) return <RotateCwIcon />;+ if (status === CertificateSyncStatus.Pending) return <ClockIcon />;return <CircleHelpIcon />;};@@ -80,7 +81,7 @@ const getSyncStatusText = (status?: CertificateSyncStatus | null) => {if (status === CertificateSyncStatus.Succeeded) return "Synced";if (status === CertificateSyncStatus.Failed) return "Failed";if (status === CertificateSyncStatus.Running) return "Syncing";- if (status === CertificateSyncStatus.Pending) return "Pending";+ if (status === CertificateSyncStatus.Pending) return "Not Synced";return "Unknown";};diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/PaloAltoNetworksPkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/PaloAltoNetworksPkiSyncDestinationSection.tsxindex 074c2b3374..eac4919853 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/PaloAltoNetworksPkiSyncDestinationSection.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/PaloAltoNetworksPkiSyncDestinationSection.tsx@@ -17,6 +17,10 @@ export const PaloAltoNetworksPkiSyncDestinationSection = ({ pkiSync }: Props) =>return (<>+ <Detail>+ <DetailLabel>Device Type</DetailLabel>+ <DetailValue>{template ? "Panorama" : "Firewall"}</DetailValue>+ </Detail>{template && (<><Detail>diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncOptionsSection/PkiSyncOptionsSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncOptionsSection/PkiSyncOptionsSection.tsxindex c1c4e61c31..dca4302f4d 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncOptionsSection/PkiSyncOptionsSection.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncOptionsSection/PkiSyncOptionsSection.tsx@@ -31,7 +31,7 @@ export const PkiSyncOptionsSection = ({ pkiSync }: Props) => {return (<>- <Separator className="mt-4" />+ <Separator /><Accordion type="multiple" variant="ghost"><AccordionItem value="sync-options"><AccordionTrigger className="py-4">Sync Options</AccordionTrigger>