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
Add FQDN support to PKI Syncs schemas
Carlos Monastyrskidf9e489b4851
diff --git a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-fns.ts b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-fns.tsindex 05a6f335ca..b458a35648 100644--- a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-fns.ts+++ b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-fns.ts@@ -140,10 +140,7 @@ const generateCertificateName = (certificateName: string, pkiSync: TPkiSyncWithCthrow new Error(`Certificate ID cannot be empty after processing certificate name: ${certificateName}`);}- const environment = "global";- const generatedName = certificateNameSchema- .replace(new RE2("\\{\\{certificateId\\}\\}", "g"), certificateId)- .replace(new RE2("\\{\\{environment\\}\\}", "g"), environment);+ const generatedName = certificateNameSchema.replace(new RE2("\\{\\{certificateId\\}\\}", "g"), certificateId);if (generatedName.length > 256 || generatedName.length < 1) {throw new Error(diff --git a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.tsindex 9849b070a3..1d6bfd5503 100644--- a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts@@ -1,8 +1,8 @@-import RE2 from "re2";import { z } from "zod";import { openApiHidden } from "@app/server/lib/schemas";import { AppConnection, AWSRegion } from "@app/services/app-connection/app-connection-enums";+import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";@@ -29,12 +29,7 @@ const AwsCertificateManagerPkiSyncOptionsSchema = z.object({return false;}- const testName = schema- .replace(new RE2("\\{\\{certificateId\\}\\}", "g"), "test-cert-id")- .replace(new RE2("\\{\\{profileId\\}\\}", "g"), "test-profile-id")- .replace(new RE2("\\{\\{commonName\\}\\}", "g"), "test-common-name")- .replace(new RE2("\\{\\{friendlyName\\}\\}", "g"), "test-friendly-name")- .replace(new RE2("\\{\\{environment\\}\\}", "g"), "test-env");+ const testName = buildCertificateNameSchemaTestName(schema);const hasForbiddenChars = AWS_CERTIFICATE_MANAGER_CERTIFICATE_NAMING.FORBIDDEN_CHARACTERS.split("").some((char) => testName.includes(char)@@ -49,7 +44,7 @@ const AwsCertificateManagerPkiSyncOptionsSchema = z.object({},{message:- "Certificate name schema must include {{certificateId}} placeholder and result in names that contain only alphanumeric characters, spaces, hyphens, and underscores and be 1-256 characters long when compiled for AWS Certificate Manager. Available placeholders: {{certificateId}}, {{profileId}}, {{commonName}}, {{friendlyName}}, {{environment}}"+ "Certificate name schema must include {{certificateId}} placeholder and result in names that contain only alphanumeric characters, spaces, hyphens, and underscores and be 1-256 characters long when compiled for AWS Certificate Manager. Available placeholders: {{certificateId}}, {{profileId}}, {{applicationId}}, {{commonName}}"})});diff --git a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-constants.ts b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-constants.tsindex fd325a3f5f..e066b05ff5 100644--- a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-constants.ts+++ b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-constants.ts@@ -37,7 +37,6 @@ export const AWS_SECRETS_MANAGER_PKI_SYNC_CERTIFICATE_NAMING = {export const AWS_SECRETS_MANAGER_PKI_SYNC_DEFAULTS = {INFISICAL_PREFIX: "infisical-",- DEFAULT_ENVIRONMENT: "production",DEFAULT_CERTIFICATE_NAME_SCHEMA: "infisical-{{certificateId}}",DEFAULT_FIELD_MAPPINGS: {certificate: "certificate",diff --git a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-fns.ts b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-fns.tsindex a385247a82..207665f072 100644--- a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-fns.ts+++ b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-fns.ts@@ -53,8 +53,7 @@ const isInfisicalManagedCertificate = (secretName: string, pkiSync: TPkiSyncWithconst certificateNameSchema = syncOptions?.certificateNameSchema;if (certificateNameSchema) {- const environment = AWS_SECRETS_MANAGER_PKI_SYNC_DEFAULTS.DEFAULT_ENVIRONMENT;- return matchesCertificateNameSchema(secretName, environment, certificateNameSchema);+ return matchesCertificateNameSchema(secretName, certificateNameSchema);}return secretName.startsWith(AWS_SECRETS_MANAGER_PKI_SYNC_DEFAULTS.INFISICAL_PREFIX);diff --git a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.tsindex 17fcd62b67..4c634b4a87 100644--- a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts@@ -1,8 +1,8 @@-import RE2 from "re2";import { z } from "zod";import { openApiHidden } from "@app/server/lib/schemas";import { AppConnection, AWSRegion } from "@app/services/app-connection/app-connection-enums";+import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";@@ -37,12 +37,7 @@ const AwsSecretsManagerPkiSyncOptionsSchema = z.object({return false;}- const testName = schema- .replace(new RE2("\\{\\{certificateId\\}\\}", "g"), "test-cert-id")- .replace(new RE2("\\{\\{profileId\\}\\}", "g"), "test-profile-id")- .replace(new RE2("\\{\\{commonName\\}\\}", "g"), "test-common-name")- .replace(new RE2("\\{\\{friendlyName\\}\\}", "g"), "test-friendly-name")- .replace(new RE2("\\{\\{environment\\}\\}", "g"), "test-env");+ const testName = buildCertificateNameSchemaTestName(schema);const hasForbiddenChars = AWS_SECRETS_MANAGER_PKI_SYNC_CERTIFICATE_NAMING.FORBIDDEN_CHARACTERS.split("").some((char) => testName.includes(char)diff --git a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-fns.ts b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-fns.tsindex 6b14475481..f2874f493c 100644--- a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-fns.ts+++ b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-fns.ts@@ -43,8 +43,7 @@ const isInfisicalManagedCertificate = (certificateName: string, pkiSync: TPkiSynconst certificateNameSchema = syncOptions?.certificateNameSchema;if (certificateNameSchema) {- const environment = "global";- return matchesCertificateNameSchema(certificateName, environment, certificateNameSchema);+ return matchesCertificateNameSchema(certificateName, certificateNameSchema);}return certificateName.startsWith("Infisical-PKI-Sync-");diff --git a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.tsindex baa9d5ae08..2ed6e8363d 100644--- a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts@@ -1,8 +1,8 @@-import RE2 from "re2";import { z } from "zod";import { openApiHidden } from "@app/server/lib/schemas";import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";@@ -24,9 +24,7 @@ const AzureKeyVaultPkiSyncOptionsSchema = z.object({(schema) => {if (!schema) return true;- const testName = schema- .replace(new RE2("\\{\\{certificateId\\}\\}", "g"), "")- .replace(new RE2("\\{\\{environment\\}\\}", "g"), "");+ const testName = buildCertificateNameSchemaTestName(schema);const hasForbiddenChars = AZURE_KEY_VAULT_CERTIFICATE_NAMING.FORBIDDEN_CHARACTERS.split("").some((char) =>testName.includes(char)@@ -36,7 +34,7 @@ const AzureKeyVaultPkiSyncOptionsSchema = z.object({},{message:- "Certificate name schema must result in names that contain only alphanumeric characters and hyphens (a-z, A-Z, 0-9, -) and be 1-127 characters long when compiled for Azure Key Vault"+ "Certificate name schema must result in names that contain only alphanumeric characters and hyphens (a-z, A-Z, 0-9, -) and be 1-127 characters long when compiled for Azure Key Vault. Available placeholders: {{certificateId}}, {{profileId}}, {{applicationId}}, {{commonName}}"})});diff --git a/backend/src/services/pki-sync/chef/chef-pki-sync-constants.ts b/backend/src/services/pki-sync/chef/chef-pki-sync-constants.tsindex c466bbd56e..c9da591c2e 100644--- a/backend/src/services/pki-sync/chef/chef-pki-sync-constants.ts+++ b/backend/src/services/pki-sync/chef/chef-pki-sync-constants.ts@@ -18,6 +18,5 @@ export const CHEF_PKI_SYNC_DATA_BAG_NAMING = {export const CHEF_PKI_SYNC_DEFAULTS = {CERTIFICATE_DATA_BAG: "ssl_certificates",ITEM_NAME_TEMPLATE: "{{certificateId}}",- INFISICAL_PREFIX: "Infisical-",- DEFAULT_ENVIRONMENT: "global"+ INFISICAL_PREFIX: "Infisical-"} as const;diff --git a/backend/src/services/pki-sync/chef/chef-pki-sync-fns.ts b/backend/src/services/pki-sync/chef/chef-pki-sync-fns.tsindex bf740c6600..2c5cc14dd0 100644--- a/backend/src/services/pki-sync/chef/chef-pki-sync-fns.ts+++ b/backend/src/services/pki-sync/chef/chef-pki-sync-fns.ts@@ -35,8 +35,7 @@ const isInfisicalManagedCertificate = (certificateName: string, pkiSync: TPkiSynconst certificateNameSchema = syncOptions?.certificateNameSchema;if (certificateNameSchema) {- const environment = CHEF_PKI_SYNC_DEFAULTS.DEFAULT_ENVIRONMENT;- return matchesCertificateNameSchema(certificateName, environment, certificateNameSchema);+ return matchesCertificateNameSchema(certificateName, certificateNameSchema);}return certificateName.startsWith(CHEF_PKI_SYNC_DEFAULTS.INFISICAL_PREFIX);diff --git a/backend/src/services/pki-sync/chef/chef-pki-sync-schemas.ts b/backend/src/services/pki-sync/chef/chef-pki-sync-schemas.tsindex 279f6723c5..4951890547 100644--- a/backend/src/services/pki-sync/chef/chef-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/chef/chef-pki-sync-schemas.ts@@ -1,8 +1,8 @@-import RE2 from "re2";import { z } from "zod";import { openApiHidden } from "@app/server/lib/schemas";import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";@@ -44,12 +44,7 @@ const ChefPkiSyncOptionsSchema = z.object({return false;}- const testName = schema- .replace(new RE2("\\{\\{certificateId\\}\\}", "g"), "test-cert-id")- .replace(new RE2("\\{\\{profileId\\}\\}", "g"), "test-profile-id")- .replace(new RE2("\\{\\{commonName\\}\\}", "g"), "test-common-name")- .replace(new RE2("\\{\\{friendlyName\\}\\}", "g"), "test-friendly-name")- .replace(new RE2("\\{\\{environment\\}\\}", "g"), "test-env");+ const testName = buildCertificateNameSchemaTestName(schema);const hasForbiddenChars = CHEF_PKI_SYNC_CERTIFICATE_NAMING.FORBIDDEN_CHARACTERS.split("").some((char) =>testName.includes(char)diff --git a/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts b/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.tsindex ecf5696ae4..81ba0428d6 100644--- a/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts@@ -1,8 +1,8 @@-import RE2 from "re2";import { z } from "zod";import { openApiHidden } from "@app/server/lib/schemas";import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";@@ -22,9 +22,7 @@ export const CloudflareCustomCertificatePkiSyncOptionsSchema = z.object({(schema) => {if (!schema) return true;- const testName = schema- .replace(new RE2("\\{\\{certificateId\\}\\}", "g"), "")- .replace(new RE2("\\{\\{environment\\}\\}", "g"), "");+ const testName = buildCertificateNameSchemaTestName(schema);const hasForbiddenChars = CLOUDFLARE_CUSTOM_CERTIFICATE_NAMING.FORBIDDEN_CHARACTERS.split("").some((char) =>testName.includes(char)@@ -34,7 +32,7 @@ export const CloudflareCustomCertificatePkiSyncOptionsSchema = z.object({},{message:- "Certificate name schema must result in names that contain only alphanumeric characters, hyphens (-), and underscores (_) and be 1-255 characters long when compiled for Cloudflare"+ "Certificate name schema must result in names that contain only alphanumeric characters, hyphens (-), and underscores (_) and be 1-255 characters long when compiled for Cloudflare. Available placeholders: {{certificateId}}, {{profileId}}, {{applicationId}}, {{commonName}}"})});diff --git a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-fns.test.ts b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-fns.test.tsnew file mode 100644index 0000000000..8ddb6be620--- /dev/null+++ b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-fns.test.ts@@ -0,0 +1,41 @@+import { buildManagedCertNamePattern } from "./f5-big-ip-pki-sync-fns";++const HEX = "550e8400e29b41d4a716446655440000";++describe("F5 BIG-IP buildManagedCertNamePattern (orphan cleanup detection)", () => {+ describe("default pattern (no schema configured)", () => {+ const pattern = buildManagedCertNamePattern(undefined);++ test("matches default Infisical names and their renewal suffixes", () => {+ expect(pattern.test(`Infisical-${HEX}`)).toBe(true);+ expect(pattern.test(`Infisical-${HEX}-chain`)).toBe(true);+ });++ // Deletion safety: never treat a non-Infisical object as managed.+ test("does NOT match unrelated certificate objects", () => {+ expect(pattern.test("prod-clientssl-cert")).toBe(false);+ expect(pattern.test(`Other-${HEX}`)).toBe(false);+ });+ });++ describe('schema "{{commonName}}-{{certificateId}}" (FQDN naming)', () => {+ const pattern = buildManagedCertNamePattern("{{commonName}}-{{certificateId}}");++ test("matches FQDN-based names anchored by the cert ID", () => {+ expect(pattern.test(`app.example.com-${HEX}`)).toBe(true);+ });++ test("still requires the trailing 32-hex cert ID", () => {+ expect(pattern.test("app.example.com-nothex")).toBe(false);+ });+ });++ describe("schema with application ID", () => {+ const pattern = buildManagedCertNamePattern("{{applicationId}}-{{certificateId}}");++ test("matches names built from the application + cert UUID placeholders", () => {+ expect(pattern.test(`${HEX}-${HEX}`)).toBe(true);+ expect(pattern.test(`nothex-${HEX}`)).toBe(false);+ });+ });+});diff --git a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-fns.ts b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-fns.tsindex 46b86c4b87..8f3b464c9b 100644--- a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-fns.ts+++ b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-fns.ts@@ -1,6 +1,5 @@/* eslint-disable no-await-in-loop */import { AxiosError, AxiosRequestConfig } from "axios";-import handlebars from "handlebars";import RE2 from "re2";import { TCertificateSyncs } from "@app/db/schemas";@@ -18,6 +17,8 @@ import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certiimport { CertificateSyncStatus } from "@app/services/certificate-sync/certificate-sync-enums";import { TCertificateMap } from "@app/services/pki-sync/pki-sync-types";+import { compileCertificateNameSchema } 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 { F5_BIG_IP_DEFAULT_PARTITION, F5BigIpProfileType } from "./f5-big-ip-pki-sync-constants";@@ -90,21 +91,29 @@ const buildEncodedObjectId = (partition: string, name: string) => encodeURICompoconst escapeRegex = (s: string) => s.replace(new RE2("[\\\\^$.*+?()\\[\\]{}|/]", "g"), "\\$&");-const buildManagedCertNamePattern = (certificateNameSchema: string | undefined): RE2 => {+export const buildManagedCertNamePattern = (certificateNameSchema: string | undefined): RE2 => {if (!certificateNameSchema) {return new RE2(`^${F5_BIG_IP_DEFAULT_CERT_NAME_PREFIX}[0-9a-f]{32}(-[a-zA-Z0-9]*)?$`);}const CERT_ID_TOKEN = "__INFISICAL_CERT_ID_PLACEHOLDER__";- const ENV_TOKEN = "__INFISICAL_ENV_PLACEHOLDER__";+ const PROFILE_ID_TOKEN = "__INFISICAL_PROFILE_ID_PLACEHOLDER__";+ const APP_ID_TOKEN = "__INFISICAL_APP_ID_PLACEHOLDER__";+ const COMMON_NAME_TOKEN = "__INFISICAL_COMMON_NAME_PLACEHOLDER__";const tokenized = certificateNameSchema.replace(new RE2("\\{\\{certificateId\\}\\}", "g"), CERT_ID_TOKEN)- .replace(new RE2("\\{\\{environment\\}\\}", "g"), ENV_TOKEN);+ .replace(new RE2("\\{\\{profileId\\}\\}", "g"), PROFILE_ID_TOKEN)+ .replace(new RE2("\\{\\{applicationId\\}\\}", "g"), APP_ID_TOKEN)+ .replace(new RE2("\\{\\{commonName\\}\\}", "g"), COMMON_NAME_TOKEN);+ // {{certificateId}}, {{profileId}}, and {{applicationId}} resolve to dash-stripped UUIDs (32 hex chars).+ // {{commonName}} is arbitrary, so match any run of BIG-IP-safe characters.const pattern = escapeRegex(tokenized).replace(new RE2(CERT_ID_TOKEN, "g"), "[0-9a-f]{32}")- .replace(new RE2(ENV_TOKEN, "g"), "global");+ .replace(new RE2(PROFILE_ID_TOKEN, "g"), "[0-9a-f]{32}")+ .replace(new RE2(APP_ID_TOKEN, "g"), "[0-9a-f]{32}")+ .replace(new RE2(COMMON_NAME_TOKEN, "g"), "[a-zA-Z0-9._-]*");return new RE2(`^${pattern}$`);};@@ -836,10 +845,16 @@ export const f5BigIpPkiSyncFactory = ({} else if (certificate?.renewedFromCertificateId && !preserveItemOnRenewal) {const certIdClean = certificateId.replace(new RE2("-", "g"), "");if (certificateNameSchema) {- targetName = handlebars.compile(certificateNameSchema)({- certificateId: certIdClean,- environment: "global"- });+ targetName = compileCertificateNameSchema(+ certificateNameSchema,+ {+ certificateId,+ profileId: certData.profileId,+ applicationId: pkiSync.applicationId,+ commonName: certData.commonName+ },+ PkiSync.F5BigIp+ );} else {targetName = `${F5_BIG_IP_DEFAULT_CERT_NAME_PREFIX}${certIdClean}`;}diff --git a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-schemas.ts b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-schemas.tsindex aff72db7be..2ca7bb7ce2 100644--- a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-schemas.ts@@ -1,8 +1,8 @@-import RE2 from "re2";import { z } from "zod";import { openApiHidden } from "@app/server/lib/schemas";import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";@@ -68,9 +68,7 @@ export const F5BigIpPkiSyncOptionsSchema = z.object({return false;}- const testName = schema- .replace(new RE2("\\{\\{certificateId\\}\\}", "g"), "test-cert-id")- .replace(new RE2("\\{\\{environment\\}\\}", "g"), "test-env");+ const testName = buildCertificateNameSchemaTestName(schema);const hasForbiddenChars = F5_BIG_IP_NAMING.FORBIDDEN_CHARACTERS.split("").some((char) =>testName.includes(char)@@ -80,7 +78,7 @@ export const F5BigIpPkiSyncOptionsSchema = z.object({},{message:- "Certificate name schema must include the {{certificateId}} placeholder and result in names that contain only alphanumeric characters, hyphens (-), underscores (_), and periods (.) and be 1-255 characters long for F5 BIG-IP"+ "Certificate name schema must include the {{certificateId}} placeholder and result in names that contain only alphanumeric characters, hyphens (-), underscores (_), and periods (.) and be 1-255 characters long for F5 BIG-IP. Available placeholders: {{certificateId}}, {{profileId}}, {{applicationId}}, {{commonName}}"})});diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-constants.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-constants.tsindex cf82049c92..774902c925 100644--- a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-constants.ts+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-constants.ts@@ -6,14 +6,14 @@ import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";/*** NetScaler certificate naming constraints.* NetScaler certkey names can contain alphanumeric characters, hyphens, underscores, and periods.- * Must be 1-255 characters long.+ * NetScaler enforces a hard maximum of 63 characters on the certkey name (NITRO error 1106).*/export const NETSCALER_NAMING = {- NAME_PATTERN: new RE2("^[a-zA-Z0-9._-]{1,255}$"),+ NAME_PATTERN: new RE2("^[a-zA-Z0-9._-]{1,63}$"),FORBIDDEN_CHARACTERS: "!@#$%^&*()+=[]{}|\\:;\"'<>,?/~` ",- MAX_NAME_LENGTH: 255,+ MAX_NAME_LENGTH: 63,MIN_NAME_LENGTH: 1,- ALLOWED_CHARACTER_PATTERN: "^[a-zA-Z0-9._-]{1,255}$"+ ALLOWED_CHARACTER_PATTERN: "^[a-zA-Z0-9._-]{1,63}$"} as const;export const NETSCALER_PKI_SYNC_LIST_OPTION = {diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.test.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.test.tsnew file mode 100644index 0000000000..7527b596bb--- /dev/null+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.test.ts@@ -0,0 +1,55 @@+import { buildManagedCertNamePattern } from "./netscaler-pki-sync-fns";++const HEX = "550e8400e29b41d4a716446655440000";++describe("NetScaler buildManagedCertNamePattern (orphan cleanup detection)", () => {+ describe("default pattern (no schema configured)", () => {+ const pattern = buildManagedCertNamePattern(undefined);++ test("matches default Infisical names and their renewal suffixes", () => {+ expect(pattern.test(`Infisical-${HEX}`)).toBe(true);+ expect(pattern.test(`Infisical-${HEX}-1`)).toBe(true);+ });++ // Deletion safety: never treat a non-Infisical certkey as managed.+ test("does NOT match unrelated certkeys", () => {+ expect(pattern.test("wildcard-prod-cert")).toBe(false);+ expect(pattern.test(`Other-${HEX}`)).toBe(false);+ expect(pattern.test(`Infisical-${HEX}.bad`)).toBe(false);+ });+ });++ describe('schema "Infisical-{{certificateId}}"', () => {+ const pattern = buildManagedCertNamePattern("Infisical-{{certificateId}}");++ test("matches managed names, rejects unrelated", () => {+ expect(pattern.test(`Infisical-${HEX}`)).toBe(true);+ expect(pattern.test("Infisical-notavalidid")).toBe(false);+ expect(pattern.test("totally-unrelated")).toBe(false);+ });+ });++ describe('schema "{{commonName}}-{{certificateId}}" (FQDN naming)', () => {+ const pattern = buildManagedCertNamePattern("{{commonName}}-{{certificateId}}");++ test("matches FQDN-based names anchored by the cert ID", () => {+ expect(pattern.test(`app.example.com-${HEX}`)).toBe(true);+ });++ test("still requires the trailing 32-hex cert ID", () => {+ expect(pattern.test("app.example.com-nothex")).toBe(false);+ });+ });++ describe("schema with profile and application IDs", () => {+ const pattern = buildManagedCertNamePattern("{{applicationId}}-{{profileId}}-{{certificateId}}");++ test("matches names built from all three UUID placeholders", () => {+ expect(pattern.test(`${HEX}-${HEX}-${HEX}`)).toBe(true);+ });++ test("rejects when a UUID segment is malformed", () => {+ expect(pattern.test(`${HEX}-nothex-${HEX}`)).toBe(false);+ });+ });+});diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.tsindex 469dff9c81..243857ac6e 100644--- a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts@@ -1,6 +1,5 @@/* eslint-disable no-await-in-loop */import { AxiosError, AxiosRequestConfig } from "axios";-import handlebars from "handlebars";import RE2 from "re2";import { TCertificateSyncs } from "@app/db/schemas";@@ -14,6 +13,8 @@ import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certiimport { CertificateSyncStatus } from "@app/services/certificate-sync/certificate-sync-enums";import { TCertificateMap } from "@app/services/pki-sync/pki-sync-types";+import { compileCertificateNameSchema } 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 { TNetScalerPkiSyncConfig } from "./netscaler-pki-sync-types";@@ -282,21 +283,29 @@ const removeNetScalerCertificate = async (const escapeRegex = (s: string) => s.replace(new RE2("[\\\\^$.*+?()\\[\\]{}|/]", "g"), "\\$&");-const buildManagedCertNamePattern = (certificateNameSchema: string | undefined): RE2 => {+export const buildManagedCertNamePattern = (certificateNameSchema: string | undefined): RE2 => {if (!certificateNameSchema) {return new RE2("^Infisical-[0-9a-f]{32}(-[a-zA-Z0-9]*)?$");}const CERT_ID_TOKEN = "__INFISICAL_CERT_ID_PLACEHOLDER__";- const ENV_TOKEN = "__INFISICAL_ENV_PLACEHOLDER__";+ const PROFILE_ID_TOKEN = "__INFISICAL_PROFILE_ID_PLACEHOLDER__";+ const APP_ID_TOKEN = "__INFISICAL_APP_ID_PLACEHOLDER__";+ const COMMON_NAME_TOKEN = "__INFISICAL_COMMON_NAME_PLACEHOLDER__";const tokenized = certificateNameSchema.replace(new RE2("\\{\\{certificateId\\}\\}", "g"), CERT_ID_TOKEN)- .replace(new RE2("\\{\\{environment\\}\\}", "g"), ENV_TOKEN);+ .replace(new RE2("\\{\\{profileId\\}\\}", "g"), PROFILE_ID_TOKEN)+ .replace(new RE2("\\{\\{applicationId\\}\\}", "g"), APP_ID_TOKEN)+ .replace(new RE2("\\{\\{commonName\\}\\}", "g"), COMMON_NAME_TOKEN);+ // {{certificateId}}, {{profileId}}, and {{applicationId}} resolve to dash-stripped UUIDs (32 hex chars).+ // {{commonName}} is arbitrary, so match any run of NetScaler-safe characters.const pattern = escapeRegex(tokenized).replace(new RE2(CERT_ID_TOKEN, "g"), "[0-9a-f]{32}")- .replace(new RE2(ENV_TOKEN, "g"), "global");+ .replace(new RE2(PROFILE_ID_TOKEN, "g"), "[0-9a-f]{32}")+ .replace(new RE2(APP_ID_TOKEN, "g"), "[0-9a-f]{32}")+ .replace(new RE2(COMMON_NAME_TOKEN, "g"), "[a-zA-Z0-9._-]*");return new RE2(`^${pattern}$`);};@@ -432,10 +441,16 @@ export const netScalerPkiSyncFactory = ({} else if (certificate?.renewedFromCertificateId && !preserveItemOnRenewal) {const certIdClean = certificateId.replace(new RE2("-", "g"), "");if (certificateNameSchema) {- targetCertKeyName = handlebars.compile(certificateNameSchema)({- certificateId: certIdClean,- environment: "global"- });+ targetCertKeyName = compileCertificateNameSchema(+ certificateNameSchema,+ {+ certificateId,+ profileId: certData.profileId,+ applicationId: pkiSync.applicationId,+ commonName: certData.commonName+ },+ PkiSync.NetScaler+ );} else {targetCertKeyName = `Infisical-${certIdClean}`;}diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.test.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.test.tsnew file mode 100644index 0000000000..8b646878eb--- /dev/null+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.test.ts@@ -0,0 +1,37 @@+import { NetScalerPkiSyncOptionsSchema } from "./netscaler-pki-sync-schemas";++const parseSchema = (certificateNameSchema: string) =>+ NetScalerPkiSyncOptionsSchema.safeParse({ certificateNameSchema }).success;++describe("NetScaler certificateNameSchema validation", () => {+ test("accepts the supported placeholders that fit the 63-char limit", () => {+ expect(parseSchema("Infisical-{{certificateId}}")).toBe(true); // 42 chars+ expect(parseSchema("{{commonName}}-{{certificateId}}")).toBe(true); // ~44 chars+ });++ test("requires the {{certificateId}} placeholder", () => {+ expect(parseSchema("{{commonName}}")).toBe(false);+ expect(parseSchema("static-name")).toBe(false);+ });++ test("rejects the removed placeholders", () => {+ expect(parseSchema("{{certificateId}}-{{environment}}")).toBe(false);+ expect(parseSchema("{{friendlyName}}-{{certificateId}}")).toBe(false);+ });++ test("rejects schemas that would produce characters NetScaler forbids", () => {+ // '*' is a forbidden NetScaler certkey character.+ expect(parseSchema("*-{{certificateId}}")).toBe(false);+ });++ test("rejects schemas that compile beyond NetScaler's 63-char limit", () => {+ // two 32-char UUID placeholders + separator = 65 chars > 63+ expect(parseSchema("{{profileId}}-{{certificateId}}")).toBe(false);+ expect(parseSchema("{{applicationId}}-{{certificateId}}")).toBe(false);+ expect(parseSchema("{{applicationId}}-{{profileId}}-{{certificateId}}")).toBe(false);+ });++ test("allows an empty/undefined schema (optional)", () => {+ expect(NetScalerPkiSyncOptionsSchema.safeParse({}).success).toBe(true);+ });+});diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.tsindex b9c520d774..e72cd3f075 100644--- a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts@@ -1,8 +1,8 @@-import RE2 from "re2";import { z } from "zod";import { openApiHidden } from "@app/server/lib/schemas";import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";import { PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";@@ -27,9 +27,7 @@ export const NetScalerPkiSyncOptionsSchema = z.object({return false;}- const testName = schema- .replace(new RE2("\\{\\{certificateId\\}\\}", "g"), "test-cert-id")- .replace(new RE2("\\{\\{environment\\}\\}", "g"), "test-env");+ const testName = buildCertificateNameSchemaTestName(schema);const hasForbiddenChars = NETSCALER_NAMING.FORBIDDEN_CHARACTERS.split("").some((char) =>testName.includes(char)@@ -39,7 +37,7 @@ export const NetScalerPkiSyncOptionsSchema = z.object({},{message:- "Certificate name schema must include the {{certificateId}} placeholder and result in names that contain only alphanumeric characters, hyphens (-), underscores (_), and periods (.) and be 1-255 characters long for NetScaler"+ "Certificate name schema must include the {{certificateId}} placeholder and result in names that contain only alphanumeric characters, hyphens (-), underscores (_), and periods (.) and be 1-63 characters long for NetScaler. Available placeholders: {{certificateId}}, {{profileId}}, {{applicationId}}, {{commonName}}"})});diff --git a/backend/src/services/pki-sync/pki-sync-certificate-name-fns.test.ts b/backend/src/services/pki-sync/pki-sync-certificate-name-fns.test.tsnew file mode 100644index 0000000000..7940499f75--- /dev/null+++ b/backend/src/services/pki-sync/pki-sync-certificate-name-fns.test.ts@@ -0,0 +1,127 @@+import { buildCertificateNameSchemaTestName, compileCertificateNameSchema } from "./pki-sync-certificate-name-fns";+import { PkiSync } from "./pki-sync-enums";++const CERT_ID = "550e8400-e29b-41d4-a716-446655440000";+const CERT_ID_CLEAN = "550e8400e29b41d4a716446655440000";+const PROFILE_ID = "11111111-2222-3333-4444-555555555555";+const PROFILE_ID_CLEAN = "11111111222233334444555555555555";+const APP_ID = "abcdef00-1111-2222-3333-444444444444";+const APP_ID_CLEAN = "abcdef00111122223333444444444444";++describe("compileCertificateNameSchema", () => {+ test("strips dashes from the certificate ID", () => {+ expect(compileCertificateNameSchema("Infisical-{{certificateId}}", { certificateId: CERT_ID })).toBe(+ `Infisical-${CERT_ID_CLEAN}`+ );+ });++ test("substitutes the common name (FQDN) verbatim when no destination is given", () => {+ expect(+ compileCertificateNameSchema("{{commonName}}-{{certificateId}}", {+ certificateId: CERT_ID,+ commonName: "app.example.com"+ })+ ).toBe(`app.example.com-${CERT_ID_CLEAN}`);+ });++ describe("per-destination common-name sanitization", () => {+ test("Azure Key Vault: dots (forbidden) become hyphens", () => {+ expect(+ compileCertificateNameSchema(+ "cert-{{commonName}}",+ { certificateId: CERT_ID, commonName: "app.example.com" },+ PkiSync.AzureKeyVault+ )+ ).toBe("cert-app-example-com");+ });++ test("Chef: dots become hyphens", () => {+ expect(+ compileCertificateNameSchema(+ "{{commonName}}",+ { certificateId: CERT_ID, commonName: "app.example.com" },+ PkiSync.Chef+ )+ ).toBe("app-example-com");+ });++ test("NetScaler: dots are allowed, so the FQDN is preserved", () => {+ expect(+ compileCertificateNameSchema(+ "{{commonName}}-{{certificateId}}",+ { certificateId: CERT_ID, commonName: "app.example.com" },+ PkiSync.NetScaler+ )+ ).toBe(`app.example.com-${CERT_ID_CLEAN}`);+ });++ test("wildcard CN: '*' is sanitized for every destination", () => {+ expect(+ compileCertificateNameSchema(+ "{{commonName}}",+ { certificateId: CERT_ID, commonName: "*.example.com" },+ PkiSync.NetScaler+ )+ ).toBe("-.example.com");+ });+ });++ test("substitutes the profile ID (dashes stripped)", () => {+ expect(compileCertificateNameSchema("{{profileId}}", { certificateId: CERT_ID, profileId: PROFILE_ID })).toBe(+ PROFILE_ID_CLEAN+ );+ });++ test("falls back to the certificate ID when the certificate has no profile", () => {+ expect(compileCertificateNameSchema("{{profileId}}", { certificateId: CERT_ID, profileId: null })).toBe(+ CERT_ID_CLEAN+ );+ });++ test("substitutes the application ID (dashes stripped)", () => {+ expect(+ compileCertificateNameSchema("{{applicationId}}-cert", { certificateId: CERT_ID, applicationId: APP_ID })+ ).toBe(`${APP_ID_CLEAN}-cert`);+ });++ test("resolves application ID to empty when the sync has no application", () => {+ expect(compileCertificateNameSchema("app-{{applicationId}}-{{certificateId}}", { certificateId: CERT_ID })).toBe(+ `app--${CERT_ID_CLEAN}`+ );+ });++ test("resolves common name to empty when absent", () => {+ expect(compileCertificateNameSchema("{{commonName}}x{{certificateId}}", { certificateId: CERT_ID })).toBe(+ `x${CERT_ID_CLEAN}`+ );+ });++ test("removed placeholders ({{environment}}, {{friendlyName}}) resolve to empty, not literal braces", () => {+ const result = compileCertificateNameSchema("a{{environment}}{{friendlyName}}b-{{certificateId}}", {+ certificateId: CERT_ID+ });+ expect(result).toBe(`ab-${CERT_ID_CLEAN}`);+ expect(result).not.toContain("{{");+ });+});++describe("buildCertificateNameSchemaTestName", () => {+ const UUID = "0".repeat(32);++ test("substitutes UUID placeholders with full 32-char stand-ins (realistic length)", () => {+ expect(buildCertificateNameSchemaTestName("{{certificateId}}-{{profileId}}-{{applicationId}}-{{commonName}}")).toBe(+ `${UUID}-${UUID}-${UUID}-common-name`+ );+ });++ test("two UUID placeholders alone already exceed NetScaler's 63-char limit", () => {+ expect(buildCertificateNameSchemaTestName("{{profileId}}-{{certificateId}}").length).toBeGreaterThan(63);+ });++ test("leaves removed placeholders untouched so destination validation rejects them", () => {+ const testName = buildCertificateNameSchemaTestName("{{environment}}-{{friendlyName}}-{{certificateId}}");+ // The leftover braces are forbidden characters for every destination, so validation fails.+ expect(testName).toContain("{{environment}}");+ expect(testName).toContain("{{friendlyName}}");+ });+});diff --git a/backend/src/services/pki-sync/pki-sync-certificate-name-fns.ts b/backend/src/services/pki-sync/pki-sync-certificate-name-fns.tsnew file mode 100644index 0000000000..dcce654aec--- /dev/null+++ b/backend/src/services/pki-sync/pki-sync-certificate-name-fns.ts@@ -0,0 +1,83 @@+import handlebars from "handlebars";+import RE2 from "re2";++import { PkiSync } from "./pki-sync-enums";++const DASH_REGEX = new RE2("-", "g");++// A dash-stripped UUID is exactly 32 hex chars. The validation test name uses this so a+// schema's real compiled length (e.g. two UUID placeholders = 64+ chars) is checked against+// each destination's limit at configuration time instead of failing silently at sync time.+const UUID_TEST_VALUE = "00000000000000000000000000000000";++// Per-destination set of characters allowed in a resource name. Free-text placeholder values+// (currently {{commonName}}) are sanitized to this set at compile time so a FQDN like+// "app.example.com" can't produce a name the destination rejects (e.g. Azure Key Vault and+// Chef forbid dots). UUID-based placeholders are always safe (hex), so only free-text is sanitized.+const NAME_VALUE_DISALLOWED_CHARS: Partial<Record<PkiSync, RE2>> = {+ [PkiSync.AzureKeyVault]: new RE2("[^a-zA-Z0-9-]", "g"),+ [PkiSync.CloudflareCustomCertificate]: new RE2("[^a-zA-Z0-9_-]", "g"),+ [PkiSync.Chef]: new RE2("[^a-zA-Z0-9_-]", "g"),+ [PkiSync.AwsCertificateManager]: new RE2("[^a-zA-Z0-9 _-]", "g"),+ [PkiSync.AwsElasticLoadBalancer]: new RE2("[^a-zA-Z0-9 _-]", "g"),+ [PkiSync.AwsSecretsManager]: new RE2("[^a-zA-Z0-9_-]", "g"),+ [PkiSync.NetScaler]: new RE2("[^a-zA-Z0-9._-]", "g"),+ [PkiSync.F5BigIp]: new RE2("[^a-zA-Z0-9._-]", "g")+};++const sanitizeNameValue = (value: string, destination?: PkiSync): string => {+ if (!value || !destination) return value;+ const disallowed = NAME_VALUE_DISALLOWED_CHARS[destination];+ return disallowed ? value.replace(disallowed, "-") : value;+};++export type TCertificateNameSchemaData = {+ certificateId: string;+ profileId?: string | null;+ applicationId?: string | null;+ commonName?: string | null;+};++/**+ * Compiles a certificate name schema (Handlebars template) into a concrete name.+ *+ * Supported placeholders:+ * - {{certificateId}} - the certificate's unique ID (dashes stripped)+ * - {{profileId}} - the certificate profile ID (dashes stripped); falls back to {{certificateId}} when the certificate has no profile+ * - {{applicationId}} - the sync's application ID (dashes stripped); empty when the sync has no application+ * - {{commonName}} - the certificate common name (FQDN), sanitized to the destination's allowed character set+ *+ * Callers pass raw values (UUIDs with dashes); cleaning and per-destination sanitization are+ * centralized here so every call site produces identical names.+ */+export const compileCertificateNameSchema = (+ schema: string,+ data: TCertificateNameSchemaData,+ destination?: PkiSync+): string => {+ const certificateId = data.certificateId.replace(DASH_REGEX, "");+ const profileId = data.profileId ? data.profileId.replace(DASH_REGEX, "") : certificateId;+ const applicationId = data.applicationId ? data.applicationId.replace(DASH_REGEX, "") : "";++ return handlebars.compile(schema)({+ certificateId,+ profileId,+ applicationId,+ commonName: sanitizeNameValue(data.commonName || "", destination)+ });+};++/**+ * Substitutes every supported placeholder with a representative test value so that a+ * destination's character/length constraints can be validated at configuration time.+ *+ * UUID-based placeholders use a full 32-char value so the compiled length is realistic+ * (this is what catches over-length schemas, e.g. on NetScaler's 63-char limit).+ * Adding a new placeholder here makes it available to every destination's validation.+ */+export const buildCertificateNameSchemaTestName = (schema: string): string =>+ schema+ .replace(new RE2("\\{\\{certificateId\\}\\}", "g"), UUID_TEST_VALUE)+ .replace(new RE2("\\{\\{profileId\\}\\}", "g"), UUID_TEST_VALUE)+ .replace(new RE2("\\{\\{applicationId\\}\\}", "g"), UUID_TEST_VALUE)+ .replace(new RE2("\\{\\{commonName\\}\\}", "g"), "common-name");diff --git a/backend/src/services/pki-sync/pki-sync-fns.test.ts b/backend/src/services/pki-sync/pki-sync-fns.test.tsnew file mode 100644index 0000000000..f74e64640d--- /dev/null+++ b/backend/src/services/pki-sync/pki-sync-fns.test.ts@@ -0,0 +1,79 @@+import { matchesCertificateNameSchema } from "./pki-sync-fns";++// A dash-stripped UUID (what {{certificateId}}, {{profileId}}, {{applicationId}} resolve to).+const HEX = "550e8400e29b41d4a716446655440000";+const OTHER_HEX = "abcdef001111222233334444aaaaaaaa";++describe("matchesCertificateNameSchema (managed-certificate detection for cleanup)", () => {+ test("with no schema, treats every name as a candidate", () => {+ expect(matchesCertificateNameSchema("literally-anything", undefined)).toBe(true);+ });++ describe('schema "Infisical-{{certificateId}}"', () => {+ const schema = "Infisical-{{certificateId}}";++ test("matches a name Infisical produced", () => {+ expect(matchesCertificateNameSchema(`Infisical-${HEX}`, schema)).toBe(true);+ });++ test("matches any cert ID, not just one specific cert (so renewed/other certs are cleaned up)", () => {+ expect(matchesCertificateNameSchema(`Infisical-${OTHER_HEX}`, schema)).toBe(true);+ });++ test("rejects a name with a non-hex ID segment", () => {+ expect(matchesCertificateNameSchema("Infisical-not-a-real-id", schema)).toBe(false);+ });++ test("rejects an ID that is not exactly 32 hex chars", () => {+ expect(matchesCertificateNameSchema(`Infisical-${HEX.slice(0, 31)}`, schema)).toBe(false);+ });++ test("rejects extra prefix or suffix (anchored match)", () => {+ expect(matchesCertificateNameSchema(`prod-Infisical-${HEX}`, schema)).toBe(false);+ expect(matchesCertificateNameSchema(`Infisical-${HEX}-extra`, schema)).toBe(false);+ });++ // Deletion safety: a certificate that did NOT come from this schema must never be considered managed.+ test("does NOT match unrelated certificates", () => {+ expect(matchesCertificateNameSchema("my-own-prod-cert", schema)).toBe(false);+ expect(matchesCertificateNameSchema("acme-com-2024", schema)).toBe(false);+ expect(matchesCertificateNameSchema("", schema)).toBe(false);+ });+ });++ test("matches profile-ID based names", () => {+ expect(matchesCertificateNameSchema(`p-${HEX}`, "p-{{profileId}}")).toBe(true);+ expect(matchesCertificateNameSchema("p-notaprofile", "p-{{profileId}}")).toBe(false);+ });++ test("matches application-ID based names", () => {+ expect(matchesCertificateNameSchema(`${HEX}-cert`, "{{applicationId}}-cert")).toBe(true);+ expect(matchesCertificateNameSchema("xyz-cert", "{{applicationId}}-cert")).toBe(false);+ });++ describe('schema "{{commonName}}-{{certificateId}}"', () => {+ const schema = "{{commonName}}-{{certificateId}}";++ test("matches arbitrary common names anchored by the cert ID", () => {+ expect(matchesCertificateNameSchema(`app.example.com-${HEX}`, schema)).toBe(true);+ expect(matchesCertificateNameSchema(`anything.here-${HEX}`, schema)).toBe(true);+ });++ // The wildcard is for the common-name slot only; the cert-ID anchor still has to match.+ test("still requires a valid cert ID, so it does not match every name", () => {+ expect(matchesCertificateNameSchema("app.example.com-nothex", schema)).toBe(false);+ });+ });++ test("treats regex-special literal characters in the schema as literals", () => {+ const schema = "cert.{{certificateId}}.pem";+ expect(matchesCertificateNameSchema(`cert.${HEX}.pem`, schema)).toBe(true);+ // The '.' must be literal, not a regex any-char.+ expect(matchesCertificateNameSchema(`certX${HEX}Ypem`, schema)).toBe(false);+ });++ test("no longer expands {{environment}} (removed placeholder)", () => {+ // {{environment}} is treated as a literal now, so a name where it was substituted with 'global' won't match.+ expect(matchesCertificateNameSchema(`global-${HEX}`, "{{environment}}-{{certificateId}}")).toBe(false);+ });+});diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.tsindex 2895865108..274a6abe2e 100644--- a/backend/src/services/pki-sync/pki-sync-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-fns.ts@@ -1,4 +1,4 @@-import handlebars from "handlebars";+import RE2 from "re2";import { z, ZodSchema } from "zod";import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";@@ -89,84 +89,30 @@ export const parsePkiSyncErrorMessage = (error: unknown): string => {return "An unknown error occurred during PKI sync operation";};-export const applyCertificateNameSchema = (- certificateMap: TCertificateMap,- environment: string,- schema?: string-): TCertificateMap => {- if (!schema) return certificateMap;+const escapeNameSchemaRegex = (value: string): string =>+ value.replace(new RE2("[\\\\^$.*+?()\\[\\]{}|/]", "g"), "\\$&");- const processedCertificateMap: TCertificateMap = {};-- for (const [certificateId, value] of Object.entries(certificateMap)) {- const newName = handlebars.compile(schema)({- certificateId,- environment- });-- processedCertificateMap[newName] = value;- }-- return processedCertificateMap;-};--export const stripCertificateNameSchema = (- certificateMap: TCertificateMap,- environment: string,- schema?: string-): TCertificateMap => {- if (!schema) return certificateMap;-- const compiledSchemaPattern = handlebars.compile(schema)({- certificateId: "{{certificateId}}",- environment- });-- const parts = compiledSchemaPattern.split("{{certificateId}}");- const prefix = parts[0];- const suffix = parts[parts.length - 1];-- const strippedMap: TCertificateMap = {};-- for (const [name, value] of Object.entries(certificateMap)) {- if (!name.startsWith(prefix) || !name.endsWith(suffix)) {- // eslint-disable-next-line no-continue- continue;- }-- const strippedName = name.slice(prefix.length, name.length - suffix.length);- strippedMap[strippedName] = value;- }-- return strippedMap;-};--export const matchesCertificateNameSchema = (name: string, environment: string, schema?: string): boolean => {+export const matchesCertificateNameSchema = (name: string, schema?: string): boolean => {if (!schema) return true;- const compiledSchemaPattern = handlebars.compile(schema)({- certificateId: "{{certificateId}}",- environment- });-- if (!compiledSchemaPattern.includes("{{certificateId}}")) {- return name === compiledSchemaPattern;- }-- const parts = compiledSchemaPattern.split("{{certificateId}}");- const prefix = parts[0];- const suffix = parts[parts.length - 1];-- if (prefix === "" && suffix === "") return true;+ const CERT_ID_TOKEN = "__INFISICAL_CERT_ID_PLACEHOLDER__";+ const PROFILE_ID_TOKEN = "__INFISICAL_PROFILE_ID_PLACEHOLDER__";+ const APP_ID_TOKEN = "__INFISICAL_APP_ID_PLACEHOLDER__";+ const COMMON_NAME_TOKEN = "__INFISICAL_COMMON_NAME_PLACEHOLDER__";- // If prefix is empty, name must end with suffix- if (prefix === "") return name.endsWith(suffix);+ const tokenized = schema+ .replace(new RE2("\\{\\{certificateId\\}\\}", "g"), CERT_ID_TOKEN)+ .replace(new RE2("\\{\\{profileId\\}\\}", "g"), PROFILE_ID_TOKEN)+ .replace(new RE2("\\{\\{applicationId\\}\\}", "g"), APP_ID_TOKEN)+ .replace(new RE2("\\{\\{commonName\\}\\}", "g"), COMMON_NAME_TOKEN);- // If suffix is empty, name must start with prefix- if (suffix === "") return name.startsWith(prefix);+ const pattern = escapeNameSchemaRegex(tokenized)+ .replace(new RE2(CERT_ID_TOKEN, "g"), "[0-9a-f]{32}")+ .replace(new RE2(PROFILE_ID_TOKEN, "g"), "[0-9a-f]{32}")+ .replace(new RE2(APP_ID_TOKEN, "g"), "[0-9a-f]{32}")+ .replace(new RE2(COMMON_NAME_TOKEN, "g"), ".*");- // Name must start with prefix and end with suffix- return name.startsWith(prefix) && name.endsWith(suffix);+ return new RE2(`^${pattern}$`).test(name);};const checkPkiSyncDestination = (pkiSync: TPkiSyncWithCredentials, destination: PkiSync): void => {diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.tsindex 6314cdc25d..de413930ee 100644--- a/backend/src/services/pki-sync/pki-sync-queue.ts+++ b/backend/src/services/pki-sync/pki-sync-queue.ts@@ -4,7 +4,6 @@ import * as x509 from "@peculiar/x509";import { AxiosError } from "axios";import { Job } from "bullmq";import { randomUUID } from "crypto";-import handlebars from "handlebars";import { TCertificates } from "@app/db/schemas";import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";@@ -34,8 +33,9 @@ import { getCaCertChain } from "../certificate-authority/certificate-authority-fimport { extractRootCaFromChain, removeRootCaFromChain } from "../certificate-common/certificate-utils";import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";import { CertificateSyncStatus } from "../certificate-sync/certificate-sync-enums";+import { compileCertificateNameSchema } from "./pki-sync-certificate-name-fns";import { TPkiSyncDALFactory } from "./pki-sync-dal";-import { PkiSyncStatus } from "./pki-sync-enums";+import { PkiSync, PkiSyncStatus } from "./pki-sync-enums";import { PkiSyncError } from "./pki-sync-errors";import { enterprisePkiSyncCheck, parsePkiSyncErrorMessage, PkiSyncFns } from "./pki-sync-fns";import {@@ -289,15 +289,16 @@ export const pkiSyncQueueFactory = ({const certificateNameSchema = syncOptions?.certificateNameSchema;if (certificateNameSchema) {- const environment = "global";- const templateData = {- certificateId: certificate.id.replace(/-/g, ""),- profileId: cert.profileId?.replace(/-/g, "") || certificate.id.replace(/-/g, ""),- commonName: cert.commonName || "",- friendlyName: cert.friendlyName || "",- environment- };- certificateName = handlebars.compile(certificateNameSchema)(templateData);+ certificateName = compileCertificateNameSchema(+ certificateNameSchema,+ {+ certificateId: certificate.id,+ profileId: cert.profileId,+ applicationId: pkiSync.applicationId,+ commonName: cert.commonName+ },+ pkiSync.destination as PkiSync+ );} else {const stableId = cert.profileId? `${cert.profileId.replace(/-/g, "")}-${(cert.commonName || "").replace(/[^a-zA-Z0-9]/g, "")}`@@ -328,7 +329,9 @@ export const pkiSyncQueueFactory = ({certificateChain: processedCertificateChain,caCertificate,alternativeNames,- certificateId: certificate.id+ certificateId: certificate.id,+ profileId: cert.profileId,+ commonName: cert.commonName};certificateMetadata.set(certificateName, {diff --git a/backend/src/services/pki-sync/pki-sync-schemas.ts b/backend/src/services/pki-sync/pki-sync-schemas.tsindex 2b88f9cc28..1a6c6bc835 100644--- a/backend/src/services/pki-sync/pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/pki-sync-schemas.ts@@ -15,7 +15,12 @@ export const PkiSyncOptionsSchema = z.object({(val) => {if (!val) return true;- const allowedPlaceholdersRegexPart = ["{{certificateId}}"]+ const allowedPlaceholdersRegexPart = [+ "{{certificateId}}",+ "{{profileId}}",+ "{{applicationId}}",+ "{{commonName}}"+ ].map((p) => p.replace(new RE2(/[-/\\^$*+?.()|[\]{}]/g), "\\$&")) // Escape regex special characters.join("|");@@ -32,7 +37,7 @@ export const PkiSyncOptionsSchema = z.object({},{message:- "Certificate name schema must include exactly one {{certificateId}} placeholder. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and slashes (/) are allowed besides the placeholders."+ "Certificate name schema must include the {{certificateId}} placeholder. It can also include {{profileId}}, {{applicationId}}, and {{commonName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and slashes (/) are allowed besides the placeholders."})});diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.tsindex 9810800bd9..83e4dfe442 100644--- a/backend/src/services/pki-sync/pki-sync-types.ts+++ b/backend/src/services/pki-sync/pki-sync-types.ts@@ -85,6 +85,8 @@ export type TCertificateMap = Record<caCertificate?: string;alternativeNames?: string[];certificateId?: string;+ profileId?: string | null;+ commonName?: string | null;}>;diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/aws-certificate-manager.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/aws-certificate-manager.mdxindex 16361e5af1..943017b65d 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/aws-certificate-manager.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/aws-certificate-manager.mdx@@ -39,7 +39,7 @@ Push certificates from your Application to AWS Certificate Manager (ACM). Certif- **Enable Removal of Expired/Revoked Certificates**: Remove certificates from the destination if they are no longer active in Infisical.- **Preserve ARN on Renewal**: Sync renewed certificates under the same ARN instead of creating a new one.- **Include Root CA**: Include the Root CA certificate in the certificate chain.- - **Certificate Name Schema**: Customize certificate tags. Must include `{{certificateId}}`. Defaults to `Infisical-{{certificateId}}`.+ - **Certificate Name Schema**: Customize certificate tags using placeholders such as `{{certificateId}}`, `{{commonName}}`, `{{profileId}}`, and `{{applicationId}}`. Must include `{{certificateId}}`. Defaults to `Infisical-{{certificateId}}`. See [Certificate Name Schema](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-name-schema) for the full placeholder reference.- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.5. Configure the **Details**:diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/aws-elastic-load-balancer.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/aws-elastic-load-balancer.mdxindex c876b11d27..ab9bd91498 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/aws-elastic-load-balancer.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/aws-elastic-load-balancer.mdx@@ -34,7 +34,7 @@ Deploy certificates directly to your AWS Application Load Balancers (ALBs) and N- **Enable Removal of Expired/Revoked Certificates**: Remove certificates from listeners and ACM when no longer active.- **Preserve ARN on Renewal**: Keep the same ARN when renewing instead of creating a new certificate.- **Include Root CA**: Include the Root CA certificate in the chain.- - **Certificate Name Schema**: Customize ACM tags using `{{certificateId}}` placeholder.+ - **Certificate Name Schema**: Customize ACM tags using placeholders such as `{{certificateId}}`, `{{commonName}}`, `{{profileId}}`, and `{{applicationId}}`. Must include `{{certificateId}}`. See [Certificate Name Schema](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-name-schema) for the full placeholder reference.- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.5. Configure the **Details**:diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/aws-secrets-manager.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/aws-secrets-manager.mdxindex a750968cc3..6d86908fdc 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/aws-secrets-manager.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/aws-secrets-manager.mdx@@ -39,7 +39,7 @@ Store certificates in AWS Secrets Manager as JSON secrets for application retrie- **Enable Removal of Expired/Revoked Certificates**: Remove certificates from the destination if they are no longer active.- **Preserve Secret on Renewal**: Update the existing secret on renewal instead of creating a new one.- **Include Root CA**: Include the Root CA certificate in the chain.- - **Certificate Name Schema**: Customize secret names using `{{certificateId}}` placeholder.+ - **Certificate Name Schema**: Customize secret names using placeholders such as `{{certificateId}}`, `{{commonName}}`, `{{profileId}}`, and `{{applicationId}}`. Must include `{{certificateId}}`. See [Certificate Name Schema](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-name-schema) for the full placeholder reference.- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.5. Configure the **Field Mappings** to customize how certificate data is stored:diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/azure-key-vault.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/azure-key-vault.mdxindex 1979887c0d..241c099787 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/azure-key-vault.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/azure-key-vault.mdx@@ -38,7 +38,7 @@ Store certificates in Azure Key Vault as certificate objects. Certificates synce- **Enable Removal of Expired/Revoked Certificates**: Remove certificates from the destination if they are no longer active.- **Enable Versioning on Renewal**: Create a new version of the certificate on renewal instead of a new certificate.- **Include Root CA**: Include the Root CA certificate in the chain.- - **Certificate Name Schema**: Customize certificate names using `{{certificateId}}` placeholder.+ - **Certificate Name Schema**: Customize certificate names using placeholders such as `{{certificateId}}`, `{{commonName}}`, `{{profileId}}`, and `{{applicationId}}`. Must include `{{certificateId}}`. See [Certificate Name Schema](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-name-schema) for the full placeholder reference.- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.<Tip>diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/chef.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/chef.mdxindex be4e1c6640..f1d362b152 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/chef.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/chef.mdx@@ -38,7 +38,7 @@ Store certificates in Chef data bags for distribution to nodes via Chef Infra. C- **Enable Removal of Expired/Revoked Certificates**: Remove certificates from the destination if they are no longer active.- **Preserve Data Bag Item on Renewal**: Update the existing data bag item on renewal instead of creating a new one.- **Include Root CA**: Include the Root CA certificate in the chain.- - **Certificate Name Schema**: Customize item names using `{{certificateId}}` placeholder.+ - **Certificate Name Schema**: Customize item names using placeholders such as `{{certificateId}}`, `{{commonName}}`, `{{profileId}}`, and `{{applicationId}}`. Must include `{{certificateId}}`. See [Certificate Name Schema](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-name-schema) for the full placeholder reference.- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.5. Configure the **Field Mappings**:diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/cloudflare-custom-certificate.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/cloudflare-custom-certificate.mdxindex f253cfa880..0c7f0851ca 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/cloudflare-custom-certificate.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/cloudflare-custom-certificate.mdx@@ -32,7 +32,7 @@ Deploy custom SSL certificates to your Cloudflare zones. Certificates synced to4. Configure the **Sync Options**:- **Enable Removal of Expired/Revoked Certificates**: Remove certificates from the destination if they are no longer active.- - **Certificate Name Schema**: Customize certificate names using `{{certificateId}}` placeholder.+ - **Certificate Name Schema**: Customize certificate names using placeholders such as `{{certificateId}}`, `{{commonName}}`, `{{profileId}}`, and `{{applicationId}}`. Must include `{{certificateId}}`. See [Certificate Name Schema](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-name-schema) for the full placeholder reference.- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.5. Configure the **Details**:diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/f5-big-ip.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/f5-big-ip.mdxindex 5535540dc7..56eb1607ab 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/f5-big-ip.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/f5-big-ip.mdx@@ -36,7 +36,7 @@ Deploy certificates to F5 BIG-IP appliances. Certificates can be automatically a- **Enable Removal of Expired/Revoked Certificates**: Remove certificates from the BIG-IP when they're no longer active in Infisical.- **Include Root CA in Certificate Chain**: Include the root CA in the chain uploaded to the BIG-IP. Most setups don't need the root, since clients already trust it.- **Preserve Certificate on Renewal**: When on, renewed certificates keep the same name on the BIG-IP, so any profile or virtual server using them keeps working without changes. When off, the renewed certificate is uploaded with a new name and the original stays on the BIG-IP.- - **Certificate Name Schema** (Optional): Customize the name used on the BIG-IP. Must include `{{certificateId}}`. Defaults to `Infisical-{{certificateId}}`. The certificate chain follows the same name with `-chain` added.+ - **Certificate Name Schema** (Optional): Customize the name used on the BIG-IP using placeholders such as `{{certificateId}}`, `{{commonName}}`, `{{profileId}}`, and `{{applicationId}}`. Must include `{{certificateId}}`. Defaults to `Infisical-{{certificateId}}`. The certificate chain follows the same name with `-chain` added. See [Certificate Name Schema](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-name-schema) for the full placeholder reference.- **Auto-Sync Enabled**: Automatically sync certificates when changes occur (including auto-renewals).5. Configure the **Details**:diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/netscaler.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/netscaler.mdxindex 8601233520..20b5babc34 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/netscaler.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/netscaler.mdx@@ -31,7 +31,7 @@ Deploy certificates to Citrix NetScaler ADC appliances via the NITRO API. Certif4. Configure the **Sync Options**:- **Enable Removal of Expired/Revoked Certificates**: Remove certificates from the destination if they are no longer active.- **Preserve Certificate on Renewal**: Update the existing certkey object in place, preserving name and vServer bindings.- - **Certificate Name Schema**: Customize certificate names using `{{certificateId}}` placeholder.+ - **Certificate Name Schema**: Customize `sslcertkey` names using placeholders such as `{{certificateId}}`, `{{commonName}}`, `{{profileId}}`, and `{{applicationId}}`. Must include `{{certificateId}}`. Defaults to `Infisical-{{certificateId}}`. See [Certificate Name Schema](/documentation/platform/pki/applications/certificate-syncs/overview#certificate-name-schema) for the full placeholder reference.- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.5. Configure the **Details**:@@ -70,7 +70,7 @@ Deploy certificates to Citrix NetScaler ADC appliances via the NITRO API. Certif"syncOptions": {"canRemoveCertificates": true,"preserveItemOnRenewal": true,- "certificateNameSchema": "myapp-{{certificateId}}"+ "certificateNameSchema": "{{commonName}}-{{certificateId}}"},"destinationConfig": {"vserverName": "vs-ssl-prod"@@ -94,7 +94,7 @@ Deploy certificates to Citrix NetScaler ADC appliances via the NITRO API. Certif"syncOptions": {"canRemoveCertificates": true,"preserveItemOnRenewal": true,- "certificateNameSchema": "myapp-{{certificateId}}"+ "certificateNameSchema": "{{commonName}}-{{certificateId}}"},"applicationId": "3c90c3cc-0d44-4b50-8888-8dd25736052a","connectionId": "550e8400-e29b-41d4-a716-446655440000",@@ -106,6 +106,10 @@ Deploy certificates to Citrix NetScaler ADC appliances via the NITRO API. Certif</Tab></Tabs>+<Note>+ NetScaler caps `sslcertkey` names at **63 characters**. Since `{{certificateId}}` is required and each UUID placeholder (`{{certificateId}}`, `{{profileId}}`, `{{applicationId}}`) resolves to 32 characters, combining two of them exceeds the limit and the schema is rejected when you save the sync. For NetScaler, pair `{{certificateId}}` with a short prefix or `{{commonName}}` (kept under the limit).+</Note>+## Certificate ManagementThe NetScaler Certificate Sync provides:diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdxindex 30b7c554f2..f9c5105ca3 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/overview.mdx@@ -111,12 +111,32 @@ flowchart LR|--------|-------------|| **Remove on expiry** | Automatically remove expired certificates from the destination || **Include Root CA** | Include the root CA certificate in the chain |-| **Certificate naming** | Customize how certificates are named in the destination (default: `Infisical-{certificateId}`) |+| **Certificate naming** | Customize how certificates are named in the destination via the Certificate Name Schema (default: `Infisical-{{certificateId}}`) |<Note>Some destinations don't support automatic removal of expired certificates. Certificates managed by Infisical may be overwritten if modified directly in the destination.</Note>+## Certificate Name Schema++The **Certificate Name Schema** controls the name each certificate is given in the destination. It is a template that supports the following placeholders, which are resolved per certificate at sync time:++<Note>+ - `{{certificateId}}` - The unique ID of the certificate. **Required** so that each synced certificate resolves to a unique, stable name.+ - `{{commonName}}` - The certificate's common name (its FQDN), e.g. `app.example.com`.+ - `{{profileId}}` - The certificate profile ID. Falls back to the certificate ID when the certificate has no profile.+ - `{{applicationId}}` - The ID of the application the sync belongs to.+</Note>++For example, `myapp-{{commonName}}-{{certificateId}}` produces a name like `myapp-app.example.com-1a2b3c...`.++Each destination enforces its own character and length rules for resource names:++- **Characters**: `{{commonName}}` is sanitized to the destination's allowed character set. For destinations that don't allow dots (e.g. Azure Key Vault, Chef), `app.example.com` becomes `app-example-com`; destinations that allow dots (e.g. NetScaler, F5 BIG-IP) keep it as-is.+- **Length**: schemas that would compile to a name longer than the destination's limit are rejected when you save the sync. UUID placeholders (`{{certificateId}}`, `{{profileId}}`, `{{applicationId}}`) each count as 32 characters.++Keep `{{certificateId}}` in the schema to guarantee a unique, stable name per certificate.+## What's Next?<CardGroup cols={2}>diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsxindex cb30849330..f167aff235 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx@@ -434,7 +434,23 @@ export const PkiSyncOptionsFields = ({ destination }: Props) => {<li><code>{"{{certificateId}}"}</code> - The unique ID of the certificate</li>+ <li>+ <code>{"{{commonName}}"}</code> - The certificate's common name (FQDN)+ </li>+ <li>+ <code>{"{{profileId}}"}</code> - The certificate profile ID (falls back to the+ certificate ID when none is set)+ </li>+ <li>+ <code>{"{{applicationId}}"}</code> - The ID of the application the sync+ belongs to+ </li></ul>+ <span className="mt-1 text-xs text-bunker-300">+ The schema must include <code>{"{{certificateId}}"}</code> to guarantee a unique+ name per certificate. Values that resolve to characters not allowed by the+ destination will be rejected at sync time.+ </span></div>{syncOption?.forbiddenCharacters && syncOption.forbiddenCharacters.length > 0 && (<div className="flex flex-col">diff --git a/frontend/src/components/pki-syncs/forms/schemas/aws-certificate-manager-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/aws-certificate-manager-pki-sync-destination-schema.tsindex 72e89a4508..13fcc2bd17 100644--- a/frontend/src/components/pki-syncs/forms/schemas/aws-certificate-manager-pki-sync-destination-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/aws-certificate-manager-pki-sync-destination-schema.ts@@ -21,7 +21,11 @@ const AwsCertificateManagerSyncOptionsSchema = z.object({return false;}- const allowedOptionalPlaceholders = ["{{environment}}"];+ const allowedOptionalPlaceholders = [+ "{{profileId}}",+ "{{applicationId}}",+ "{{commonName}}"+ ];const allowedPlaceholdersRegexPart = ["{{certificateId}}", ...allowedOptionalPlaceholders].map((p) => p.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&")).join("|");@@ -34,7 +38,7 @@ const AwsCertificateManagerSyncOptionsSchema = z.object({},{message:- "Certificate name schema must include {{certificateId}} placeholder for AWS Certificate Manager."+ "Certificate name schema must include the {{certificateId}} placeholder for AWS Certificate Manager. It can also include {{profileId}}, {{applicationId}}, and {{commonName}} placeholders."})});diff --git a/frontend/src/components/pki-syncs/forms/schemas/aws-secrets-manager-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/aws-secrets-manager-pki-sync-destination-schema.tsindex 023fea6dab..81b31a29c8 100644--- a/frontend/src/components/pki-syncs/forms/schemas/aws-secrets-manager-pki-sync-destination-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/aws-secrets-manager-pki-sync-destination-schema.ts@@ -31,10 +31,9 @@ const AwsSecretsManagerSyncOptionsSchema = z.object({if (!val) return true;const allowedOptionalPlaceholders = [- "{{environment}}","{{profileId}}",- "{{commonName}}",- "{{friendlyName}}"+ "{{applicationId}}",+ "{{commonName}}"];const allowedPlaceholdersRegexPart = ["{{certificateId}}", ...allowedOptionalPlaceholders]@@ -56,7 +55,7 @@ const AwsSecretsManagerSyncOptionsSchema = z.object({},{message:- "Certificate name schema must include exactly one {{certificateId}} placeholder. It can also include {{environment}}, {{profileId}}, {{commonName}}, or {{friendlyName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed besides the placeholders."+ "Certificate name schema must include exactly one {{certificateId}} placeholder. It can also include {{profileId}}, {{applicationId}}, and {{commonName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed besides the placeholders."}),fieldMappings: AwsSecretsManagerFieldMappingsSchema.optional().default({diff --git a/frontend/src/components/pki-syncs/forms/schemas/azure-key-vault-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/azure-key-vault-pki-sync-destination-schema.tsindex 653c0fa0ed..ba2301fcce 100644--- a/frontend/src/components/pki-syncs/forms/schemas/azure-key-vault-pki-sync-destination-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/azure-key-vault-pki-sync-destination-schema.ts@@ -16,7 +16,11 @@ const AzureKeyVaultSyncOptionsSchema = z.object({(val) => {if (!val) return true;- const allowedOptionalPlaceholders = ["{{environment}}"];+ const allowedOptionalPlaceholders = [+ "{{profileId}}",+ "{{applicationId}}",+ "{{commonName}}"+ ];const allowedPlaceholdersRegexPart = ["{{certificateId}}", ...allowedOptionalPlaceholders].map((p) => p.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"))@@ -37,7 +41,7 @@ const AzureKeyVaultSyncOptionsSchema = z.object({},{message:- "Certificate name schema must include exactly one {{certificateId}} placeholder. It can also include {{environment}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and slashes (/) are allowed besides the placeholders."+ "Certificate name schema must include the {{certificateId}} placeholder. It can also include {{profileId}}, {{applicationId}}, and {{commonName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and slashes (/) are allowed besides the placeholders."})});diff --git a/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.tsindex 97f196e3d3..96317215f8 100644--- a/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts@@ -14,7 +14,11 @@ export const BasePkiSyncSchema = <T extends AnyZodObject | undefined = undefined(val) => {if (!val) return true;- const allowedOptionalPlaceholders = ["{{environment}}"];+ const allowedOptionalPlaceholders = [+ "{{profileId}}",+ "{{applicationId}}",+ "{{commonName}}"+ ];const allowedPlaceholdersRegexPart = ["{{certificateId}}", ...allowedOptionalPlaceholders].map((p) => p.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&")) // Escape regex special characters@@ -35,7 +39,7 @@ export const BasePkiSyncSchema = <T extends AnyZodObject | undefined = undefined},{message:- "Certificate name schema must include exactly one {{certificateId}} placeholder. It can also include {{environment}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and slashes (/) are allowed besides the placeholders."+ "Certificate name schema must include the {{certificateId}} placeholder. It can also include {{profileId}}, {{applicationId}}, and {{commonName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and slashes (/) are allowed besides the placeholders."})});diff --git a/frontend/src/components/pki-syncs/forms/schemas/chef-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/chef-pki-sync-destination-schema.tsindex 2fe22e84af..50d2d40f4a 100644--- a/frontend/src/components/pki-syncs/forms/schemas/chef-pki-sync-destination-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/chef-pki-sync-destination-schema.ts@@ -31,10 +31,9 @@ const ChefSyncOptionsSchema = z.object({if (!val) return true;const allowedOptionalPlaceholders = [- "{{environment}}","{{profileId}}",- "{{commonName}}",- "{{friendlyName}}"+ "{{applicationId}}",+ "{{commonName}}"];const allowedPlaceholdersRegexPart = ["{{certificateId}}", ...allowedOptionalPlaceholders]@@ -56,7 +55,7 @@ const ChefSyncOptionsSchema = z.object({},{message:- "Certificate item name schema must include exactly one {{certificateId}} placeholder. It can also include {{environment}}, {{profileId}}, {{commonName}}, or {{friendlyName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed besides the placeholders."+ "Certificate item name schema must include exactly one {{certificateId}} placeholder. It can also include {{profileId}}, {{applicationId}}, and {{commonName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed besides the placeholders."}),fieldMappings: ChefFieldMappingsSchema.optional().default({diff --git a/frontend/src/components/pki-syncs/forms/schemas/cloudflare-custom-certificate-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/cloudflare-custom-certificate-pki-sync-destination-schema.tsindex 61fe8ee002..a18a0e99a4 100644--- a/frontend/src/components/pki-syncs/forms/schemas/cloudflare-custom-certificate-pki-sync-destination-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/cloudflare-custom-certificate-pki-sync-destination-schema.ts@@ -14,7 +14,11 @@ const CloudflareCustomCertificateSyncOptionsSchema = z.object({(val) => {if (!val) return true;- const allowedOptionalPlaceholders = ["{{environment}}"];+ const allowedOptionalPlaceholders = [+ "{{profileId}}",+ "{{applicationId}}",+ "{{commonName}}"+ ];const allowedPlaceholdersRegexPart = ["{{certificateId}}", ...allowedOptionalPlaceholders].map((p) => p.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"))@@ -35,7 +39,7 @@ const CloudflareCustomCertificateSyncOptionsSchema = z.object({},{message:- "Certificate name schema must include exactly one {{certificateId}} placeholder. It can also include {{environment}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), and underscores (_) are allowed besides the placeholders."+ "Certificate name schema must include the {{certificateId}} placeholder. It can also include {{profileId}}, {{applicationId}}, and {{commonName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), and underscores (_) are allowed besides the placeholders."})});diff --git a/frontend/src/components/pki-syncs/forms/schemas/f5-big-ip-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/f5-big-ip-pki-sync-destination-schema.tsindex ed6ba918d0..6149fd6e7f 100644--- a/frontend/src/components/pki-syncs/forms/schemas/f5-big-ip-pki-sync-destination-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/f5-big-ip-pki-sync-destination-schema.ts@@ -18,7 +18,11 @@ const F5BigIpSyncOptionsSchema = z.object({(val) => {if (!val) return true;- const allowedOptionalPlaceholders = ["{{environment}}"];+ const allowedOptionalPlaceholders = [+ "{{profileId}}",+ "{{applicationId}}",+ "{{commonName}}"+ ];const allowedPlaceholdersRegexPart = ["{{certificateId}}", ...allowedOptionalPlaceholders].map((p) => p.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"))@@ -39,7 +43,7 @@ const F5BigIpSyncOptionsSchema = z.object({},{message:- "Certificate name schema must include exactly one {{certificateId}} placeholder. It can also include {{environment}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and periods (.) are allowed besides the placeholders."+ "Certificate name schema must include the {{certificateId}} placeholder. It can also include {{profileId}}, {{applicationId}}, and {{commonName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and periods (.) are allowed besides the placeholders."})});diff --git a/frontend/src/components/pki-syncs/forms/schemas/netscaler-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/netscaler-pki-sync-destination-schema.tsindex a4d1b6beab..5e844029c8 100644--- a/frontend/src/components/pki-syncs/forms/schemas/netscaler-pki-sync-destination-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/netscaler-pki-sync-destination-schema.ts@@ -15,7 +15,11 @@ const NetScalerSyncOptionsSchema = z.object({(val) => {if (!val) return true;- const allowedOptionalPlaceholders = ["{{environment}}"];+ const allowedOptionalPlaceholders = [+ "{{profileId}}",+ "{{applicationId}}",+ "{{commonName}}"+ ];const allowedPlaceholdersRegexPart = ["{{certificateId}}", ...allowedOptionalPlaceholders].map((p) => p.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"))@@ -26,17 +30,26 @@ const NetScalerSyncOptionsSchema = z.object({);const contentIsValid = allowedContentRegex.test(val);+ // NetScaler caps certkey names at 63 chars. UUID placeholders resolve to 32 chars each,+ // so check the realistic compiled length to reject over-limit schemas before sync time.+ const compiledLength = val+ .replace(/\{\{certificateId\}\}/g, "0".repeat(32))+ .replace(/\{\{profileId\}\}/g, "0".repeat(32))+ .replace(/\{\{applicationId\}\}/g, "0".repeat(32))+ .replace(/\{\{commonName\}\}/g, "common-name").length;+ const lengthIsValid = compiledLength <= 63;+if (val.trim()) {const certificateIdRegex = /\{\{certificateId\}\}/;const certificateIdIsPresent = certificateIdRegex.test(val);- return contentIsValid && certificateIdIsPresent;+ return contentIsValid && certificateIdIsPresent && lengthIsValid;}return contentIsValid;},{message:- "Certificate name schema must include exactly one {{certificateId}} placeholder. It can also include {{environment}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and periods (.) are allowed besides the placeholders."+ "Certificate name schema must include the {{certificateId}} placeholder and compile to at most 63 characters for NetScaler (each UUID placeholder counts as 32 characters). It can also include {{profileId}}, {{applicationId}}, and {{commonName}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and periods (.) are allowed besides the placeholders."})});