Skip to content

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

fix(pki-sync): claim destination names before writing

bernie-gc62f455b1d38
diff --git a/backend/src/services/certificate-sync/certificate-sync-dal.ts b/backend/src/services/certificate-sync/certificate-sync-dal.ts
index a0a00f2042..ccb4e412ad 100644
--- a/backend/src/services/certificate-sync/certificate-sync-dal.ts
+++ b/backend/src/services/certificate-sync/certificate-sync-dal.ts
@@ -87,6 +87,26 @@ export const certificateSyncDALFactory = (db: TDbClient) => {
}
};
+ const claimExternalIdentifier = async (
+ pkiSyncId: string,
+ certificateId: string,
+ externalIdentifier: string,
+ tx?: Knex
+ ): Promise<void> => {
+ try {
+ await (tx || db)(TableName.CertificateSync)
+ .insert({ pkiSyncId, certificateId, syncStatus: CertificateSyncStatus.Pending, externalIdentifier })
+ .onConflict(["pkiSyncId", "certificateId"])
+ .ignore();
+ await (tx || db)(TableName.CertificateSync)
+ .where({ pkiSyncId, certificateId })
+ .whereNull("externalIdentifier")
+ .update({ externalIdentifier });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "ClaimExternalIdentifier" });
+ }
+ };
+
const addCertificates = async (
pkiSyncId: string,
certificateData: Array<{ certificateId: string; externalIdentifier?: string }>,
@@ -327,6 +347,7 @@ export const certificateSyncDALFactory = (db: TDbClient) => {
findCertificateIdsByPkiSyncId,
findPkiSyncIdsByCertificateId,
findExternalIdentifiersInUse,
+ claimExternalIdentifier,
addCertificates,
removeCertificates,
updateSyncStatus,
diff --git a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-fns.test.ts b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-fns.test.ts
new file mode 100644
index 0000000000..fdb9b424d2
--- /dev/null
+++ b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-fns.test.ts
@@ -0,0 +1,84 @@
+import { TPkiSyncWithCredentials } from "@app/services/pki-sync/pki-sync-types";
+
+import { awsSecretsManagerPkiSyncFactory } from "./aws-secrets-manager-pki-sync-fns";
+
+const { events, existingSecretNames } = vi.hoisted(() => ({
+ events: [] as string[],
+ existingSecretNames: [] as string[]
+}));
+
+vi.mock("@app/lib/crypto", () => ({ crypto: { isFipsModeEnabled: () => false } }));
+vi.mock("@app/lib/aws/hashing", () => ({ CustomAWSHasher: function CustomAWSHasher() {} }));
+vi.mock("@app/services/app-connection/aws/aws-connection-fns", () => ({
+ getAwsConnectionConfig: async () => ({ region: "us-east-1", credentials: { accessKeyId: "a", secretAccessKey: "b" } })
+}));
+vi.mock("@aws-sdk/client-secrets-manager", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@aws-sdk/client-secrets-manager")>();
+ return {
+ ...actual,
+ SecretsManagerClient: class {
+ // eslint-disable-next-line class-methods-use-this
+ async send(command: { constructor: { name: string }; input: { Name?: string; SecretId?: string } }) {
+ const { name } = command.constructor;
+ if (name === "ListSecretsCommand") {
+ return { SecretList: existingSecretNames.map((Name) => ({ Name, ARN: Name })) };
+ }
+ events.push(`${name}:${command.input.Name ?? command.input.SecretId}`);
+ return {};
+ }
+ }
+ };
+});
+
+const CERT_ID = "550e8400-e29b-41d4-a716-446655440000";
+const SECRET_NAME = "infisical-550e8400e29b41d4a716446655440000";
+
+const makeFactory = (ownedByOtherSync: string[] = []) =>
+ awsSecretsManagerPkiSyncFactory({
+ certificateDAL: { findById: async () => ({ id: CERT_ID }) } as never,
+ certificateSyncDAL: {
+ findByPkiSyncId: async () => [],
+ claimExternalIdentifier: async (_syncId: string, _certId: string, name: string) => {
+ events.push(`claim:${name}`);
+ },
+ findExternalIdentifiersInUse: async () => new Set(ownedByOtherSync),
+ findByPkiSyncAndCertificate: async () => ({ id: "record-1" }),
+ updateById: async () => ({}),
+ removeCertificates: async () => 0,
+ addCertificates: async () => [],
+ updateSyncStatus: async () => {}
+ } as never
+ });
+
+const pkiSync = {
+ id: "sync-1",
+ destination: "aws-secrets-manager",
+ destinationConfig: { region: "us-east-1" },
+ syncOptions: { certificateNameSchema: "infisical-{{certificateId}}", canRemoveCertificates: true },
+ connection: {}
+} as unknown as TPkiSyncWithCredentials;
+
+describe("AWS Secrets Manager PKI sync destination ownership", () => {
+ beforeEach(() => {
+ events.length = 0;
+ existingSecretNames.length = 0;
+ });
+
+ test("claims the secret name before creating the secret", async () => {
+ await makeFactory().syncCertificates(pkiSync, {
+ [SECRET_NAME]: { cert: "CERT", privateKey: "KEY", certificateId: CERT_ID }
+ } as never);
+
+ expect(events).toEqual([`claim:${SECRET_NAME}`, `CreateSecretCommand:${SECRET_NAME}`]);
+ });
+
+ test("does not delete managed-looking secrets owned by another sync", async () => {
+ const otherSyncSecret = "infisical-aaaaaaaabbbbccccddddeeeeeeeeeeee";
+ const orphanSecret = "infisical-11111111222233334444555555555555";
+ existingSecretNames.push(otherSyncSecret, orphanSecret, "infisical-app-db-password");
+
+ await makeFactory([otherSyncSecret]).syncCertificates(pkiSync, {} as never);
+
+ expect(events).toEqual([`DeleteSecretCommand:${orphanSecret}`]);
+ });
+});
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.ts
index c77d91d27f..b418ef47ce 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
@@ -110,6 +110,7 @@ type TAwsSecretsManagerPkiSyncFactoryDeps = {
| "findByPkiSyncId"
| "updateSyncStatus"
| "findExternalIdentifiersInUse"
+ | "claimExternalIdentifier"
>;
};
@@ -346,6 +347,8 @@ export const awsSecretsManagerPkiSyncFactory = ({
const configKeyId: unknown = awsPkiSync.destinationConfig.keyId;
const keyId: string = typeof configKeyId === "string" ? configKeyId : "alias/aws/secretsmanager";
+ await certificateSyncDAL.claimExternalIdentifier(pkiSync.id, certificateId, targetSecretName);
+
if (isUpdate) {
await withRateLimitRetry(
() =>
@@ -381,34 +384,18 @@ export const awsSecretsManagerPkiSyncFactory = ({
result.uploaded += 1;
}
- const existingRecord = syncRecordsByCertId.get(certificateId);
- if (existingRecord?.id) {
- await certificateSyncDAL.updateById(existingRecord.id, {
+ const certSync = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId);
+ if (certSync?.id) {
+ await certificateSyncDAL.updateById(certSync.id, {
externalIdentifier: targetSecretName,
syncStatus: CertificateSyncStatus.Succeeded,
lastSyncedAt: new Date(),
lastSyncMessage: "Certificate successfully synced to AWS Secrets Manager"
});
+ }
- if (oldCertificateIdToRemove && oldCertificateIdToRemove !== certificateId) {
- await certificateSyncDAL.removeCertificates(pkiSync.id, [oldCertificateIdToRemove]);
- }
- } else {
- await certificateSyncDAL.addCertificates(pkiSync.id, [
- {
- certificateId,
- externalIdentifier: targetSecretName
- }
- ]);
-
- const newCertSync = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId);
- if (newCertSync?.id) {
- await certificateSyncDAL.updateById(newCertSync.id, {
- syncStatus: CertificateSyncStatus.Succeeded,
- lastSyncedAt: new Date(),
- lastSyncMessage: "Certificate successfully synced to AWS Secrets Manager"
- });
- }
+ if (oldCertificateIdToRemove && oldCertificateIdToRemove !== certificateId) {
+ await certificateSyncDAL.removeCertificates(pkiSync.id, [oldCertificateIdToRemove]);
}
} catch (error) {
result.details?.failedUploads?.push({
@@ -425,9 +412,9 @@ export const awsSecretsManagerPkiSyncFactory = ({
"Failed to sync certificate"
);
- const existingRecord = syncRecordsByCertId.get(certificateId);
- if (existingRecord?.id) {
- await certificateSyncDAL.updateById(existingRecord.id, {
+ const failedCertSync = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId);
+ if (failedCertSync?.id) {
+ await certificateSyncDAL.updateById(failedCertSync.id, {
syncStatus: CertificateSyncStatus.Failed,
lastSyncMessage: parseErrorMessage(error)
});
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.ts
index d96c2f8e4e..cfe964ffb5 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
@@ -62,6 +62,7 @@ type TAzureKeyVaultPkiSyncFactoryDeps = {
| "findByPkiSyncId"
| "updateSyncStatus"
| "findExternalIdentifiersInUse"
+ | "claimExternalIdentifier"
>;
certificateDAL: Pick<TCertificateDALFactory, "findById">;
};
@@ -526,6 +527,10 @@ export const azureKeyVaultPkiSyncFactory = ({
}
};
+ if (certificateId) {
+ await certificateSyncDAL.claimExternalIdentifier(pkiSync.id, certificateId, key);
+ }
+
const response = await request.post(
`${destinationConfig.vaultBaseUrl}/certificates/${encodeURIComponent(key)}/import?api-version=7.4`,
importData,
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.ts
index 810afcf59f..51215724b5 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
@@ -74,6 +74,7 @@ type TChefPkiSyncFactoryDeps = {
| "findByPkiSyncId"
| "updateSyncStatus"
| "findExternalIdentifiersInUse"
+ | "claimExternalIdentifier"
>;
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
@@ -297,6 +298,8 @@ export const chefPkiSyncFactory = ({
...(caCertificate && { [fieldMappings.caCertificate]: caCertificate })
};
+ await certificateSyncDAL.claimExternalIdentifier(pkiSync.id, certificateId, targetItemName);
+
const itemExists = chefDataBagItems[targetItemName] === true;
if (itemExists) {
diff --git a/backend/src/services/pki-sync/kemp-loadmaster/kemp-loadmaster-pki-sync-fns.ts b/backend/src/services/pki-sync/kemp-loadmaster/kemp-loadmaster-pki-sync-fns.ts
index 1877d55294..f60155c464 100644
--- a/backend/src/services/pki-sync/kemp-loadmaster/kemp-loadmaster-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/kemp-loadmaster/kemp-loadmaster-pki-sync-fns.ts
@@ -47,6 +47,7 @@ type TKempLoadMasterPkiSyncFactoryDeps = {
| "findByPkiSyncId"
| "updateSyncStatus"
| "findExternalIdentifiersInUse"
+ | "claimExternalIdentifier"
>;
certificateDAL: Pick<TCertificateDALFactory, "findById">;
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
@@ -498,6 +499,10 @@ export const kempLoadMasterPkiSyncFactory = ({
oldCertificateIdToRemove
} of certificatesToUpload) {
try {
+ if (certificateId) {
+ await certificateSyncDAL.claimExternalIdentifier(pkiSync.id, certificateId, targetIdentifier);
+ }
+
const bundle = buildCertificateBundle(cert, privateKey, certificateChain);
await upsertCertificate(
makeRequest,
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.ts
index 1b69756b73..a5c88caeaf 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
@@ -46,6 +46,7 @@ type TNetScalerPkiSyncFactoryDeps = {
| "findByPkiSyncId"
| "updateSyncStatus"
| "findExternalIdentifiersInUse"
+ | "claimExternalIdentifier"
>;
certificateDAL: Pick<TCertificateDALFactory, "findById">;
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
@@ -496,6 +497,10 @@ export const netScalerPkiSyncFactory = ({
fullCertContent = `${cert}\n${certificateChain}`;
}
+ if (certificateId) {
+ await certificateSyncDAL.claimExternalIdentifier(pkiSync.id, certificateId, targetCertKeyName);
+ }
+
await uploadFileToNetScaler(session, certFilename, fullCertContent);
await uploadFileToNetScaler(session, keyFilename, privateKey);
await createOrUpdateCertKey(session, targetCertKeyName, certFilename, keyFilename);