Add Certificate Syncs

This commit is contained in:
Carlos Monastyrski
2025-09-16 01:36:06 -03:00
parent ca877cb225
commit 5bfff46c16
100 changed files with 8044 additions and 31 deletions
@@ -25,6 +25,20 @@ export const certificateDALFactory = (db: TDbClient) => {
}
};
const findAllActiveCertsForSubscriber = async ({ subscriberId }: { subscriberId: string }) => {
try {
const certs = await db
.replicaNode()(TableName.Certificate)
.where({ pkiSubscriberId: subscriberId, status: CertStatus.ACTIVE })
.where("notAfter", ">", new Date())
.orderBy("notBefore", "desc");
return certs;
} catch (error) {
throw new DatabaseError({ error, name: "Find all active certificates for subscriber" });
}
};
const countCertificatesInProject = async ({
projectId,
friendlyName,
@@ -83,6 +97,7 @@ export const certificateDALFactory = (db: TDbClient) => {
...certificateOrm,
countCertificatesInProject,
countCertificatesForPkiSubscriber,
findLatestActiveCertForSubscriber
findLatestActiveCertForSubscriber,
findAllActiveCertsForSubscriber
};
};
@@ -1,3 +1,4 @@
/* eslint-disable no-await-in-loop */
import { ForbiddenError } from "@casl/ability";
import * as x509 from "@peculiar/x509";
@@ -10,6 +11,7 @@ import {
} from "@app/ee/services/permission/project-permission";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";
@@ -20,6 +22,8 @@ import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TPkiCollectionDALFactory } from "@app/services/pki-collection/pki-collection-dal";
import { TPkiCollectionItemDALFactory } from "@app/services/pki-collection/pki-collection-item-dal";
import { TPkiSyncDALFactory } from "@app/services/pki-sync/pki-sync-dal";
import { TPkiSyncQueueFactory } from "@app/services/pki-sync/pki-sync-queue";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
@@ -53,6 +57,8 @@ type TCertificateServiceFactoryDep = {
projectDAL: Pick<TProjectDALFactory, "findProjectBySlug" | "findOne" | "updateById" | "findById" | "transaction">;
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
};
export type TCertificateServiceFactory = ReturnType<typeof certificateServiceFactory>;
@@ -69,8 +75,32 @@ export const certificateServiceFactory = ({
pkiCollectionItemDAL,
projectDAL,
kmsService,
permissionService
permissionService,
pkiSyncDAL,
pkiSyncQueue
}: TCertificateServiceFactoryDep) => {
/**
* Trigger auto sync for PKI syncs connected to a PKI subscriber when certificates are issued/revoked/deleted
*/
const triggerAutoSyncForSubscriber = async (subscriberId: string) => {
try {
// Find all PKI syncs that are connected to this subscriber and have auto sync enabled
const pkiSyncs = await pkiSyncDAL.find({
subscriberId,
isAutoSyncEnabled: true
});
// Queue sync jobs for each auto sync enabled PKI sync
for (const pkiSync of pkiSyncs) {
await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSync.id });
}
} catch (error) {
// Don't throw error to avoid breaking the main certificate operation
// Just log the auto sync failure
logger.error(error, `Failed to trigger auto sync for subscriber ${subscriberId}:`);
}
};
/**
* Return details for certificate with serial number [serialNumber]
*/
@@ -158,6 +188,11 @@ export const certificateServiceFactory = ({
const deletedCert = await certificateDAL.deleteById(cert.id);
// Trigger auto sync for PKI syncs connected to this certificate's subscriber
if (cert.pkiSubscriberId) {
await triggerAutoSyncForSubscriber(cert.pkiSubscriberId);
}
return {
deletedCert
};
@@ -222,6 +257,11 @@ export const certificateServiceFactory = ({
}
);
// Trigger auto sync for PKI syncs connected to this certificate's subscriber
if (cert.pkiSubscriberId) {
await triggerAutoSyncForSubscriber(cert.pkiSubscriberId);
}
// Note: External CA revocation handling would go here for supported CA types
// Currently, only internal CAs and ACME CAs support revocation
@@ -1,3 +1,4 @@
/* eslint-disable no-await-in-loop */
/* eslint-disable no-bitwise */
import { ForbiddenError, subject } from "@casl/ability";
import * as x509 from "@peculiar/x509";
@@ -12,6 +13,7 @@ import {
} from "@app/ee/services/permission/project-permission";
import { getConfig } from "@app/lib/config/env";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { ms } from "@app/lib/ms";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
@@ -36,6 +38,8 @@ import {
import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TPkiSubscriberDALFactory } from "@app/services/pki-subscriber/pki-subscriber-dal";
import { TPkiSyncDALFactory } from "@app/services/pki-sync/pki-sync-dal";
import { TPkiSyncQueueFactory } from "@app/services/pki-sync/pki-sync-queue";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
@@ -79,6 +83,8 @@ type TPkiSubscriberServiceFactoryDep = {
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "decryptWithKmsKey" | "encryptWithKmsKey">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
internalCaFns: ReturnType<typeof InternalCertificateAuthorityFns>;
pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;
};
export type TPkiSubscriberServiceFactory = ReturnType<typeof pkiSubscriberServiceFactory>;
@@ -96,8 +102,32 @@ export const pkiSubscriberServiceFactory = ({
kmsService,
permissionService,
certificateAuthorityQueue,
internalCaFns
internalCaFns,
pkiSyncDAL,
pkiSyncQueue
}: TPkiSubscriberServiceFactoryDep) => {
/**
* Trigger auto sync for PKI syncs connected to a PKI subscriber when certificates are issued
*/
const triggerAutoSyncForSubscriber = async (subscriberId: string) => {
try {
// Find all PKI syncs that are connected to this subscriber and have auto sync enabled
const pkiSyncs = await pkiSyncDAL.find({
subscriberId,
isAutoSyncEnabled: true
});
// Queue sync jobs for each auto sync enabled PKI sync
for (const pkiSync of pkiSyncs) {
await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSync.id });
}
} catch (error) {
// Don't throw error to avoid breaking the main certificate operation
// Just log the auto sync failure
logger.error(error, `Failed to trigger auto sync for subscriber ${subscriberId}:`);
}
};
const createSubscriber = async ({
name,
commonName,
@@ -413,7 +443,12 @@ export const pkiSubscriberServiceFactory = ({
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(subscriber.caId);
if (ca.internalCa?.id) {
return internalCaFns.issueCertificate(subscriber, ca);
const result = await internalCaFns.issueCertificate(subscriber, ca);
// Trigger auto sync for PKI syncs connected to this subscriber after certificate issuance
await triggerAutoSyncForSubscriber(subscriber.id);
return result;
}
throw new BadRequestError({ message: "CA does not support immediate issuance of certificates" });
@@ -671,6 +706,9 @@ export const pkiSubscriberServiceFactory = ({
return cert;
});
// Trigger auto sync for PKI syncs connected to this subscriber after certificate signing
await triggerAutoSyncForSubscriber(subscriber.id);
return {
certificate: leafCert.toString("pem"),
certificateChain: `${issuingCaCertificate}\n${caCertChain}`.trim(),
@@ -0,0 +1,521 @@
/* eslint-disable no-await-in-loop */
import { AxiosError } from "axios";
import { request } from "@app/lib/config/request";
import { logger } from "@app/lib/logger";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { getAzureConnectionAccessToken } from "@app/services/app-connection/azure-key-vault";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TCertificateMap } from "@app/services/pki-sync/pki-sync-types";
import { PkiSyncError } from "../pki-sync-errors";
import { GetAzureKeyVaultCertificate, TAzureKeyVaultPkiSyncWithCredentials } from "./azure-key-vault-pki-sync-types";
type TAzureKeyVaultPkiSyncFactoryDeps = {
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
};
export const azureKeyVaultPkiSyncFactory = ({ kmsService, appConnectionDAL }: TAzureKeyVaultPkiSyncFactoryDeps) => {
const $getAzureKeyVaultCertificates = async (accessToken: string, vaultBaseUrl: string) => {
const paginateAzureKeyVaultCertificates = async () => {
let result: GetAzureKeyVaultCertificate[] = [];
let currentUrl = `${vaultBaseUrl}/certificates?api-version=7.4`;
while (currentUrl) {
const res = await request.get<{ value: GetAzureKeyVaultCertificate[]; nextLink: string }>(currentUrl, {
headers: {
Authorization: `Bearer ${accessToken}`
}
});
result = result.concat(res.data.value);
currentUrl = res.data.nextLink;
}
return result;
};
const getAzureKeyVaultCertificates = await paginateAzureKeyVaultCertificates();
const enabledAzureKeyVaultCertificates = getAzureKeyVaultCertificates.filter((cert) => cert.attributes.enabled);
// disabled certificates to skip sending updates to
const disabledAzureKeyVaultCertificateKeys = getAzureKeyVaultCertificates
.filter(({ attributes }) => !attributes.enabled)
.map((getAzureKeyVaultCertificate) => {
return getAzureKeyVaultCertificate.id.substring(getAzureKeyVaultCertificate.id.lastIndexOf("/") + 1);
});
let lastSlashIndex: number;
const res = (
await Promise.all(
enabledAzureKeyVaultCertificates.map(async (getAzureKeyVaultCertificate) => {
if (!lastSlashIndex) {
lastSlashIndex = getAzureKeyVaultCertificate.id.lastIndexOf("/");
}
// Get the certificate details
const azureKeyVaultCertificate = await request.get<GetAzureKeyVaultCertificate>(
`${getAzureKeyVaultCertificate.id}?api-version=7.4`,
{
headers: {
Authorization: `Bearer ${accessToken}`
}
}
);
// Convert base64 certificate to PEM format if available
let certPem = "";
if (azureKeyVaultCertificate.data.cer) {
try {
// Azure Key Vault stores certificate in base64 DER format
// We need to convert it to PEM format with proper headers
const base64Cert = azureKeyVaultCertificate.data.cer;
certPem = `-----BEGIN CERTIFICATE-----\n${base64Cert.match(/.{1,64}/g)?.join("\n")}\n-----END CERTIFICATE-----`;
} catch (error) {
// If conversion fails, assume it's already in PEM format
certPem = azureKeyVaultCertificate.data.cer;
}
}
return {
...azureKeyVaultCertificate.data,
key: getAzureKeyVaultCertificate.id.substring(lastSlashIndex + 1),
cert: certPem,
privateKey: "" // Private keys cannot be extracted from Azure Key Vault for security reasons
};
})
)
).reduce(
(obj, certificate) => ({
...obj,
[certificate.key]: {
cert: certificate.cert,
privateKey: certificate.privateKey
}
}),
{} as Record<string, { cert: string; privateKey: string }>
);
return {
vaultCertificates: res,
disabledAzureKeyVaultCertificateKeys
};
};
const syncCertificates = async (pkiSync: TAzureKeyVaultPkiSyncWithCredentials, certificateMap: TCertificateMap) => {
logger.info(
{
syncId: pkiSync.id,
vaultUrl: pkiSync.destinationConfig.vaultBaseUrl,
certificateCount: Object.keys(certificateMap).length
},
"Starting Azure Key Vault certificate sync"
);
const { accessToken } = await getAzureConnectionAccessToken(pkiSync.connection.id, appConnectionDAL, kmsService);
const { vaultCertificates, disabledAzureKeyVaultCertificateKeys } = await $getAzureKeyVaultCertificates(
accessToken,
pkiSync.destinationConfig.vaultBaseUrl
);
logger.info(
{
syncId: pkiSync.id,
existingCertCount: Object.keys(vaultCertificates).length,
disabledCertCount: disabledAzureKeyVaultCertificateKeys.length
},
"Retrieved existing certificates from Azure Key Vault"
);
const setCertificates: {
key: string;
cert: string;
privateKey: string;
}[] = [];
// Track which certificates should exist in Azure Key Vault
const activeCertificateNames = Object.keys(certificateMap);
// Iterate through certificates to sync to Azure Key Vault
Object.entries(certificateMap).forEach(([certName, { cert, privateKey }]) => {
if (disabledAzureKeyVaultCertificateKeys.includes(certName)) {
logger.debug(
{ syncId: pkiSync.id, certificateName: certName },
"Skipping disabled certificate in Azure Key Vault"
);
return;
}
const existingCert = vaultCertificates[certName];
const shouldUpdateCert = !existingCert || existingCert.cert !== cert;
if (shouldUpdateCert) {
setCertificates.push({
key: certName,
cert,
privateKey
});
logger.debug(
{ syncId: pkiSync.id, certificateName: certName, isUpdate: !!existingCert },
"Certificate will be uploaded to Azure Key Vault"
);
} else {
logger.debug(
{ syncId: pkiSync.id, certificateName: certName },
"Certificate already up to date in Azure Key Vault"
);
}
});
// Identify expired/removed certificates that need to be cleaned up from Azure Key Vault
// Only remove certificates that were managed by Infisical (start with 'Infisical-')
const certificatesToRemove = Object.keys(vaultCertificates).filter(
(vaultCertName) =>
vaultCertName.startsWith("Infisical-") &&
!activeCertificateNames.includes(vaultCertName) &&
!disabledAzureKeyVaultCertificateKeys.includes(vaultCertName)
);
logger.info(
{
syncId: pkiSync.id,
certificatesToUpload: setCertificates.length,
certificatesToRemove: certificatesToRemove.length,
totalCertificates: Object.keys(certificateMap).length
},
"Determined certificates to upload and remove from Azure Key Vault"
);
// Upload certificates to Azure Key Vault
const uploadPromises = setCertificates.map(async ({ key, cert, privateKey }) => {
try {
// Combine certificate and private key in PEM format for Azure Key Vault
// Azure Key Vault accepts PEM format with both cert and private key
let combinedPem = cert;
if (privateKey) {
combinedPem = `${privateKey}\n${cert}`;
}
// Convert to base64 for Azure Key Vault import
const base64Cert = Buffer.from(combinedPem).toString("base64");
const importData = {
value: base64Cert,
policy: {
key_props: {
exportable: true,
key_size: 2048,
kty: "RSA",
reuse_key: false
},
secret_props: {
contentType: "application/x-pem-file"
},
x509_props: {
subject: "",
sans: {
dns_names: [],
emails: [],
upns: []
}
}
}
};
const response = await request.post(
`${pkiSync.destinationConfig.vaultBaseUrl}/certificates/${encodeURIComponent(key)}/import?api-version=7.4`,
importData,
{
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json"
}
}
);
logger.info(
{ syncId: pkiSync.id, certificateName: key },
"Successfully uploaded certificate to Azure Key Vault"
);
return { key, success: true, response: response.data as unknown };
} catch (error) {
if (error instanceof AxiosError) {
const errorMessage =
error.response?.data && typeof error.response.data === "object" && "error" in error.response.data
? (error.response.data as { error?: { message?: string } }).error?.message || error.message
: error.message;
// Check if the error is due to certificate in deleted but recoverable state
const isDeletedButRecoverable =
errorMessage.includes("deleted but recoverable state") || errorMessage.includes("name cannot be reused");
if (isDeletedButRecoverable) {
logger.warn(
{ certificateKey: key, syncId: pkiSync.id },
"Certificate exists in deleted but recoverable state in Azure Key Vault - skipping upload"
);
// Return a successful result to avoid failing the entire sync
return { key, success: false, skipped: true, reason: "Certificate in deleted but recoverable state" };
}
throw new PkiSyncError({
message: `Failed to upload certificate ${key} to Azure Key Vault: ${errorMessage}`,
cause: error,
context: {
certificateKey: key,
statusCode: error.response?.status,
responseData: error.response?.data
}
});
}
throw error;
}
});
const results = await Promise.allSettled(uploadPromises);
const failedUploads = results.filter((result) => result.status === "rejected");
const fulfilledResults = results.filter((result) => result.status === "fulfilled");
// Separate successful uploads from skipped certificates
const successfulUploads = fulfilledResults.filter(
(result) => result.status === "fulfilled" && result.value.success
);
const skippedUploads = fulfilledResults.filter((result) => result.status === "fulfilled" && result.value.skipped);
// Remove expired/removed certificates from Azure Key Vault
let removedCertificates = 0;
let failedRemovals = 0;
if (certificatesToRemove.length > 0) {
logger.info(
{
syncId: pkiSync.id,
certificatesToRemove: certificatesToRemove.length
},
"Removing expired/removed certificates from Azure Key Vault"
);
const removePromises = certificatesToRemove.map(async (certName) => {
try {
await request.delete(
`${pkiSync.destinationConfig.vaultBaseUrl}/certificates/${encodeURIComponent(certName)}?api-version=7.4`,
{
headers: {
Authorization: `Bearer ${accessToken}`
}
}
);
logger.info(
{ syncId: pkiSync.id, certificateName: certName },
"Successfully removed expired/removed certificate from Azure Key Vault"
);
return { key: certName, success: true };
} catch (error) {
// If certificate doesn't exist (404), consider it as successfully removed
if (error instanceof AxiosError && error.response?.status === 404) {
logger.info(
{ syncId: pkiSync.id, certificateName: certName },
"Certificate not found in Azure Key Vault during sync cleanup - considering removal successful"
);
return { key: certName, success: true, alreadyRemoved: true };
}
logger.error(
{ error, syncId: pkiSync.id, certificateName: certName },
"Failed to remove expired/removed certificate from Azure Key Vault"
);
// Don't throw here - we want to continue with other operations
return { key: certName, success: false, error: error as Error };
}
});
const removeResults = await Promise.allSettled(removePromises);
const successfulRemovals = removeResults.filter(
(result) => result.status === "fulfilled" && result.value.success
);
removedCertificates = successfulRemovals.length;
failedRemovals = removeResults.length - removedCertificates;
if (failedRemovals > 0) {
logger.warn(
{
syncId: pkiSync.id,
failedRemovals,
successfulRemovals: removedCertificates
},
"Some expired/removed certificates could not be removed from Azure Key Vault"
);
}
}
// Log skipped certificates for transparency
if (skippedUploads.length > 0) {
const skippedNames = skippedUploads.map((result) =>
result.status === "fulfilled" ? result.value.key : "unknown"
);
logger.info(
{
syncId: pkiSync.id,
skippedCertificates: skippedNames,
skippedCount: skippedUploads.length
},
"Some certificates were skipped due to Azure Key Vault constraints"
);
}
logger.info(
{
syncId: pkiSync.id,
successfulUploads: successfulUploads.length,
failedUploads: failedUploads.length,
skippedUploads: skippedUploads.length,
removedCertificates,
failedRemovals,
skippedCertificates: Object.keys(certificateMap).length - setCertificates.length
},
"Azure Key Vault certificate sync completed"
);
if (failedUploads.length > 0) {
const failedReasons = failedUploads.map((failure) => {
if (failure.status === "rejected") {
return (failure.reason as Error)?.message || "Unknown error";
}
return "Unknown error";
});
logger.error(
{
syncId: pkiSync.id,
failedReasons,
failedCount: failedUploads.length
},
"Some certificates failed to upload to Azure Key Vault"
);
throw new PkiSyncError({
message: `Failed to upload ${failedUploads.length} certificate(s) to Azure Key Vault`,
context: {
failedReasons,
totalCertificates: setCertificates.length,
failedCount: failedUploads.length
}
});
}
return {
uploaded: setCertificates.length,
removed: removedCertificates,
failedRemovals,
skipped: Object.keys(certificateMap).length - setCertificates.length
};
};
const importCertificates = async (pkiSync: TAzureKeyVaultPkiSyncWithCredentials): Promise<TCertificateMap> => {
const { accessToken } = await getAzureConnectionAccessToken(pkiSync.connection.id, appConnectionDAL, kmsService);
const { vaultCertificates } = await $getAzureKeyVaultCertificates(
accessToken,
pkiSync.destinationConfig.vaultBaseUrl
);
return vaultCertificates;
};
const removeCertificates = async (pkiSync: TAzureKeyVaultPkiSyncWithCredentials, certificateNames: string[]) => {
const { accessToken } = await getAzureConnectionAccessToken(pkiSync.connection.id, appConnectionDAL, kmsService);
// Only remove certificates that are managed by Infisical (start with 'Infisical-' prefix)
const infisicalManagedCertNames = certificateNames.filter((certName) => certName.startsWith("Infisical-"));
if (infisicalManagedCertNames.length < certificateNames.length) {
logger.debug(
{
syncId: pkiSync.id,
totalRequested: certificateNames.length,
infisicalManaged: infisicalManagedCertNames.length,
skipped: certificateNames.length - infisicalManagedCertNames.length
},
"Filtered out non-Infisical certificates from removal request"
);
}
const removePromises = infisicalManagedCertNames.map(async (certName) => {
try {
const response = await request.delete(
`${pkiSync.destinationConfig.vaultBaseUrl}/certificates/${encodeURIComponent(certName)}?api-version=7.4`,
{
headers: {
Authorization: `Bearer ${accessToken}`
}
}
);
return { key: certName, success: true, response: response.data as unknown };
} catch (error) {
if (error instanceof AxiosError) {
// If certificate doesn't exist (404), consider it as successfully removed
if (error.response?.status === 404) {
logger.info(
{ syncId: pkiSync.id, certificateName: certName },
"Certificate not found in Azure Key Vault - considering removal successful"
);
return { key: certName, success: true, alreadyRemoved: true };
}
throw new PkiSyncError({
message: `Failed to remove certificate ${certName} from Azure Key Vault`,
cause: error,
context: {
certificateKey: certName,
statusCode: error.response?.status,
responseData: error.response?.data
}
});
}
throw error;
}
});
const results = await Promise.allSettled(removePromises);
const failedRemovals = results.filter((result) => result.status === "rejected");
if (failedRemovals.length > 0) {
const failedReasons = failedRemovals.map((failure) => {
if (failure.status === "rejected") {
return (failure.reason as Error)?.message || "Unknown error";
}
return "Unknown error";
});
throw new PkiSyncError({
message: `Failed to remove ${failedRemovals.length} certificate(s) from Azure Key Vault`,
context: {
failedReasons,
totalCertificates: infisicalManagedCertNames.length,
failedCount: failedRemovals.length
}
});
}
return {
removed: infisicalManagedCertNames.length - failedRemovals.length,
failed: failedRemovals.length,
skipped: certificateNames.length - infisicalManagedCertNames.length
};
};
return {
syncCertificates,
importCertificates,
removeCertificates
};
};
@@ -0,0 +1,29 @@
import { z } from "zod";
import { TPkiSyncWithCredentials } from "../pki-sync-types";
export type GetAzureKeyVaultCertificate = {
id: string;
value: string;
attributes: {
enabled: boolean;
created: number;
updated: number;
recoveryLevel: string;
tags?: Record<string, string>;
};
x5t?: string;
contentType?: string;
key?: string;
cer?: string;
};
export const AzureKeyVaultPkiSyncConfigSchema = z.object({
vaultBaseUrl: z.string().url()
});
export type TAzureKeyVaultPkiSyncConfig = z.infer<typeof AzureKeyVaultPkiSyncConfigSchema>;
export type TAzureKeyVaultPkiSyncWithCredentials = TPkiSyncWithCredentials & {
destinationConfig: TAzureKeyVaultPkiSyncConfig;
};
@@ -0,0 +1,181 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { TableName, TPkiSyncs } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { buildFindFilter, ormify, prependTableNameToFindFilter, selectAllTableCols } from "@app/lib/knex";
import { PkiSync } from "./pki-sync-enums";
export type TPkiSyncDALFactory = ReturnType<typeof pkiSyncDALFactory>;
type PkiSyncFindFilter = Parameters<typeof buildFindFilter<TPkiSyncs>>[0];
const basePkiSyncQuery = ({ filter, db, tx }: { db: TDbClient; filter?: PkiSyncFindFilter; tx?: Knex }) => {
const query = (tx || db.replicaNode())(TableName.PkiSync)
.leftJoin(TableName.AppConnection, `${TableName.PkiSync}.connectionId`, `${TableName.AppConnection}.id`)
.select(selectAllTableCols(TableName.PkiSync))
.select(
// app connection fields
db.ref("name").withSchema(TableName.AppConnection).as("appConnectionName"),
db.ref("app").withSchema(TableName.AppConnection).as("appConnectionApp"),
db.ref("encryptedCredentials").withSchema(TableName.AppConnection).as("appConnectionEncryptedCredentials"),
db.ref("orgId").withSchema(TableName.AppConnection).as("appConnectionOrgId"),
db.ref("method").withSchema(TableName.AppConnection).as("appConnectionMethod"),
db.ref("description").withSchema(TableName.AppConnection).as("appConnectionDescription"),
db.ref("version").withSchema(TableName.AppConnection).as("appConnectionVersion"),
db.ref("gatewayId").withSchema(TableName.AppConnection).as("appConnectionGatewayId"),
db.ref("createdAt").withSchema(TableName.AppConnection).as("appConnectionCreatedAt"),
db.ref("updatedAt").withSchema(TableName.AppConnection).as("appConnectionUpdatedAt"),
db
.ref("isPlatformManagedCredentials")
.withSchema(TableName.AppConnection)
.as("appConnectionIsPlatformManagedCredentials"),
db.ref("encryptedCredentials").withSchema(TableName.AppConnection).as("appConnectionEncryptedCredentials")
);
if (filter) {
// eslint-disable-next-line @typescript-eslint/no-misused-promises
void query.where(buildFindFilter(prependTableNameToFindFilter(TableName.PkiSync, filter)));
}
return query;
};
const expandPkiSync = (pkiSync: Awaited<ReturnType<typeof basePkiSyncQuery>>[number]) => {
const {
appConnectionName,
appConnectionApp,
appConnectionEncryptedCredentials,
appConnectionOrgId,
appConnectionMethod,
appConnectionDescription,
appConnectionVersion,
appConnectionGatewayId,
appConnectionCreatedAt,
appConnectionUpdatedAt,
appConnectionIsPlatformManagedCredentials,
...el
} = pkiSync;
return {
...el,
destination: el.destination as PkiSync,
destinationConfig: el.destinationConfig as Record<string, unknown>,
syncOptions: el.syncOptions as Record<string, unknown>,
appConnectionName,
appConnectionApp,
connection: {
id: el.connectionId,
name: appConnectionName,
app: appConnectionApp,
encryptedCredentials: appConnectionEncryptedCredentials,
orgId: appConnectionOrgId,
method: appConnectionMethod,
description: appConnectionDescription,
version: appConnectionVersion,
gatewayId: appConnectionGatewayId,
createdAt: appConnectionCreatedAt,
updatedAt: appConnectionUpdatedAt,
isPlatformManagedCredentials: appConnectionIsPlatformManagedCredentials
}
};
};
export const pkiSyncDALFactory = (db: TDbClient) => {
const pkiSyncOrm = ormify(db, TableName.PkiSync);
const findByProjectId = async (projectId: string, tx?: Knex) => {
try {
const pkiSyncs = await basePkiSyncQuery({ filter: { projectId }, db, tx });
return pkiSyncs.map(expandPkiSync);
} catch (error) {
throw new DatabaseError({ error, name: "Find By Project ID - PKI Sync" });
}
};
const findBySubscriberId = async (subscriberId: string, tx?: Knex) => {
try {
const pkiSyncs = await basePkiSyncQuery({ filter: { subscriberId }, db, tx });
return pkiSyncs.map(expandPkiSync);
} catch (error) {
throw new DatabaseError({ error, name: "Find By Subscriber ID - PKI Sync" });
}
};
const findByIdAndProjectId = async (id: string, projectId: string, tx?: Knex) => {
try {
const pkiSync = await basePkiSyncQuery({ filter: { id, projectId }, db, tx }).first();
return pkiSync ? expandPkiSync(pkiSync) : undefined;
} catch (error) {
throw new DatabaseError({ error, name: "Find By ID and Project ID - PKI Sync" });
}
};
const findByNameAndProjectId = async (name: string, projectId: string, tx?: Knex) => {
try {
const pkiSync = await basePkiSyncQuery({ filter: { name, projectId }, db, tx }).first();
return pkiSync ? expandPkiSync(pkiSync) : undefined;
} catch (error) {
throw new DatabaseError({ error, name: "Find By Name and Project ID - PKI Sync" });
}
};
const findById = async (id: string, tx?: Knex) => {
try {
const pkiSync = await basePkiSyncQuery({ filter: { id }, db, tx }).first();
return pkiSync ? expandPkiSync(pkiSync) : undefined;
} catch (error) {
throw new DatabaseError({ error, name: "Find By ID - PKI Sync" });
}
};
const findOne = async (filter: Parameters<(typeof pkiSyncOrm)["findOne"]>[0], tx?: Knex) => {
try {
const pkiSync = await basePkiSyncQuery({ filter, db, tx }).first();
return pkiSync ? expandPkiSync(pkiSync) : undefined;
} catch (error) {
throw new DatabaseError({ error, name: "Find One - PKI Sync" });
}
};
const find = async (filter: Parameters<(typeof pkiSyncOrm)["find"]>[0], tx?: Knex) => {
try {
const pkiSyncs = await basePkiSyncQuery({ filter, db, tx });
return pkiSyncs.map(expandPkiSync);
} catch (error) {
throw new DatabaseError({ error, name: "Find - PKI Sync" });
}
};
const create = async (data: Parameters<(typeof pkiSyncOrm)["create"]>[0]) => {
const pkiSync = (await pkiSyncOrm.transaction(async (tx) => {
const sync = await pkiSyncOrm.create(data, tx);
return basePkiSyncQuery({ filter: { id: sync.id }, db, tx }).first();
}))!;
return expandPkiSync(pkiSync);
};
const updateById = async (syncId: string, data: Parameters<(typeof pkiSyncOrm)["updateById"]>[1]) => {
const pkiSync = (await pkiSyncOrm.transaction(async (tx) => {
const sync = await pkiSyncOrm.updateById(syncId, data, tx);
return basePkiSyncQuery({ filter: { id: sync.id }, db, tx }).first();
}))!;
return expandPkiSync(pkiSync);
};
return {
...pkiSyncOrm,
findByProjectId,
findBySubscriberId,
findByIdAndProjectId,
findByNameAndProjectId,
findById,
findOne,
find,
create,
updateById
};
};
@@ -0,0 +1,22 @@
export enum PkiSync {
AzureKeyVault = "azure-key-vault"
}
export enum PkiSyncStatus {
Pending = "PENDING",
Running = "RUNNING",
Success = "SUCCESS",
Failed = "FAILED"
}
export enum PkiSyncImportBehavior {
ImportAllSecrets = "IMPORT_ALL_SECRETS",
PreferInfisicalSecrets = "PREFER_INFISICAL_SECRETS",
PreferExternalSecrets = "PREFER_EXTERNAL_SECRETS"
}
export enum PkiSyncAction {
SyncCertificates = "sync-certificates",
ImportCertificates = "import-certificates",
RemoveCertificates = "remove-certificates"
}
@@ -0,0 +1,25 @@
export class PkiSyncError extends Error {
public context?: Record<string, unknown>;
public cause?: Error;
public shouldRetry: boolean;
constructor({
message,
cause,
context,
shouldRetry = true
}: {
message: string;
cause?: Error;
context?: Record<string, unknown>;
shouldRetry?: boolean;
}) {
super(message);
this.name = "PkiSyncError";
this.cause = cause;
this.context = context;
this.shouldRetry = shouldRetry;
}
}
@@ -0,0 +1,121 @@
import { z, ZodSchema } from "zod";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { BadRequestError } from "@app/lib/errors";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { PkiSync } from "./pki-sync-enums";
import { TCertificateMap, TPkiSyncWithCredentials } from "./pki-sync-types";
const ENTERPRISE_PKI_SYNCS: PkiSync[] = [];
export const enterprisePkiSyncCheck = async (
licenseService: Pick<TLicenseServiceFactory, "getPlan">,
orgId: string,
pkiSyncDestination: PkiSync,
errorMessage?: string
) => {
const plan = await licenseService.getPlan(orgId);
if (!plan.enterpriseSecretSyncs && ENTERPRISE_PKI_SYNCS.includes(pkiSyncDestination)) {
throw new BadRequestError({
message: errorMessage || "Failed to create PKI sync due to plan restriction. Upgrade plan to create PKI sync."
});
}
};
export const listPkiSyncOptions = () => {
return Object.values(PkiSync);
};
export const matchesSchema = <T extends ZodSchema>(schema: T, data: unknown): data is z.infer<T> => {
return schema.safeParse(data).success;
};
export const parsePkiSyncErrorMessage = (error: unknown): string => {
if (error instanceof Error) {
return error.message;
}
if (typeof error === "string") {
return error;
}
return "An unknown error occurred during PKI sync operation";
};
export const PkiSyncFns = {
getCertificates: async (
pkiSync: TPkiSyncWithCredentials,
dependencies: {
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
}
): Promise<TCertificateMap> => {
switch (pkiSync.destination) {
case PkiSync.AzureKeyVault: {
const { azureKeyVaultPkiSyncFactory } = await import("./azure-key-vault/azure-key-vault-pki-sync-fns");
const azureKeyVaultPkiSync = azureKeyVaultPkiSyncFactory(dependencies);
// Type assertion needed due to destinationConfig type differences
return azureKeyVaultPkiSync.importCertificates(
pkiSync as unknown as import("./azure-key-vault/azure-key-vault-pki-sync-types").TAzureKeyVaultPkiSyncWithCredentials
);
}
default:
throw new Error(`Unsupported PKI sync destination: ${String(pkiSync.destination)}`);
}
},
syncCertificates: async (
pkiSync: TPkiSyncWithCredentials,
certificateMap: TCertificateMap,
dependencies: {
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
}
): Promise<{
uploaded: number;
removed?: number;
failedRemovals?: number;
skipped: number;
}> => {
switch (pkiSync.destination) {
case PkiSync.AzureKeyVault: {
const { azureKeyVaultPkiSyncFactory } = await import("./azure-key-vault/azure-key-vault-pki-sync-fns");
const azureKeyVaultPkiSync = azureKeyVaultPkiSyncFactory(dependencies);
// Type assertion needed due to destinationConfig type differences
return azureKeyVaultPkiSync.syncCertificates(
pkiSync as unknown as import("./azure-key-vault/azure-key-vault-pki-sync-types").TAzureKeyVaultPkiSyncWithCredentials,
certificateMap
);
}
default:
throw new Error(`Unsupported PKI sync destination: ${String(pkiSync.destination)}`);
}
},
removeCertificates: async (
pkiSync: TPkiSyncWithCredentials,
certificateNames: string[],
dependencies: {
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
}
): Promise<void> => {
switch (pkiSync.destination) {
case PkiSync.AzureKeyVault: {
const { azureKeyVaultPkiSyncFactory } = await import("./azure-key-vault/azure-key-vault-pki-sync-fns");
const azureKeyVaultPkiSync = azureKeyVaultPkiSyncFactory(dependencies);
// Type assertion needed due to destinationConfig type differences
await azureKeyVaultPkiSync.removeCertificates(
pkiSync as unknown as import("./azure-key-vault/azure-key-vault-pki-sync-types").TAzureKeyVaultPkiSyncWithCredentials,
certificateNames
);
break;
}
default:
throw new Error(`Unsupported PKI sync destination: ${String(pkiSync.destination)}`);
}
}
};
@@ -0,0 +1,11 @@
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { PkiSync } from "./pki-sync-enums";
export const PKI_SYNC_NAME_MAP: Record<PkiSync, string> = {
[PkiSync.AzureKeyVault]: "Azure Key Vault"
};
export const PKI_SYNC_CONNECTION_MAP: Record<PkiSync, AppConnection> = {
[PkiSync.AzureKeyVault]: AppConnection.AzureKeyVault
};
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,37 @@
import { z } from "zod";
import { PkiSync } from "./pki-sync-enums";
// Base PKI sync schema for API responses
export const PkiSyncSchema = z.object({
id: z.string(),
name: z.string(),
description: z.string().nullable().optional(),
destination: z.nativeEnum(PkiSync),
isAutoSyncEnabled: z.boolean(),
destinationConfig: z.record(z.unknown()),
syncOptions: z.record(z.unknown()),
projectId: z.string(),
subscriberId: z.string().nullable().optional(),
connectionId: z.string(),
createdAt: z.date(),
updatedAt: z.date(),
syncStatus: z.string().nullable().optional(),
lastSyncedAt: z.date().nullable().optional()
});
// Schema for PKI sync list items (includes app connection info)
export const PkiSyncListItemSchema = PkiSyncSchema.extend({
appConnectionName: z.string(),
appConnectionApp: z.string()
});
// Schema for PKI sync details (includes app connection info)
export const PkiSyncDetailsSchema = PkiSyncSchema.extend({
appConnectionName: z.string(),
appConnectionApp: z.string()
});
export type TPkiSyncSchema = z.infer<typeof PkiSyncSchema>;
export type TPkiSyncListItemSchema = z.infer<typeof PkiSyncListItemSchema>;
export type TPkiSyncDetailsSchema = z.infer<typeof PkiSyncDetailsSchema>;
@@ -0,0 +1,384 @@
import { ForbiddenError, subject } from "@casl/ability";
import { ActionProjectType } from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionPkiSyncActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
import { OrgServiceActor } from "@app/lib/types";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
import { TPkiSubscriberDALFactory } from "@app/services/pki-subscriber/pki-subscriber-dal";
import { TPkiSyncDALFactory } from "./pki-sync-dal";
import { PkiSync } from "./pki-sync-enums";
import { enterprisePkiSyncCheck, listPkiSyncOptions } from "./pki-sync-fns";
import { TPkiSyncQueueFactory } from "./pki-sync-queue";
import {
PkiSyncStatus,
TCreatePkiSyncDTO,
TDeletePkiSyncDTO,
TFindPkiSyncByIdDTO,
TFindPkiSyncByNameDTO,
TListPkiSyncsByProjectId,
TListPkiSyncsBySubscriberId,
TPkiSync,
TTriggerPkiSyncImportCertificatesByIdDTO,
TTriggerPkiSyncRemoveCertificatesByIdDTO,
TTriggerPkiSyncSyncCertificatesByIdDTO,
TUpdatePkiSyncDTO
} from "./pki-sync-types";
type TPkiSyncServiceFactoryDep = {
pkiSyncDAL: TPkiSyncDALFactory;
pkiSubscriberDAL: Pick<TPkiSubscriberDALFactory, "findById">;
appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
pkiSyncQueue: Pick<
TPkiSyncQueueFactory,
"queuePkiSyncSyncCertificatesById" | "queuePkiSyncImportCertificatesById" | "queuePkiSyncRemoveCertificatesById"
>;
};
export type TPkiSyncServiceFactory = ReturnType<typeof pkiSyncServiceFactory>;
export const pkiSyncServiceFactory = ({
pkiSyncDAL,
pkiSubscriberDAL,
appConnectionService,
permissionService,
licenseService,
pkiSyncQueue
}: TPkiSyncServiceFactoryDep) => {
const createPkiSync = async (
{
name,
description,
destination,
isAutoSyncEnabled = true,
destinationConfig,
syncOptions = {},
subscriberId,
connectionId,
projectId
}: Omit<TCreatePkiSyncDTO, "auditLogInfo">,
actor: OrgServiceActor
): Promise<TPkiSync> => {
await enterprisePkiSyncCheck(licenseService, actor.orgId, destination);
const { permission } = await permissionService.getProjectPermission({
actor: actor.type,
actorId: actor.id,
actorAuthMethod: actor.authMethod,
actorOrgId: actor.orgId,
actionProjectType: ActionProjectType.CertificateManager,
projectId
});
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionPkiSyncActions.Create,
subject(ProjectPermissionSub.PkiSyncs, { projectId })
);
if (subscriberId) {
const subscriber = await pkiSubscriberDAL.findById(subscriberId);
if (!subscriber || subscriber.projectId !== projectId) {
throw new NotFoundError({ message: "PKI subscriber not found" });
}
}
// Get the destination app type based on PKI sync destination
const destinationApp = destination === PkiSync.AzureKeyVault ? AppConnection.AzureKeyVault : destination;
// Validates permission to connect and app is valid for sync destination
await appConnectionService.connectAppConnectionById(destinationApp, connectionId, actor);
try {
const pkiSync = await pkiSyncDAL.create({
name,
description,
destination,
isAutoSyncEnabled,
destinationConfig,
syncOptions,
subscriberId,
connectionId,
projectId,
...(isAutoSyncEnabled && { syncStatus: PkiSyncStatus.Pending })
});
if (pkiSync.isAutoSyncEnabled) {
await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSync.id });
}
return pkiSync as TPkiSync;
} catch (err) {
if (err instanceof DatabaseError && (err.error as { code: string })?.code === "23505") {
throw new BadRequestError({
message: `A PKI Sync with the name "${name}" already exists for the project with ID "${projectId}"`
});
}
throw err;
}
};
const updatePkiSync = async (
{
id,
projectId,
name,
description,
isAutoSyncEnabled,
destinationConfig,
syncOptions,
subscriberId,
connectionId
}: Omit<TUpdatePkiSyncDTO, "auditLogInfo">,
actor: OrgServiceActor
): Promise<TPkiSync> => {
const { permission } = await permissionService.getProjectPermission({
actor: actor.type,
actorId: actor.id,
actorAuthMethod: actor.authMethod,
actorOrgId: actor.orgId,
actionProjectType: ActionProjectType.CertificateManager,
projectId
});
const pkiSync = await pkiSyncDAL.findByIdAndProjectId(id, projectId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionPkiSyncActions.Edit,
subject(ProjectPermissionSub.PkiSyncs, {
projectId,
subscriberId: pkiSync.subscriberId
})
);
if (name && name !== pkiSync.name) {
const existingPkiSync = await pkiSyncDAL.findByNameAndProjectId(name, projectId);
if (existingPkiSync) {
throw new BadRequestError({ message: "PKI sync with this name already exists" });
}
}
if (subscriberId) {
const subscriber = await pkiSubscriberDAL.findById(subscriberId);
if (!subscriber || subscriber.projectId !== projectId) {
throw new NotFoundError({ message: "PKI subscriber not found" });
}
}
if (connectionId && connectionId !== pkiSync.connectionId) {
const destinationApp =
pkiSync.destination === PkiSync.AzureKeyVault
? AppConnection.AzureKeyVault
: (pkiSync.destination as AppConnection);
await appConnectionService.connectAppConnectionById(destinationApp, connectionId, actor);
}
const updatedPkiSync = await pkiSyncDAL.updateById(id, {
name,
description,
isAutoSyncEnabled,
destinationConfig,
syncOptions,
subscriberId,
connectionId
});
return updatedPkiSync as TPkiSync;
};
const deletePkiSync = async (
{ id, projectId }: Omit<TDeletePkiSyncDTO, "auditLogInfo">,
actor: OrgServiceActor
): Promise<TPkiSync> => {
const { permission } = await permissionService.getProjectPermission({
actor: actor.type,
actorId: actor.id,
actorAuthMethod: actor.authMethod,
actorOrgId: actor.orgId,
actionProjectType: ActionProjectType.CertificateManager,
projectId
});
const pkiSync = await pkiSyncDAL.findByIdAndProjectId(id, projectId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionPkiSyncActions.Delete,
subject(ProjectPermissionSub.PkiSyncs, {
projectId,
subscriberId: pkiSync.subscriberId
})
);
const deletedPkiSync = await pkiSyncDAL.deleteById(id);
return deletedPkiSync as TPkiSync;
};
const listPkiSyncsByProjectId = async ({ projectId }: TListPkiSyncsByProjectId, actor: OrgServiceActor) => {
const { permission } = await permissionService.getProjectPermission({
actor: actor.type,
actorId: actor.id,
actorAuthMethod: actor.authMethod,
actorOrgId: actor.orgId,
actionProjectType: ActionProjectType.CertificateManager,
projectId
});
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionPkiSyncActions.Read,
subject(ProjectPermissionSub.PkiSyncs, { projectId })
);
const pkiSyncs = await pkiSyncDAL.findByProjectId(projectId);
return pkiSyncs;
};
const listPkiSyncsBySubscriberId = async ({ subscriberId }: TListPkiSyncsBySubscriberId) => {
const pkiSyncs = await pkiSyncDAL.findBySubscriberId(subscriberId);
return pkiSyncs;
};
const findPkiSyncById = async ({ id, projectId }: TFindPkiSyncByIdDTO, actor: OrgServiceActor) => {
const { permission } = await permissionService.getProjectPermission({
actor: actor.type,
actorId: actor.id,
actorAuthMethod: actor.authMethod,
actorOrgId: actor.orgId,
actionProjectType: ActionProjectType.CertificateManager,
projectId
});
const pkiSync = await pkiSyncDAL.findByIdAndProjectId(id, projectId);
if (!pkiSync)
throw new NotFoundError({
message: `Could not find PKI Sync with ID "${id}"`
});
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionPkiSyncActions.Read,
subject(ProjectPermissionSub.PkiSyncs, {
projectId,
subscriberId: pkiSync.subscriberId
})
);
return pkiSync;
};
const findPkiSyncByName = async ({ name, projectId }: TFindPkiSyncByNameDTO) => {
const pkiSync = await pkiSyncDAL.findByNameAndProjectId(name, projectId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
return pkiSync;
};
const triggerPkiSyncSyncCertificatesById = async (
{ id, projectId }: Omit<TTriggerPkiSyncSyncCertificatesByIdDTO, "auditLogInfo">,
actor: OrgServiceActor
) => {
const { permission } = await permissionService.getProjectPermission({
actor: actor.type,
actorId: actor.id,
actorAuthMethod: actor.authMethod,
actorOrgId: actor.orgId,
actionProjectType: ActionProjectType.CertificateManager,
projectId
});
const pkiSync = await pkiSyncDAL.findByIdAndProjectId(id, projectId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionPkiSyncActions.SyncCertificates,
subject(ProjectPermissionSub.PkiSyncs, {
projectId,
subscriberId: pkiSync.subscriberId
})
);
await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: id });
return { message: "PKI sync job added to queue successfully" };
};
const triggerPkiSyncImportCertificatesById = async (
{ id, projectId }: Omit<TTriggerPkiSyncImportCertificatesByIdDTO, "auditLogInfo">,
actor: OrgServiceActor
) => {
const { permission } = await permissionService.getProjectPermission({
actor: actor.type,
actorId: actor.id,
actorAuthMethod: actor.authMethod,
actorOrgId: actor.orgId,
actionProjectType: ActionProjectType.CertificateManager,
projectId
});
const pkiSync = await pkiSyncDAL.findByIdAndProjectId(id, projectId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionPkiSyncActions.ImportCertificates,
subject(ProjectPermissionSub.PkiSyncs, {
projectId,
subscriberId: pkiSync.subscriberId
})
);
await pkiSyncQueue.queuePkiSyncImportCertificatesById({ syncId: id });
return { message: "PKI sync import job added to queue successfully" };
};
const triggerPkiSyncRemoveCertificatesById = async (
{ id, projectId }: Omit<TTriggerPkiSyncRemoveCertificatesByIdDTO, "auditLogInfo">,
actor: OrgServiceActor
) => {
const { permission } = await permissionService.getProjectPermission({
actor: actor.type,
actorId: actor.id,
actorAuthMethod: actor.authMethod,
actorOrgId: actor.orgId,
actionProjectType: ActionProjectType.CertificateManager,
projectId
});
const pkiSync = await pkiSyncDAL.findByIdAndProjectId(id, projectId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionPkiSyncActions.RemoveCertificates,
subject(ProjectPermissionSub.PkiSyncs, {
projectId,
subscriberId: pkiSync.subscriberId
})
);
await pkiSyncQueue.queuePkiSyncRemoveCertificatesById({ syncId: id });
return { message: "PKI sync remove job added to queue successfully" };
};
const getPkiSyncOptions = () => {
return listPkiSyncOptions();
};
return {
createPkiSync,
updatePkiSync,
deletePkiSync,
listPkiSyncsByProjectId,
listPkiSyncsBySubscriberId,
findPkiSyncById,
findPkiSyncByName,
triggerPkiSyncSyncCertificatesById,
triggerPkiSyncImportCertificatesById,
triggerPkiSyncRemoveCertificatesById,
getPkiSyncOptions
};
};
@@ -0,0 +1,183 @@
import { Job } from "bullmq";
import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types";
import { QueueJobs } from "@app/queue";
import { ResourceMetadataDTO } from "@app/services/resource-metadata/resource-metadata-schema";
import { TPkiSyncDALFactory } from "./pki-sync-dal";
import { PkiSync } from "./pki-sync-enums";
export type TPkiSync = {
id: string;
name: string;
description?: string;
destination: PkiSync;
isAutoSyncEnabled: boolean;
version: number;
destinationConfig: Record<string, unknown>;
syncOptions: Record<string, unknown>;
projectId: string;
subscriberId?: string;
connectionId: string;
createdAt: Date;
updatedAt: Date;
syncStatus?: string;
lastSyncJobId?: string;
lastSyncMessage?: string;
lastSyncedAt?: Date;
importStatus?: string;
lastImportJobId?: string;
lastImportMessage?: string;
lastImportedAt?: Date;
removeStatus?: string;
lastRemoveJobId?: string;
lastRemoveMessage?: string;
lastRemovedAt?: Date;
};
export type TPkiSyncListItem = TPkiSync & {
appConnectionName: string;
appConnectionApp: string;
};
export type TPkiSyncWithCredentials = TPkiSync & {
connection: {
id: string;
name: string;
app: string;
credentials: Record<string, unknown>;
orgId: string;
};
};
export type TCertificateMap = Record<string, { cert: string; privateKey: string }>;
export type TCreatePkiSyncDTO = {
name: string;
description?: string;
destination: PkiSync;
isAutoSyncEnabled?: boolean;
destinationConfig: Record<string, unknown>;
syncOptions?: Record<string, unknown>;
subscriberId?: string;
connectionId: string;
projectId: string;
auditLogInfo: AuditLogInfo;
resourceMetadata?: ResourceMetadataDTO;
};
export type TUpdatePkiSyncDTO = {
id: string;
projectId: string;
name?: string;
description?: string;
isAutoSyncEnabled?: boolean;
destinationConfig?: Record<string, unknown>;
syncOptions?: Record<string, unknown>;
subscriberId?: string;
connectionId?: string;
auditLogInfo: AuditLogInfo;
resourceMetadata?: ResourceMetadataDTO;
};
export type TDeletePkiSyncDTO = {
id: string;
projectId: string;
auditLogInfo: AuditLogInfo;
};
export type TListPkiSyncsByProjectId = {
projectId: string;
};
export type TListPkiSyncsBySubscriberId = {
subscriberId: string;
};
export type TFindPkiSyncByIdDTO = {
id: string;
projectId: string;
};
export type TFindPkiSyncByNameDTO = {
name: string;
projectId: string;
};
export type TTriggerPkiSyncSyncCertificatesByIdDTO = {
id: string;
projectId: string;
auditLogInfo: AuditLogInfo;
};
export type TTriggerPkiSyncImportCertificatesByIdDTO = {
id: string;
projectId: string;
auditLogInfo: AuditLogInfo;
};
export type TTriggerPkiSyncRemoveCertificatesByIdDTO = {
id: string;
projectId: string;
auditLogInfo: AuditLogInfo;
};
export enum PkiSyncStatus {
Pending = "pending",
Running = "running",
Succeeded = "succeeded",
Failed = "failed"
}
export enum PkiSyncAction {
SyncCertificates = "sync-certificates",
ImportCertificates = "import-certificates",
RemoveCertificates = "remove-certificates"
}
export type TPkiSyncRaw = NonNullable<Awaited<ReturnType<TPkiSyncDALFactory["findById"]>>>;
export type TQueuePkiSyncSyncCertificatesByIdDTO = {
syncId: string;
failedToAcquireLockCount?: number;
auditLogInfo?: AuditLogInfo;
};
export type TQueuePkiSyncImportCertificatesByIdDTO = {
syncId: string;
auditLogInfo?: AuditLogInfo;
};
export type TQueuePkiSyncRemoveCertificatesByIdDTO = {
syncId: string;
auditLogInfo?: AuditLogInfo;
deleteSyncOnComplete?: boolean;
};
export type TQueueSendPkiSyncActionFailedNotificationsDTO = {
pkiSync: TPkiSyncRaw;
auditLogInfo?: AuditLogInfo;
action: PkiSyncAction;
};
export type TPkiSyncSyncCertificatesDTO = Job<
TQueuePkiSyncSyncCertificatesByIdDTO,
void,
QueueJobs.PkiSyncSyncCertificates
>;
export type TPkiSyncImportCertificatesDTO = Job<
TQueuePkiSyncImportCertificatesByIdDTO,
void,
QueueJobs.PkiSyncImportCertificates
>;
export type TPkiSyncRemoveCertificatesDTO = Job<
TQueuePkiSyncRemoveCertificatesByIdDTO,
void,
QueueJobs.PkiSyncRemoveCertificates
>;
export type TSendPkiSyncFailedNotificationsJobDTO = Job<
TQueueSendPkiSyncActionFailedNotificationsDTO,
void,
QueueJobs.PkiSyncSendActionFailedNotifications
>;