Skip to content

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

Merge remote-tracking branch 'origin/main' into feat/pki-ENG-3666

Carlos Monastyrskibc04fc61138c
diff --cc backend/src/services/pki-sync/pki-sync-queue.ts
index c0b9381076,0000000000..3747393fc1
mode 100644,000000..100644
--- a/backend/src/services/pki-sync/pki-sync-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-queue.ts
@@@ -1,1033 -1,0 +1,1038 @@@
+/* eslint-disable no-await-in-loop */
+import opentelemetry from "@opentelemetry/api";
+import * as x509 from "@peculiar/x509";
+import { AxiosError } from "axios";
+import { Job } from "bullmq";
+
+import { ProjectMembershipRole } from "@app/db/schemas";
+import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
+import { getConfig } from "@app/lib/config/env";
+import { logger } from "@app/lib/logger";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
+
+import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";
+import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";
+import { TCertificateDALFactory } from "../certificate/certificate-dal";
+import { getCertificateCredentials } from "../certificate/certificate-fns";
+import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";
+import { CertStatus } from "../certificate/certificate-types";
+import { TPkiSyncDALFactory } from "./pki-sync-dal";
+import { PkiSyncAction } from "./pki-sync-enums";
+import { PkiSyncError } from "./pki-sync-errors";
+import { enterprisePkiSyncCheck, parsePkiSyncErrorMessage, PkiSyncFns } from "./pki-sync-fns";
+import {
+ PkiSyncStatus,
+ TCertificateMap,
+ TPkiSyncImportCertificatesDTO,
+ TPkiSyncRaw,
+ TPkiSyncRemoveCertificatesDTO,
+ TPkiSyncSyncCertificatesDTO,
+ TPkiSyncWithCredentials,
+ TQueuePkiSyncImportCertificatesByIdDTO,
+ TQueuePkiSyncRemoveCertificatesByIdDTO,
+ TQueuePkiSyncSyncCertificatesByIdDTO,
+ TQueueSendPkiSyncActionFailedNotificationsDTO,
+ TSendPkiSyncFailedNotificationsJobDTO
+} from "./pki-sync-types";
+
+export type TPkiSyncQueueFactory = ReturnType<typeof pkiSyncQueueFactory>;
+
+type TPkiSyncQueueFactoryDep = {
+ queueService: Pick<TQueueServiceFactory, "queue" | "start">;
+ kmsService: Pick<
+ TKmsServiceFactory,
+ "createCipherPairWithDataKey" | "decryptWithKmsKey" | "generateKmsKey" | "encryptWithKmsKey"
+ >;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;
+ keyStore: Pick<TKeyStoreFactory, "acquireLock" | "setItemWithExpiry" | "getItem">;
+ pkiSyncDAL: Pick<TPkiSyncDALFactory, "findById" | "find" | "updateById" | "deleteById" | "update">;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+ projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findAllProjectMembers">;
+ projectDAL: TProjectDALFactory;
+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ certificateDAL: Pick<
+ TCertificateDALFactory,
+ "findLatestActiveCertForSubscriber" | "findAllActiveCertsForSubscriber" | "create"
+ >;
+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne" | "create">;
+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;
+};
+
+type PkiSyncActionJob = Job<
+ TQueuePkiSyncSyncCertificatesByIdDTO | TQueuePkiSyncImportCertificatesByIdDTO | TQueuePkiSyncRemoveCertificatesByIdDTO
+>;
+
+const JITTER_MS = 10 * 1000;
+const REQUEUE_MS = 30 * 1000;
+const REQUEUE_LIMIT = 30;
+const CONNECTION_CONCURRENCY_LIMIT = 3;
+
+const getRequeueDelay = (failureCount?: number) => {
+ const jitter = Math.random() * JITTER_MS;
+ if (!failureCount) return jitter;
+ return REQUEUE_MS + jitter;
+};
+
+export const pkiSyncQueueFactory = ({
+ queueService,
+ kmsService,
+ appConnectionDAL,
+ keyStore,
+ pkiSyncDAL,
+ auditLogService,
+ projectMembershipDAL,
+ projectDAL,
+ licenseService,
+ certificateDAL,
+ certificateBodyDAL,
+ certificateSecretDAL
+}: TPkiSyncQueueFactoryDep) => {
+ const appCfg = getConfig();
+
+ const integrationMeter = opentelemetry.metrics.getMeter("PkiSyncs");
+ const syncCertificatesErrorHistogram = integrationMeter.createHistogram("pki_sync_sync_certificates_errors", {
+ description: "PKI Sync - sync certificates errors",
+ unit: "1"
+ });
+ const importCertificatesErrorHistogram = integrationMeter.createHistogram("pki_sync_import_certificates_errors", {
+ description: "PKI Sync - import certificates errors",
+ unit: "1"
+ });
+ const removeCertificatesErrorHistogram = integrationMeter.createHistogram("pki_sync_remove_certificates_errors", {
+ description: "PKI Sync - remove certificates errors",
+ unit: "1"
+ });
+
+ const $isConnectionConcurrencyLimitReached = async (connectionId: string) => {
+ const concurrencyCount = await keyStore.getItem(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId));
+
+ if (!concurrencyCount) return false;
+
+ const count = Number.parseInt(concurrencyCount, 10);
+
+ if (Number.isNaN(count)) return false;
+
+ return count >= CONNECTION_CONCURRENCY_LIMIT;
+ };
+
+ const $incrementConnectionConcurrencyCount = async (connectionId: string) => {
+ const concurrencyCount = await keyStore.getItem(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId));
+
+ const currentCount = Number.parseInt(concurrencyCount || "0", 10);
+
+ const incrementedCount = Number.isNaN(currentCount) ? 1 : currentCount + 1;
+
+ await keyStore.setItemWithExpiry(
+ KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId),
+ (REQUEUE_MS * REQUEUE_LIMIT) / 1000, // in seconds
+ incrementedCount
+ );
+ };
+
+ const $decrementConnectionConcurrencyCount = async (connectionId: string) => {
+ const concurrencyCount = await keyStore.getItem(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId));
+
+ const currentCount = Number.parseInt(concurrencyCount || "0", 10);
+
+ const decrementedCount = Math.max(0, Number.isNaN(currentCount) ? 0 : currentCount - 1);
+
+ await keyStore.setItemWithExpiry(
+ KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId),
+ (REQUEUE_MS * REQUEUE_LIMIT) / 1000, // in seconds
+ decrementedCount
+ );
+ };
+
+ const $createCertificatesInSubscriber = async (
+ pkiSync: TPkiSyncWithCredentials,
+ certificatesToCreate: Array<{
+ name: string;
+ certificate: string;
+ privateKey?: string;
+ }>
+ ) => {
+ const { projectId, subscriberId } = pkiSync;
+
+ if (!subscriberId) {
+ throw new Error("PKI Sync subscriber ID is required for certificate creation");
+ }
+
+ logger.info(`Creating ${certificatesToCreate.length} certificates in PKI subscriber ${subscriberId}`);
+
+ for (const certData of certificatesToCreate) {
+ try {
+ // Validate certificate data
+ if (!certData.certificate || certData.certificate.trim() === "") {
+ logger.error(`Skipping certificate ${certData.name}: empty certificate data`);
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
+ // Parse certificate to extract metadata
+ const cert = new x509.X509Certificate(certData.certificate);
+ const { serialNumber } = cert;
+ const { notBefore } = cert;
+ const { notAfter } = cert;
+ const commonName =
+ cert.subject
+ .split(",")
+ .find((part) => part.trim().startsWith("CN="))
+ ?.split("=")[1]
+ ?.trim() || certData.name;
+
+ // Get KMS key for encryption
+ const kmsKeyId = await getProjectKmsCertificateKeyId({ projectId, projectDAL, kmsService });
+ const kmsEncryptor = await kmsService.encryptWithKmsKey({
+ kmsId: kmsKeyId
+ });
+
+ // Create certificate record
+ const createdCert = await certificateDAL.create({
+ pkiSubscriberId: subscriberId,
+ status: CertStatus.ACTIVE,
+ serialNumber,
+ notBefore,
+ notAfter,
+ commonName,
+ friendlyName: certData.name,
+ projectId
+ });
+
+ // Create certificate body record with encrypted certificate
+ const { cipherTextBlob: encryptedCertificate } = await kmsEncryptor({
+ plainText: Buffer.from(certData.certificate)
+ });
+
+ await certificateBodyDAL.create({
+ certId: createdCert.id,
+ encryptedCertificate
+ });
+
+ // Create certificate secret record with encrypted private key (if available)
+ if (certData.privateKey) {
+ const { cipherTextBlob: encryptedPrivateKey } = await kmsEncryptor({
+ plainText: Buffer.from(certData.privateKey)
+ });
+
+ await certificateSecretDAL.create({
+ certId: createdCert.id,
+ encryptedPrivateKey
+ });
+ }
+
+ logger.info(`Successfully created certificate ${certData.name} with ID ${createdCert.id}`);
+ } catch (error) {
+ logger.error(`Failed to create certificate ${certData.name}: ${String(error)}`);
+ // Continue with other certificates even if one fails
+ }
+ }
+ };
+
+ const $getInfisicalCertificates = async (
+ pkiSync: TPkiSyncRaw | TPkiSyncWithCredentials
+ ): Promise<TCertificateMap> => {
+ const { projectId, subscriberId } = pkiSync;
+
+ if (!subscriberId) {
+ throw new PkiSyncError({
+ message: "Invalid PKI Sync source configuration: subscriber no longer exists. Please update source subscriber.",
+ shouldRetry: false
+ });
+ }
+
+ const certificateMap: TCertificateMap = {};
+
+ try {
+ // Get all active certificates for the subscriber (not just the latest)
+ const certificates = await certificateDAL.findAllActiveCertsForSubscriber({
+ subscriberId
+ });
+
+ logger.info(
+ { subscriberId, certificateCount: certificates.length },
+ "Found active certificates for PKI sync subscriber"
+ );
+
+ for (const certificate of certificates) {
+ try {
+ // Only sync certificates issued by Infisical (not imported ones)
+ // Imported certificates don't have caId and certificateTemplateId
+ if (!certificate.caId) {
+ logger.debug(
+ { certificateId: certificate.id, subscriberId },
+ "Skipping imported certificate - not syncing to destination"
+ );
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
+ // Check if certificate is expired
+ const now = new Date();
+ if (certificate.notAfter < now) {
+ logger.debug(
+ { certificateId: certificate.id, subscriberId, expiredAt: certificate.notAfter },
+ "Skipping expired certificate"
+ );
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
+ // Get the certificate body and decrypt the certificate data
+ const certBody = await certificateBodyDAL.findOne({ certId: certificate.id });
+
+ if (certBody) {
+ const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
+ projectId: certificate.projectId,
+ projectDAL,
+ kmsService
+ });
+
+ const kmsDecryptor = await kmsService.decryptWithKmsKey({
+ kmsId: certificateManagerKeyId
+ });
+
+ const decryptedCert = await kmsDecryptor({
+ cipherTextBlob: certBody.encryptedCertificate
+ });
+
+ const certObj = new x509.X509Certificate(decryptedCert);
+ const certificatePem = certObj.toString("pem");
+
+ // Get private key using getCertificateCredentials - handle cases where private key doesn't exist
+ let certPrivateKey: string | undefined;
+ try {
+ const credentials = await getCertificateCredentials({
+ certId: certificate.id,
+ projectId: certificate.projectId,
+ certificateSecretDAL,
+ projectDAL,
+ kmsService
+ });
+ certPrivateKey = credentials.certPrivateKey;
+ } catch (credError) {
+ logger.warn(
+ { certificateId: certificate.id, subscriberId, error: credError },
+ "Certificate private key not found - certificate may be imported or key was not stored"
+ );
+ // Continue without private key - some providers may only need the certificate
+ certPrivateKey = undefined;
+ }
+
+ // Use Infisical-prefixed ID for clear identification in destination
+ // Azure Key Vault doesn't allow underscores, so use hyphens and remove UUID hyphens
+ const certificateName = `Infisical-${certificate.id.replace(/-/g, "")}`;
+
+ certificateMap[certificateName] = {
+ cert: certificatePem,
+ privateKey: certPrivateKey || ""
+ };
+
+ logger.info(
+ { certificateId: certificate.id, certificateName, subscriberId },
+ "Successfully prepared certificate for PKI sync"
+ );
+ } else {
+ logger.warn({ certificateId: certificate.id, subscriberId }, "Certificate body not found for certificate");
+ }
+ } catch (error) {
+ logger.error(
+ { error, subscriberId, certificateId: certificate.id },
+ "Failed to decrypt certificate for PKI sync"
+ );
+ // Continue with other certificates
+ }
+ }
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to fetch certificate for subscriber [subscriberId=${subscriberId}] [projectId=${projectId}]`
+ );
+ throw new PkiSyncError({
+ message: `Failed to fetch certificate for PKI subscriber: ${error instanceof Error ? error.message : String(error)}`,
+ shouldRetry: true
+ });
+ }
+
+ return certificateMap;
+ };
+
+ const queuePkiSyncSyncCertificatesById = async (payload: TQueuePkiSyncSyncCertificatesByIdDTO) =>
+ queueService.queue(QueueName.PkiSync, QueueJobs.PkiSyncSyncCertificates, payload, {
+ delay: getRequeueDelay(payload.failedToAcquireLockCount), // this is for delaying re-queued jobs if sync is locked
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 3000
+ },
+ removeOnComplete: true,
+ removeOnFail: true
+ });
+
+ const queuePkiSyncImportCertificatesById = async (payload: TQueuePkiSyncImportCertificatesByIdDTO) =>
+ queueService.queue(QueueName.PkiSync, QueueJobs.PkiSyncImportCertificates, payload, {
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 3000
+ },
+ removeOnComplete: true,
+ removeOnFail: true
+ });
+
+ const queuePkiSyncRemoveCertificatesById = async (payload: TQueuePkiSyncRemoveCertificatesByIdDTO) =>
+ queueService.queue(QueueName.PkiSync, QueueJobs.PkiSyncRemoveCertificates, payload, {
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 3000
+ },
+ removeOnComplete: true,
+ removeOnFail: true
+ });
+
+ const $queueSendPkiSyncFailedNotifications = async (payload: TQueueSendPkiSyncActionFailedNotificationsDTO) => {
+ if (!appCfg.isSmtpConfigured) return;
+
+ await queueService.queue(QueueName.PkiSync, QueueJobs.PkiSyncSendActionFailedNotifications, payload, {
+ jobId: `pki-sync-${payload.pkiSync.id}-failed-notifications`,
+ attempts: 5,
+ delay: 1000 * 60,
+ backoff: {
+ type: "exponential",
+ delay: 3000
+ },
+ removeOnFail: true,
+ removeOnComplete: true
+ });
+ };
+
+ const $importCertificates = async (pkiSync: TPkiSyncWithCredentials): Promise<TCertificateMap> => {
+ const {
+ projectId,
+ destination,
+ connection: { orgId }
+ } = pkiSync;
+
+ await enterprisePkiSyncCheck(
+ licenseService,
+ orgId,
+ destination,
+ "Failed to import certificates due to plan restriction. Upgrade plan to access enterprise PKI syncs."
+ );
+
+ if (!projectId) {
+ throw new Error("Invalid PKI Sync source configuration: project no longer exists.");
+ }
+
+ const importedCertificates = await PkiSyncFns.getCertificates(pkiSync, {
+ appConnectionDAL,
+ kmsService
+ });
+
+ if (!Object.keys(importedCertificates).length) return {};
+
+ const importedCertificateMap: TCertificateMap = {};
+
+ const certificateMap = await $getInfisicalCertificates(pkiSync);
+
+ // Compare existing certificates with imported ones and determine which need to be created/updated
+ const certificatesToCreate: Array<{
+ name: string;
+ certificate: string;
+ privateKey?: string;
+ }> = [];
+
+ Object.entries(importedCertificates).forEach(([name, certificateData]) => {
+ const { cert: certificate, privateKey } = certificateData;
+
+ if (!Object.prototype.hasOwnProperty.call(certificateMap, name)) {
+ // Certificate doesn't exist in Infisical, create it
+ certificatesToCreate.push({
+ name,
+ certificate,
+ privateKey
+ });
+ importedCertificateMap[name] = certificateData;
+ } else {
+ // Certificate exists - could compare and update if needed
+ // For now, we'll skip updating existing certificates to avoid conflicts
+ importedCertificateMap[name] = certificateData;
+ }
+ });
+
+ // Create new certificates in Infisical
+ if (certificatesToCreate.length > 0) {
+ logger.info(`PKI Sync Import: Creating ${certificatesToCreate.length} new certificates`);
+ await $createCertificatesInSubscriber(pkiSync, certificatesToCreate);
+ }
+
+ return importedCertificateMap;
+ };
+
+ const $handleSyncCertificatesJob = async (job: TPkiSyncSyncCertificatesDTO, pkiSync: TPkiSyncRaw) => {
+ const {
+ data: { syncId, auditLogInfo }
+ } = job;
+
+ await enterprisePkiSyncCheck(
+ licenseService,
+ pkiSync.connection.orgId,
+ pkiSync.destination,
+ "Failed to sync certificates due to plan restriction. Upgrade plan to access enterprise PKI syncs."
+ );
+
+ await pkiSyncDAL.updateById(syncId, {
+ syncStatus: PkiSyncStatus.Running
+ });
+
+ logger.info(
+ `PkiSync Sync [syncId=${pkiSync.id}] [destination=${pkiSync.destination}] [projectId=${pkiSync.projectId}] [subscriberId=${pkiSync.subscriberId}] [connectionId=${pkiSync.connectionId}]`
+ );
+
+ let isSynced = false;
+ let syncMessage: string | null = null;
+ let isFinalAttempt = job.attemptsStarted === job.opts.attempts;
+
+ try {
+ const {
- connection: { orgId, encryptedCredentials }
++ connection: { orgId, encryptedCredentials },
++ projectId
+ } = pkiSync;
+
+ const credentials = await decryptAppConnectionCredentials({
+ orgId,
+ encryptedCredentials,
- kmsService
++ kmsService,
++ projectId
+ });
+
+ const pkiSyncWithCredentials = {
+ ...pkiSync,
+ connection: {
+ ...pkiSync.connection,
+ credentials
+ }
+ } as TPkiSyncWithCredentials;
+
+ const certificateMap = await $getInfisicalCertificates(pkiSync);
+
+ const syncResult = await PkiSyncFns.syncCertificates(pkiSyncWithCredentials, certificateMap, {
+ appConnectionDAL,
+ kmsService
+ });
+
+ logger.info(
+ {
+ syncId: pkiSync.id,
+ uploaded: syncResult.uploaded || 0,
+ removed: syncResult.removed || 0,
+ failedRemovals: syncResult.failedRemovals || 0,
+ skipped: syncResult.skipped || 0
+ },
+ "PKI sync operation completed with certificate cleanup"
+ );
+
+ isSynced = true;
+ } catch (err) {
+ logger.error(
+ err,
+ `PkiSync Sync Error [syncId=${pkiSync.id}] [destination=${pkiSync.destination}] [projectId=${pkiSync.projectId}] [subscriberId=${pkiSync.subscriberId}] [connectionId=${pkiSync.connectionId}]`
+ );
+
+ if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
+ syncCertificatesErrorHistogram.record(1, {
+ version: 1,
+ destination: pkiSync.destination,
+ syncId: pkiSync.id,
+ projectId: pkiSync.projectId,
+ type: err instanceof AxiosError ? "AxiosError" : err?.constructor?.name || "UnknownError",
+ status: err instanceof AxiosError ? err.response?.status : undefined,
+ name: err instanceof Error ? err.name : undefined
+ });
+ }
+
+ syncMessage = parsePkiSyncErrorMessage(err);
+
+ if (err instanceof PkiSyncError && !err.shouldRetry) {
+ isFinalAttempt = true;
+ } else {
+ // re-throw so job fails
+ throw err;
+ }
+ } finally {
+ const ranAt = new Date();
+ const syncStatus = isSynced ? PkiSyncStatus.Succeeded : PkiSyncStatus.Failed;
+
+ await auditLogService.createAuditLog({
+ projectId: pkiSync.projectId,
+ ...(auditLogInfo ?? {
+ actor: {
+ type: ActorType.PLATFORM,
+ metadata: {}
+ }
+ }),
+ event: {
+ type: EventType.PKI_SYNC_SYNC_CERTIFICATES,
+ metadata: {
+ syncId: pkiSync.id,
+ syncMessage,
+ jobId: job.id!,
+ jobRanAt: ranAt
+ }
+ }
+ });
+
+ if (isSynced || isFinalAttempt) {
+ const updatedPkiSync = await pkiSyncDAL.updateById(pkiSync.id, {
+ syncStatus,
+ lastSyncJobId: job.id,
+ lastSyncMessage: syncMessage,
+ lastSyncedAt: isSynced ? ranAt : undefined
+ });
+
+ if (!isSynced) {
+ await $queueSendPkiSyncFailedNotifications({
+ pkiSync: updatedPkiSync,
+ action: PkiSyncAction.SyncCertificates,
+ auditLogInfo
+ });
+ }
+ }
+ }
+
+ logger.info("PkiSync Sync Job with ID %s Completed", job.id);
+ };
+
+ const $handleImportCertificatesJob = async (job: TPkiSyncImportCertificatesDTO, pkiSync: TPkiSyncRaw) => {
+ const {
+ data: { syncId, auditLogInfo }
+ } = job;
+
+ await pkiSyncDAL.updateById(syncId, {
+ importStatus: PkiSyncStatus.Running
+ });
+
+ logger.info(
+ `PkiSync Import [syncId=${pkiSync.id}] [destination=${pkiSync.destination}] [projectId=${pkiSync.projectId}] [subscriberId=${pkiSync.subscriberId}] [connectionId=${pkiSync.connectionId}]`
+ );
+
+ let isSuccess = false;
+ let importMessage: string | null = null;
+ let isFinalAttempt = job.attemptsStarted === job.opts.attempts;
+
+ try {
+ const {
- connection: { orgId, encryptedCredentials }
++ connection: { orgId, encryptedCredentials },
++ projectId
+ } = pkiSync;
+
+ const credentials = await decryptAppConnectionCredentials({
+ orgId,
+ encryptedCredentials,
- kmsService
++ kmsService,
++ projectId
+ });
+
+ await $importCertificates({
+ ...pkiSync,
+ connection: {
+ ...pkiSync.connection,
+ credentials
+ }
+ } as TPkiSyncWithCredentials);
+
+ isSuccess = true;
+ } catch (err) {
+ logger.error(
+ err,
+ `PkiSync Import Error [syncId=${pkiSync.id}] [destination=${pkiSync.destination}] [projectId=${pkiSync.projectId}] [subscriberId=${pkiSync.subscriberId}] [connectionId=${pkiSync.connectionId}]`
+ );
+
+ if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
+ importCertificatesErrorHistogram.record(1, {
+ version: 1,
+ destination: pkiSync.destination,
+ syncId: pkiSync.id,
+ projectId: pkiSync.projectId,
+ type: err instanceof AxiosError ? "AxiosError" : err?.constructor?.name || "UnknownError",
+ status: err instanceof AxiosError ? err.response?.status : undefined,
+ name: err instanceof Error ? err.name : undefined
+ });
+ }
+
+ importMessage = parsePkiSyncErrorMessage(err);
+
+ if (err instanceof PkiSyncError && !err.shouldRetry) {
+ isFinalAttempt = true;
+ } else {
+ // re-throw so job fails
+ throw err;
+ }
+ } finally {
+ const ranAt = new Date();
+ const importStatus = isSuccess ? PkiSyncStatus.Succeeded : PkiSyncStatus.Failed;
+
+ await auditLogService.createAuditLog({
+ projectId: pkiSync.projectId,
+ ...(auditLogInfo ?? {
+ actor: {
+ type: ActorType.PLATFORM,
+ metadata: {}
+ }
+ }),
+ event: {
+ type: EventType.PKI_SYNC_IMPORT_CERTIFICATES,
+ metadata: {
+ syncId: pkiSync.id,
+ importMessage,
+ jobId: job.id!,
+ jobRanAt: ranAt
+ }
+ }
+ });
+
+ if (isSuccess || isFinalAttempt) {
+ const updatedPkiSync = await pkiSyncDAL.updateById(pkiSync.id, {
+ importStatus,
+ lastImportJobId: job.id,
+ lastImportMessage: importMessage,
+ lastImportedAt: isSuccess ? ranAt : undefined
+ });
+
+ if (!isSuccess) {
+ await $queueSendPkiSyncFailedNotifications({
+ pkiSync: updatedPkiSync,
+ action: PkiSyncAction.ImportCertificates,
+ auditLogInfo
+ });
+ }
+ }
+ }
+
+ logger.info("PkiSync Import Job with ID %s Completed", job.id);
+ };
+
+ const $handleRemoveCertificatesJob = async (job: TPkiSyncRemoveCertificatesDTO, pkiSync: TPkiSyncRaw) => {
+ const {
+ data: { syncId, auditLogInfo, deleteSyncOnComplete }
+ } = job;
+
+ await enterprisePkiSyncCheck(
+ licenseService,
+ pkiSync.connection.orgId,
+ pkiSync.destination,
+ "Failed to remove certificates due to plan restriction. Upgrade plan to access enterprise PKI syncs."
+ );
+
+ await pkiSyncDAL.updateById(syncId, {
+ removeStatus: PkiSyncStatus.Running
+ });
+
+ logger.info(
+ `PkiSync Remove [syncId=${pkiSync.id}] [destination=${pkiSync.destination}] [projectId=${pkiSync.projectId}] [subscriberId=${pkiSync.subscriberId}] [connectionId=${pkiSync.connectionId}]`
+ );
+
+ let isSuccess = false;
+ let removeMessage: string | null = null;
+ let isFinalAttempt = job.attemptsStarted === job.opts.attempts;
+
+ try {
+ const {
+ connection: { orgId, encryptedCredentials }
+ } = pkiSync;
+
+ const credentials = await decryptAppConnectionCredentials({
+ orgId,
+ encryptedCredentials,
- kmsService
++ kmsService,
++ projectId: pkiSync.projectId
+ });
+
+ const certificateMap = await $getInfisicalCertificates(pkiSync);
+
+ await PkiSyncFns.removeCertificates(
+ {
+ ...pkiSync,
+ connection: {
+ ...pkiSync.connection,
+ credentials
+ }
+ } as TPkiSyncWithCredentials,
+ Object.keys(certificateMap),
+ {
+ appConnectionDAL,
+ kmsService
+ }
+ );
+
+ isSuccess = true;
+ } catch (err) {
+ logger.error(
+ err,
+ `PkiSync Remove Error [syncId=${pkiSync.id}] [destination=${pkiSync.destination}] [projectId=${pkiSync.projectId}] [subscriberId=${pkiSync.subscriberId}] [connectionId=${pkiSync.connectionId}]`
+ );
+
+ if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
+ removeCertificatesErrorHistogram.record(1, {
+ version: 1,
+ destination: pkiSync.destination,
+ syncId: pkiSync.id,
+ projectId: pkiSync.projectId,
+ type: err instanceof AxiosError ? "AxiosError" : err?.constructor?.name || "UnknownError",
+ status: err instanceof AxiosError ? err.response?.status : undefined,
+ name: err instanceof Error ? err.name : undefined
+ });
+ }
+
+ removeMessage = parsePkiSyncErrorMessage(err);
+
+ if (err instanceof PkiSyncError && !err.shouldRetry) {
+ isFinalAttempt = true;
+ } else {
+ // re-throw so job fails
+ throw err;
+ }
+ } finally {
+ const ranAt = new Date();
+ const removeStatus = isSuccess ? PkiSyncStatus.Succeeded : PkiSyncStatus.Failed;
+
+ await auditLogService.createAuditLog({
+ projectId: pkiSync.projectId,
+ ...(auditLogInfo ?? {
+ actor: {
+ type: ActorType.PLATFORM,
+ metadata: {}
+ }
+ }),
+ event: {
+ type: EventType.PKI_SYNC_REMOVE_CERTIFICATES,
+ metadata: {
+ syncId: pkiSync.id,
+ removeMessage,
+ jobId: job.id!,
+ jobRanAt: ranAt
+ }
+ }
+ });
+
+ if (isSuccess || isFinalAttempt) {
+ if (isSuccess && deleteSyncOnComplete) {
+ await pkiSyncDAL.deleteById(pkiSync.id);
+ } else {
+ const updatedPkiSync = await pkiSyncDAL.updateById(pkiSync.id, {
+ removeStatus,
+ lastRemoveJobId: job.id,
+ lastRemoveMessage: removeMessage,
+ lastRemovedAt: isSuccess ? ranAt : undefined
+ });
+
+ if (!isSuccess) {
+ await $queueSendPkiSyncFailedNotifications({
+ pkiSync: updatedPkiSync,
+ action: PkiSyncAction.RemoveCertificates,
+ auditLogInfo
+ });
+ }
+ }
+ }
+ }
+
+ logger.info("PkiSync Remove Job with ID %s Completed", job.id);
+ };
+
+ const $sendPkiSyncFailedNotifications = async (job: TSendPkiSyncFailedNotificationsJobDTO) => {
+ const {
+ data: { pkiSync, auditLogInfo, action }
+ } = job;
+
+ const { projectId, name, lastSyncMessage, lastRemoveMessage, lastImportMessage } = pkiSync;
+
+ const projectMembers = await projectMembershipDAL.findAllProjectMembers(projectId);
+ const project = await projectDAL.findById(projectId);
+
+ // Filter for project admins similar to secret sync
+ let projectAdmins = projectMembers.filter((member) =>
+ member.roles.some((role) => role.role === ProjectMembershipRole.Admin)
+ );
+
+ const triggeredByUserId = auditLogInfo?.actor?.type === ActorType.USER ? auditLogInfo.actor.metadata?.userId : null;
+
+ if (triggeredByUserId) {
+ // Don't send notification to the user who triggered the action
+ projectAdmins = projectAdmins.filter((member) => member.user.id !== triggeredByUserId);
+ }
+
+ // Get appropriate error message based on action type
+ let errorMessage: string | null = null;
+ if (action === PkiSyncAction.SyncCertificates) {
+ errorMessage = lastSyncMessage || null;
+ } else if (action === PkiSyncAction.ImportCertificates) {
+ errorMessage = lastImportMessage || null;
+ } else {
+ errorMessage = lastRemoveMessage || null;
+ }
+
+ // Log notification for now - actual email sending would require SMTP configuration
+ if (projectAdmins.length > 0) {
+ logger.info(
+ `PKI Sync ${action} failure notification would be sent to ${projectAdmins.length} admin(s) for sync "${name}" in project "${project.name}". Error: ${errorMessage}`
+ );
+ } else {
+ logger.info(
+ `PKI Sync ${action} failure occurred for sync "${name}" in project "${project.name}" but no admins to notify. Error: ${errorMessage}`
+ );
+ }
+ };
+
+ const $handleAcquireLockFailure = async (job: PkiSyncActionJob) => {
+ const { syncId, auditLogInfo } = job.data;
+
+ switch (job.name) {
+ case QueueJobs.PkiSyncSyncCertificates: {
+ const { failedToAcquireLockCount = 0, ...rest } = job.data as TQueuePkiSyncSyncCertificatesByIdDTO;
+
+ if (failedToAcquireLockCount < REQUEUE_LIMIT) {
+ await queuePkiSyncSyncCertificatesById({ ...rest, failedToAcquireLockCount: failedToAcquireLockCount + 1 });
+ return;
+ }
+
+ const pkiSync = await pkiSyncDAL.updateById(syncId, {
+ syncStatus: PkiSyncStatus.Failed,
+ lastSyncMessage:
+ "Failed to run job. This typically happens when a sync is already in progress. Please try again.",
+ lastSyncJobId: job.id
+ });
+
+ await $queueSendPkiSyncFailedNotifications({
+ pkiSync,
+ action: PkiSyncAction.SyncCertificates,
+ auditLogInfo
+ });
+
+ break;
+ }
+ case QueueJobs.PkiSyncImportCertificates: {
+ const pkiSync = await pkiSyncDAL.updateById(syncId, {
+ importStatus: PkiSyncStatus.Failed,
+ lastImportMessage:
+ "Failed to run job. This typically happens when a sync is already in progress. Please try again.",
+ lastImportJobId: job.id
+ });
+
+ await $queueSendPkiSyncFailedNotifications({
+ pkiSync,
+ action: PkiSyncAction.ImportCertificates,
+ auditLogInfo
+ });
+
+ break;
+ }
+ case QueueJobs.PkiSyncRemoveCertificates: {
+ const pkiSync = await pkiSyncDAL.updateById(syncId, {
+ removeStatus: PkiSyncStatus.Failed,
+ lastRemoveMessage:
+ "Failed to run job. This typically happens when a sync is already in progress. Please try again.",
+ lastRemoveJobId: job.id
+ });
+
+ await $queueSendPkiSyncFailedNotifications({
+ pkiSync,
+ action: PkiSyncAction.RemoveCertificates,
+ auditLogInfo
+ });
+
+ break;
+ }
+ default:
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
+ throw new Error(`Unhandled PKI Sync Job ${job.name}`);
+ }
+ };
+
+ queueService.start(QueueName.PkiSync, async (job) => {
+ if (job.name === QueueJobs.PkiSyncSendActionFailedNotifications) {
+ await $sendPkiSyncFailedNotifications(job as TSendPkiSyncFailedNotificationsJobDTO);
+ return;
+ }
+
+ const { syncId } = job.data as
+ | TQueuePkiSyncSyncCertificatesByIdDTO
+ | TQueuePkiSyncImportCertificatesByIdDTO
+ | TQueuePkiSyncRemoveCertificatesByIdDTO;
+
+ const pkiSync = await pkiSyncDAL.findById(syncId);
+
+ if (!pkiSync) throw new Error(`Cannot find PKI sync with ID ${syncId}`);
+
+ const { connectionId } = pkiSync;
+
+ if (job.name === QueueJobs.PkiSyncSyncCertificates) {
+ const isConcurrentLimitReached = await $isConnectionConcurrencyLimitReached(connectionId);
+
+ if (isConcurrentLimitReached) {
+ logger.info(
+ `PkiSync Concurrency limit reached [syncId=${syncId}] [job=${job.name}] [connectionId=${connectionId}]`
+ );
+
+ await $handleAcquireLockFailure(job as PkiSyncActionJob);
+
+ return;
+ }
+ }
+
+ let lock: Awaited<ReturnType<typeof keyStore.acquireLock>>;
+
+ try {
+ lock = await keyStore.acquireLock(
+ [KeyStorePrefixes.PkiSyncLock(syncId)],
+ // PKI syncs can take excessive amounts of time so we need to keep it locked
+ 5 * 60 * 1000
+ );
+ } catch (e) {
+ logger.info(`PkiSync Failed to acquire lock [syncId=${syncId}] [job=${job.name}]`);
+
+ await $handleAcquireLockFailure(job as PkiSyncActionJob);
+
+ return;
+ }
+
+ try {
+ switch (job.name) {
+ case QueueJobs.PkiSyncSyncCertificates: {
+ await $incrementConnectionConcurrencyCount(connectionId);
+ await $handleSyncCertificatesJob(job as TPkiSyncSyncCertificatesDTO, pkiSync);
+ break;
+ }
+ case QueueJobs.PkiSyncImportCertificates:
+ await $handleImportCertificatesJob(job as TPkiSyncImportCertificatesDTO, pkiSync);
+ break;
+ case QueueJobs.PkiSyncRemoveCertificates:
+ await $handleRemoveCertificatesJob(job as TPkiSyncRemoveCertificatesDTO, pkiSync);
+ break;
+ default:
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
+ throw new Error(`Unhandled PKI Sync Job ${job.name}`);
+ }
+ } finally {
+ if (job.name === QueueJobs.PkiSyncSyncCertificates) {
+ await $decrementConnectionConcurrencyCount(connectionId);
+ }
+
+ await lock.release();
+ }
+ });
+
+ return {
+ queuePkiSyncSyncCertificatesById,
+ queuePkiSyncImportCertificatesById,
+ queuePkiSyncRemoveCertificatesById
+ };
+};
diff --cc frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
index b12b2c6850,0000000000..b7cfe50189
mode 100644,000000..100644
--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
@@@ -1,253 -1,0 +1,253 @@@
+import { useState } from "react";
+import { Controller, FormProvider, useForm } from "react-hook-form";
+import { faInfoCircle } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { Tab } from "@headlessui/react";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { twMerge } from "tailwind-merge";
+
+import { createNotification } from "@app/components/notifications";
+import { Button, FormControl, Switch } from "@app/components/v2";
- import { useWorkspace } from "@app/context";
++import { useProject } from "@app/context";
+import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";
+import {
+ PkiSync,
+ TCreatePkiSyncDTO,
+ TPkiSync,
+ useCreatePkiSync,
+ usePkiSyncOption
+} from "@app/hooks/api/pkiSyncs";
+
+import { PkiSyncDestinationFields } from "./PkiSyncDestinationFields";
+import { PkiSyncDetailsFields } from "./PkiSyncDetailsFields";
+import { PkiSyncOptionsFields } from "./PkiSyncOptionsFields";
+import { PkiSyncReviewFields } from "./PkiSyncReviewFields";
+import { PkiSyncSourceFields } from "./PkiSyncSourceFields";
+import { PkiSyncFormSchema, TPkiSyncForm } from "./schemas";
+
+type Props = {
+ onComplete: (pkiSync: TPkiSync) => void;
+ destination: PkiSync;
+ onCancel: () => void;
+};
+
+const FORM_TABS: { name: string; key: string; fields: (keyof TPkiSyncForm)[] }[] = [
+ { name: "Source", key: "source", fields: ["subscriberId"] },
+ { name: "Destination", key: "destination", fields: ["connection", "destinationConfig"] },
+ { name: "Sync Options", key: "options", fields: ["syncOptions"] },
+ { name: "Details", key: "details", fields: ["name", "description"] },
+ { name: "Review", key: "review", fields: [] }
+];
+
+export const CreatePkiSyncForm = ({ destination, onComplete, onCancel }: Props) => {
+ const createPkiSync = useCreatePkiSync();
- const { currentWorkspace } = useWorkspace();
++ const { currentProject } = useProject();
+ const { name: destinationName } = PKI_SYNC_MAP[destination];
+
+ const [showConfirmation, setShowConfirmation] = useState(false);
+
+ const [selectedTabIndex, setSelectedTabIndex] = useState(0);
+
+ const { syncOption } = usePkiSyncOption(destination);
+
+ const formMethods = useForm<TPkiSyncForm>({
+ resolver: zodResolver(PkiSyncFormSchema),
+ defaultValues: {
+ destination,
+ isAutoSyncEnabled: true,
+ syncOptions: {
+ canImportCertificates: syncOption?.canImportCertificates ?? true,
+ canRemoveCertificates: syncOption?.canRemoveCertificates ?? true
+ }
+ } as Partial<TPkiSyncForm>,
+ reValidateMode: "onChange"
+ });
+
+ const onSubmit = async ({ connection, destinationConfig, ...formData }: TPkiSyncForm) => {
+ try {
+ const pkiSync = await createPkiSync.mutateAsync({
+ ...formData,
+ connectionId: connection.id,
- projectId: currentWorkspace.id,
++ projectId: currentProject.id,
+ destinationConfig: {
+ destination,
+ config: destinationConfig
+ } as unknown as TCreatePkiSyncDTO["destinationConfig"]
+ });
+
+ createNotification({
+ text: `Successfully added ${destinationName} Certificate Sync`,
+ type: "success"
+ });
+ onComplete(pkiSync);
+ } catch (err: Error | unknown) {
+ console.error(err);
+ setShowConfirmation(false);
+ createNotification({
+ title: `Failed to add ${destinationName} Certificate Sync`,
+ text: err instanceof Error ? err.message : "An unknown error occurred",
+ type: "error"
+ });
+ }
+ };
+
+ const handlePrev = () => {
+ if (selectedTabIndex === 0) {
+ onCancel();
+ return;
+ }
+
+ setSelectedTabIndex((prev) => prev - 1);
+ };
+
+ const { handleSubmit, trigger, control } = formMethods;
+
+ const isStepValid = async (index: number) => trigger(FORM_TABS[index].fields);
+
+ const isFinalStep = selectedTabIndex === FORM_TABS.length - 1;
+
+ const handleNext = async () => {
+ if (isFinalStep) {
+ setShowConfirmation(true);
+ return;
+ }
+
+ const isValid = await isStepValid(selectedTabIndex);
+
+ if (!isValid) return;
+
+ setSelectedTabIndex((prev) => prev + 1);
+ };
+
+ const isTabEnabled = async (index: number) => {
+ let isEnabled = true;
+ for (let i = index - 1; i >= 0; i -= 1) {
+ // eslint-disable-next-line no-await-in-loop
+ isEnabled = isEnabled && (await isStepValid(i));
+ }
+
+ return isEnabled;
+ };
+
+ if (showConfirmation)
+ return (
+ <>
+ <div className="flex flex-col rounded-sm border border-l-[2px] border-mineshaft-600 border-l-primary bg-mineshaft-700/80 px-4 py-3">
+ <div className="mb-1 flex items-center text-sm">
+ <FontAwesomeIcon icon={faInfoCircle} size="sm" className="mr-1.5 text-primary" />
+ Certificate Sync Behavior
+ </div>
+ <p className="mt-1 text-sm text-bunker-200">
+ Certificate Syncs are the source of truth for connected third-party services. Any
+ certificate, including associated data, not present or imported in Infisical before
+ syncing will be overwritten, and changes made directly in the connected service outside
+ of infisical may also be overwritten by future syncs.
+ </p>
+ </div>
+ <div className="mt-4 flex gap-4">
+ <Button
+ isDisabled={createPkiSync.isPending}
+ isLoading={createPkiSync.isPending}
+ onClick={handleSubmit(onSubmit)}
+ colorSchema="secondary"
+ >
+ I Understand
+ </Button>
+
+ <Button
+ isDisabled={createPkiSync.isPending}
+ variant="plain"
+ onClick={() => setShowConfirmation(false)}
+ colorSchema="secondary"
+ >
+ Cancel
+ </Button>
+ </div>
+ </>
+ );
+
+ return (
+ <form className={twMerge(isFinalStep && "max-h-[70vh] overflow-y-auto")}>
+ <FormProvider {...formMethods}>
+ <Tab.Group selectedIndex={selectedTabIndex} onChange={setSelectedTabIndex}>
+ <Tab.List className="-pb-1 mb-6 w-full border-b-2 border-mineshaft-600">
+ {FORM_TABS.map((tab, index) => (
+ <Tab
+ onClick={async (e) => {
+ e.preventDefault();
+ const isEnabled = await isTabEnabled(index);
+ setSelectedTabIndex((prev) => (isEnabled ? index : prev));
+ }}
+ className={({ selected }) =>
+ `w-30 -mb-[0.14rem] ${index > selectedTabIndex ? "opacity-30" : ""} px-4 py-2 text-sm font-medium outline-none disabled:opacity-60 ${
+ selected
+ ? "border-b-2 border-mineshaft-300 text-mineshaft-200"
+ : "text-bunker-300"
+ }`
+ }
+ key={tab.key}
+ >
+ {index + 1}. {tab.name}
+ </Tab>
+ ))}
+ </Tab.List>
+ <Tab.Panels>
+ <Tab.Panel>
+ <PkiSyncSourceFields />
+ </Tab.Panel>
+ <Tab.Panel>
+ <PkiSyncDestinationFields />
+ </Tab.Panel>
+ <Tab.Panel>
+ <PkiSyncOptionsFields />
+ <Controller
+ control={control}
+ name="isAutoSyncEnabled"
+ render={({ field: { value, onChange }, fieldState: { error } }) => {
+ return (
+ <FormControl
+ helperText={
+ value
+ ? "Certificates will automatically be synced when changes occur in the source subscriber."
+ : "Certificates will not automatically be synced when changes occur in the source subscriber. You can still trigger syncs manually."
+ }
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Switch
+ className="bg-mineshaft-400/80 shadow-inner data-[state=checked]:bg-green/80"
+ id="auto-sync-enabled"
+ thumbClassName="bg-mineshaft-800"
+ onCheckedChange={onChange}
+ isChecked={value}
+ >
+ <p className="w-[8.4rem]">Auto-Sync {value ? "Enabled" : "Disabled"}</p>
+ </Switch>
+ </FormControl>
+ );
+ }}
+ />
+ </Tab.Panel>
+ <Tab.Panel>
+ <PkiSyncDetailsFields />
+ </Tab.Panel>
+ <Tab.Panel>
+ <PkiSyncReviewFields />
+ </Tab.Panel>
+ </Tab.Panels>
+ </Tab.Group>
+ </FormProvider>
+
+ <div className="flex w-full flex-row-reverse justify-between gap-4 pt-4">
+ <Button onClick={handleNext} colorSchema="secondary">
+ {isFinalStep ? "Create Sync" : "Next"}
+ </Button>
+ {selectedTabIndex > 0 && (
+ <Button onClick={handlePrev} colorSchema="secondary">
+ Back
+ </Button>
+ )}
+ </div>
+ </form>
+ );
+};
diff --cc frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx
index ffcf6ca7da,0000000000..2b8c978d7d
mode 100644,000000..100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx
@@@ -1,86 -1,0 +1,90 @@@
+import { Controller, useFormContext } from "react-hook-form";
+import { faInfoCircle } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { Link } from "@tanstack/react-router";
+
+import { FilterableSelect, FormControl } from "@app/components/v2";
- import { OrgPermissionSubjects, useOrgPermission } from "@app/context";
++import { OrgPermissionSubjects, useOrgPermission, useProject } from "@app/context";
+import { OrgPermissionAppConnectionActions } from "@app/context/OrgPermissionContext/types";
+import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";
+import { PKI_SYNC_CONNECTION_MAP } from "@app/helpers/pkiSyncs";
+import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";
+
+import { TPkiSyncForm } from "./schemas";
+
+type Props = {
+ onChange?: VoidFunction;
+};
+
+export const PkiSyncConnectionField = ({ onChange: callback }: Props) => {
+ const { permission } = useOrgPermission();
+ const { control, watch } = useFormContext<TPkiSyncForm>();
++ const { currentProject } = useProject();
+
+ const destination = watch("destination");
+ const app = PKI_SYNC_CONNECTION_MAP[destination];
+
- const { data: availableConnections, isPending } = useListAvailableAppConnections(app);
++ const { data: availableConnections, isPending } = useListAvailableAppConnections(
++ app,
++ currentProject.id
++ );
+
+ const connectionName = APP_CONNECTION_MAP[app].name;
+
+ const canCreateConnection = permission.can(
+ OrgPermissionAppConnectionActions.Create,
+ OrgPermissionSubjects.AppConnections
+ );
+
+ const appName = APP_CONNECTION_MAP[PKI_SYNC_CONNECTION_MAP[destination]].name;
+
+ return (
+ <>
+ <p className="mb-4 text-sm text-bunker-300">
+ Specify the {appName} Connection to use to connect to {connectionName} and configure
+ destination parameters.
+ </p>
+ <Controller
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl
+ tooltipText="App Connections can be created from the Organization Settings page."
+ isError={Boolean(error)}
+ errorText={error?.message}
+ label={`${connectionName} Connection`}
+ >
+ <FilterableSelect
+ value={value}
+ onChange={(newValue) => {
+ onChange(newValue);
+ if (callback) callback();
+ }}
+ isLoading={isPending}
+ options={availableConnections}
+ placeholder="Select connection..."
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ />
+ </FormControl>
+ )}
+ control={control}
+ name="connection"
+ />
+ {availableConnections?.length === 0 && (
+ <p className="-mt-2.5 mb-2.5 text-xs text-yellow">
+ <FontAwesomeIcon className="mr-1" size="xs" icon={faInfoCircle} />
+ {canCreateConnection ? (
+ <>
+ You do not have access to any {appName} Connections. Create one from the{" "}
+ <Link to="/organization/app-connections" className="underline">
+ App Connections
+ </Link>{" "}
+ page.
+ </>
+ ) : (
+ `You do not have access to any ${appName} Connections. Contact an admin to create one.`
+ )}
+ </p>
+ )}
+ </>
+ );
+};
diff --cc frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
index ed938d4200,0000000000..f5481dd0ba
mode 100644,000000..100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
@@@ -1,100 -1,0 +1,100 @@@
+import { useFormContext } from "react-hook-form";
+
+import { Badge, GenericFieldLabel } from "@app/components/v2";
- import { useWorkspace } from "@app/context";
++import { useProject } from "@app/context";
+import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";
- import { useListWorkspacePkiSubscribers } from "@app/hooks/api/workspace";
++import { useListWorkspacePkiSubscribers } from "@app/hooks/api";
+
+import { TPkiSyncForm } from "./schemas";
+
+export const PkiSyncReviewFields = () => {
+ const { watch } = useFormContext<TPkiSyncForm>();
- const { currentWorkspace } = useWorkspace();
++ const { currentProject } = useProject();
+
- const { data: pkiSubscribers = [] } = useListWorkspacePkiSubscribers(currentWorkspace?.id || "");
++ const { data: pkiSubscribers = [] } = useListWorkspacePkiSubscribers(currentProject?.id || "");
+
+ const getSubscriberName = (subscriberId?: string) => {
+ const subscriber = pkiSubscribers.find((sub) => sub.id === subscriberId);
+ return subscriber?.name || "Unknown";
+ };
+
+ const {
+ name,
+ description,
+ connection,
+ subscriberId,
+ syncOptions,
+ destination,
+ destinationConfig,
+ isAutoSyncEnabled
+ } = watch();
+
+ const destinationName = PKI_SYNC_MAP[destination].name;
+
+ return (
+ <div className="mb-4 flex flex-col gap-6">
+ <div className="flex flex-col gap-3">
+ <div className="w-full border-b border-mineshaft-600">
+ <span className="text-sm text-mineshaft-300">Source</span>
+ </div>
+ <div className="flex flex-wrap gap-x-8 gap-y-2">
+ <GenericFieldLabel label="PKI Subscriber">
+ {getSubscriberName(subscriberId)}
+ </GenericFieldLabel>
+ </div>
+ </div>
+ <div className="flex flex-col gap-3">
+ <div className="w-full border-b border-mineshaft-600">
+ <span className="text-sm text-mineshaft-300">Destination</span>
+ </div>
+ <div className="flex flex-wrap gap-x-8 gap-y-2">
+ <GenericFieldLabel label="Connection">{connection?.name}</GenericFieldLabel>
+ <GenericFieldLabel label="Service">{destinationName}</GenericFieldLabel>
+ {destinationConfig && "vaultBaseUrl" in destinationConfig && (
+ <GenericFieldLabel label="Vault URL">
+ {destinationConfig.vaultBaseUrl}
+ </GenericFieldLabel>
+ )}
+ </div>
+ </div>
+ <div className="flex flex-col gap-3">
+ <div className="w-full border-b border-mineshaft-600">
+ <span className="text-sm text-mineshaft-300">Sync Options</span>
+ </div>
+ <div className="flex flex-wrap gap-x-8 gap-y-2">
+ <GenericFieldLabel label="Auto-Sync">
+ <Badge variant={isAutoSyncEnabled ? "success" : "danger"}>
+ {isAutoSyncEnabled ? "Enabled" : "Disabled"}
+ </Badge>
+ </GenericFieldLabel>
+ <GenericFieldLabel label="Upload Certificates">
+ <Badge variant="success">Always Enabled</Badge>
+ </GenericFieldLabel>
+ {syncOptions?.canImportCertificates !== undefined && (
+ <GenericFieldLabel label="Import Certificates">
+ <Badge variant={syncOptions.canImportCertificates ? "success" : "danger"}>
+ {syncOptions.canImportCertificates ? "Enabled" : "Disabled"}
+ </Badge>
+ </GenericFieldLabel>
+ )}
+ {syncOptions?.canRemoveCertificates !== undefined && (
+ <GenericFieldLabel label="Remove Certificates">
+ <Badge variant={syncOptions.canRemoveCertificates ? "success" : "danger"}>
+ {syncOptions.canRemoveCertificates ? "Enabled" : "Disabled"}
+ </Badge>
+ </GenericFieldLabel>
+ )}
+ </div>
+ </div>
+ <div className="flex flex-col gap-3">
+ <div className="w-full border-b border-mineshaft-600">
+ <span className="text-sm text-mineshaft-300">Details</span>
+ </div>
+ <div className="flex flex-wrap gap-x-8 gap-y-2">
+ <GenericFieldLabel label="Name">{name}</GenericFieldLabel>
+ <GenericFieldLabel label="Description">{description}</GenericFieldLabel>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --cc frontend/src/components/pki-syncs/forms/PkiSyncSourceFields.tsx
index 22c28e1053,0000000000..80f17f4e6c
mode 100644,000000..100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncSourceFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncSourceFields.tsx
@@@ -1,53 -1,0 +1,53 @@@
+import { Controller, useFormContext } from "react-hook-form";
+
+import { FilterableSelect, FormControl } from "@app/components/v2";
- import { useWorkspace } from "@app/context";
- import { useListWorkspacePkiSubscribers } from "@app/hooks/api/workspace";
++import { useProject } from "@app/context";
++import { useListWorkspacePkiSubscribers } from "@app/hooks/api";
+
+import { TPkiSyncForm } from "./schemas";
+
+export const PkiSyncSourceFields = () => {
+ const { control } = useFormContext<TPkiSyncForm>();
- const { currentWorkspace } = useWorkspace();
++ const { currentProject } = useProject();
+
+ const { data: pkiSubscribers = [], isLoading } = useListWorkspacePkiSubscribers(
- currentWorkspace?.id || ""
++ currentProject?.id || ""
+ );
+
+ return (
+ <>
+ <p className="mb-4 text-sm text-bunker-300">
+ Specify the PKI subscriber where you would like to sync certificates from.
+ </p>
+
+ <Controller
+ control={control}
+ name="subscriberId"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl label="PKI Subscriber" isError={Boolean(error)} errorText={error?.message}>
+ <FilterableSelect
+ value={pkiSubscribers.find((sub) => sub.id === value)}
+ onChange={(selectedSubscriber) => {
+ if (Array.isArray(selectedSubscriber)) return;
+ if (
+ selectedSubscriber &&
+ !Array.isArray(selectedSubscriber) &&
+ "id" in selectedSubscriber
+ ) {
+ onChange(selectedSubscriber.id);
+ } else {
+ onChange(undefined);
+ }
+ }}
+ options={pkiSubscribers}
+ isLoading={isLoading}
+ placeholder="Select PKI subscriber..."
+ getOptionLabel={(option) => option?.name || ""}
+ getOptionValue={(option) => option?.id || ""}
+ />
+ </FormControl>
+ )}
+ />
+ </>
+ );
+};
diff --cc frontend/src/context/ProjectPermissionContext/types.ts
index 23d27f1ad0,ad6b5bb0a6..306d928086
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@@ -183,9 -181,12 +191,13 @@@ export type IdentityManagementSubjectFi
identityId: string;
};
+ export type AppConnectionSubjectFields = {
+ connectionId: string;
+ };
+
export type ConditionalProjectPermissionSubject =
| ProjectPermissionSub.SecretSyncs
+ | ProjectPermissionSub.PkiSyncs
| ProjectPermissionSub.Secrets
| ProjectPermissionSub.DynamicSecrets
| ProjectPermissionSub.Identity
diff --cc frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx
index 1baa097cfb,ec47273309..5a17c7592a
--- a/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx
+++ b/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx
@@@ -6,8 -6,8 +6,9 @@@ import
faCog,
faFileLines,
faHome,
- faLink,
faMobile,
+ faPlug,
++ faPuzzlePiece,
faSitemap,
faStamp,
faUsers
@@@ -131,23 -131,23 +132,40 @@@ export const PkiManagerLayout = () =>
</MenuItem>
)}
</Link>
+ <Link
+ to="/projects/cert-management/$projectId/integrations"
+ params={{
- projectId: currentWorkspace.id
++ projectId: currentProject.id
+ }}
+ >
+ {({ isActive }) => (
+ <MenuItem isSelected={isActive}>
+ <div className="mx-1 flex gap-2">
+ <div className="w-6">
- <FontAwesomeIcon icon={faLink} />
++ <FontAwesomeIcon icon={faPuzzlePiece} />
+ </div>
+ Integrations
+ </div>
+ </MenuItem>
+ )}
+ </Link>
+ <Link
+ to="/projects/cert-management/$projectId/app-connections"
+ params={{
+ projectId: currentProject.id
+ }}
+ >
+ {({ isActive }) => (
+ <MenuItem isSelected={isActive}>
+ <div className="mx-1 flex gap-2">
+ <div className="w-6">
+ <FontAwesomeIcon icon={faPlug} />
+ </div>
+ App Connections
+ </div>
+ </MenuItem>
+ )}
+ </Link>
</MenuGroup>
<MenuGroup title="Others">
<Link
diff --cc frontend/src/pages/cert-manager/IntegrationsListPage/IntegrationsListPage.tsx
index 591ce951e5,0000000000..e52982ef01
mode 100644,000000..100644
--- a/frontend/src/pages/cert-manager/IntegrationsListPage/IntegrationsListPage.tsx
+++ b/frontend/src/pages/cert-manager/IntegrationsListPage/IntegrationsListPage.tsx
@@@ -1,69 -1,0 +1,69 @@@
+import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
+import { useNavigate, useSearch } from "@tanstack/react-router";
+
+import { ProjectPermissionCan } from "@app/components/permissions";
+import { PageHeader, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
+import { ROUTE_PATHS } from "@app/const/routes";
- import { ProjectPermissionSub, useWorkspace } from "@app/context";
++import { ProjectPermissionSub, useProject } from "@app/context";
+import { ProjectPermissionPkiSyncActions } from "@app/context/ProjectPermissionContext/types";
+import { IntegrationsListPageTabs } from "@app/types/integrations";
+
+import { PkiSyncsTab } from "./components";
+
+export const IntegrationsListPage = () => {
+ const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
++ const { currentProject } = useProject();
+ const { t } = useTranslation();
+
+ const { selectedTab } = useSearch({
+ from: ROUTE_PATHS.CertManager.IntegrationsListPage.id
+ });
+
+ const currentTab = selectedTab || IntegrationsListPageTabs.PkiSyncs;
+
+ const updateSelectedTab = (tab: string) => {
+ navigate({
+ to: ROUTE_PATHS.CertManager.IntegrationsListPage.path,
+ search: {
+ selectedTab: tab as IntegrationsListPageTabs
+ },
+ params: {
- projectId: currentWorkspace.id
++ projectId: currentProject?.id
+ }
+ });
+ };
+
+ return (
+ <>
+ <Helmet>
+ <title>{t("common.head-title", { title: t("integrations.title") })}</title>
+ <meta property="og:image" content="/images/message.png" />
+ <meta property="og:title" content="Manage your certificates in seconds" />
+ <meta name="og:description" content="Sync and manage PKI certificates across services" />
+ </Helmet>
+ <div className="container relative mx-auto max-w-7xl pb-12 text-white">
+ <div className="mb-8">
+ <PageHeader
+ title="Integrations"
+ description="Manage integrations with third-party certificate services."
+ />
+ <Tabs value={currentTab} onValueChange={updateSelectedTab}>
+ <TabList>
+ <Tab value={IntegrationsListPageTabs.PkiSyncs}>Certificate Syncs</Tab>
+ </TabList>
+ <TabPanel value={IntegrationsListPageTabs.PkiSyncs}>
+ <ProjectPermissionCan
+ renderGuardBanner
+ I={ProjectPermissionPkiSyncActions.Read}
+ a={ProjectPermissionSub.PkiSyncs}
+ >
+ <PkiSyncsTab />
+ </ProjectPermissionCan>
+ </TabPanel>
+ </Tabs>
+ </div>
+ </div>
+ </>
+ );
+};
diff --cc frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncsTab.tsx
index 72649fc9d7,0000000000..68c6e4bea6
mode 100644,000000..100644
--- a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncsTab.tsx
+++ b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncsTab.tsx
@@@ -1,110 -1,0 +1,110 @@@
+import { useCallback, useEffect, useMemo } from "react";
+import { faArrowUpRightFromSquare, faBookOpen, faPlus } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useNavigate, useSearch } from "@tanstack/react-router";
+
+import { ProjectPermissionCan } from "@app/components/permissions";
+import { CreatePkiSyncModal } from "@app/components/pki-syncs";
+import { Button, Spinner } from "@app/components/v2";
+import { ROUTE_PATHS } from "@app/const/routes";
- import { ProjectPermissionSub, useWorkspace } from "@app/context";
++import { ProjectPermissionSub, useProject } from "@app/context";
+import { ProjectPermissionPkiSyncActions } from "@app/context/ProjectPermissionContext/types";
+import { usePopUp } from "@app/hooks";
+import { useListPkiSyncs } from "@app/hooks/api/pkiSyncs";
+
+import { PkiSyncsTable } from "./PkiSyncTable";
+
+export const PkiSyncsTab = () => {
+ const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["addSync"] as const);
+
+ const { addSync, ...search } = useSearch({
+ from: ROUTE_PATHS.CertManager.IntegrationsListPage.id
+ });
+
+ const navigate = useNavigate();
+
- const { currentWorkspace } = useWorkspace();
++ const { currentProject } = useProject();
+
+ const memoizedSearch = useMemo(() => search, [search]);
+
+ const navigateToBase = useCallback(() => {
+ navigate({
+ to: ROUTE_PATHS.CertManager.IntegrationsListPage.path,
+ params: {
- projectId: currentWorkspace.id
++ projectId: currentProject?.id
+ },
+ search: memoizedSearch
+ });
- }, [navigate, currentWorkspace.id, memoizedSearch]);
++ }, [navigate, currentProject?.id, memoizedSearch]);
+
+ useEffect(() => {
+ if (!addSync) return;
+
+ handlePopUpOpen("addSync", addSync);
+ navigateToBase();
+ }, [addSync, handlePopUpOpen, navigateToBase]);
+
+ const { data: pkiSyncs = [], isPending: isPkiSyncsPending } = useListPkiSyncs(
- currentWorkspace.id
++ currentProject?.id || ""
+ );
+
+ if (isPkiSyncsPending)
+ return (
+ <div className="flex h-[60vh] flex-col items-center justify-center gap-2">
+ <Spinner />
+ </div>
+ );
+
+ return (
+ <>
+ <div className="w-full rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
+ <div className="mb-4 flex items-center justify-between">
+ <div>
+ <div className="flex items-start gap-1">
+ <p className="text-xl font-semibold text-mineshaft-100">Certificate Syncs</p>
+ <a
+ href="https://infisical.com/docs/integrations/pki-syncs/overview"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <div className="ml-1 mt-[0.32rem] inline-block rounded-md bg-yellow/20 px-1.5 text-sm text-yellow opacity-80 hover:opacity-100">
+ <FontAwesomeIcon icon={faBookOpen} className="mr-1.5" />
+ <span>Docs</span>
+ <FontAwesomeIcon
+ icon={faArrowUpRightFromSquare}
+ className="mb-[0.07rem] ml-1.5 text-[10px]"
+ />
+ </div>
+ </a>
+ </div>
+ <p className="text-sm text-bunker-300">
+ Use App Connections to sync certificates to third-party services.
+ </p>
+ </div>
+ <ProjectPermissionCan
+ I={ProjectPermissionPkiSyncActions.Create}
+ a={ProjectPermissionSub.PkiSyncs}
+ >
+ {(isAllowed) => (
+ <Button
+ colorSchema="secondary"
+ type="button"
+ leftIcon={<FontAwesomeIcon icon={faPlus} />}
+ onClick={() => handlePopUpOpen("addSync")}
+ isDisabled={!isAllowed}
+ >
+ Add Sync
+ </Button>
+ )}
+ </ProjectPermissionCan>
+ </div>
+ <PkiSyncsTable pkiSyncs={pkiSyncs} />
+ </div>
+ <CreatePkiSyncModal
+ selectSync={popUp.addSync.data}
+ isOpen={popUp.addSync.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("addSync", isOpen)}
+ />
+ </>
+ );
+};
diff --cc frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncAuditLogsSection.tsx
index 8f4675b385,0000000000..2ee55a2343
mode 100644,000000..100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncAuditLogsSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncAuditLogsSection.tsx
@@@ -1,78 -1,0 +1,78 @@@
+import { faFingerprint } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { Link } from "@tanstack/react-router";
+
- import { useSubscription, useWorkspace } from "@app/context";
++import { useProject, useSubscription } from "@app/context";
+import { EventType } from "@app/hooks/api/auditLogs/enums";
+import { TPkiSync } from "@app/hooks/api/pkiSyncs";
+import { LogsSection } from "@app/pages/organization/AuditLogsPage/components/LogsSection";
+
+const PKI_SYNC_EVENTS = [
+ EventType.PKI_SYNC_SYNC_CERTIFICATES,
+ EventType.PKI_SYNC_IMPORT_CERTIFICATES,
+ EventType.PKI_SYNC_REMOVE_CERTIFICATES
+];
+
+type Props = {
+ pkiSync: TPkiSync;
+};
+
+export const PkiSyncAuditLogsSection = ({ pkiSync }: Props) => {
+ const { subscription } = useSubscription();
- const { currentWorkspace } = useWorkspace();
++ const { currentProject } = useProject();
+
+ const auditLogsRetentionDays = subscription?.auditLogsRetentionDays ?? 30;
+
+ return (
+ <div className="flex max-h-full w-full flex-col gap-3 rounded-lg border border-mineshaft-600 bg-mineshaft-900 px-4 py-3">
+ <div className="flex items-center justify-between border-b border-mineshaft-400 pb-2">
+ <h3 className="font-semibold text-mineshaft-100">Sync Logs</h3>
+ {subscription.auditLogs && (
+ <p className="text-xs text-bunker-300">
+ Displaying audit logs from the last {Math.min(auditLogsRetentionDays, 60)} days
+ </p>
+ )}
+ </div>
+ {subscription.auditLogs ? (
+ <LogsSection
+ refetchInterval={4000}
+ showFilters={false}
- project={currentWorkspace}
++ project={currentProject}
+ presets={{
+ eventMetadata: { syncId: pkiSync.id },
+ startDate: new Date(
+ new Date().setDate(new Date().getDate() - Math.min(auditLogsRetentionDays, 60))
+ ),
+ eventType: PKI_SYNC_EVENTS
+ }}
+ />
+ ) : (
+ <div className="flex h-full items-center justify-center rounded-lg bg-mineshaft-800 text-sm text-mineshaft-200">
+ <div className="flex flex-col items-center gap-4 py-20">
+ <FontAwesomeIcon size="2x" icon={faFingerprint} />
+ <p>
+ Please{" "}
+ {subscription && subscription.slug !== null ? (
+ <Link to="/organization/billing" target="_blank" rel="noopener noreferrer">
+ <span className="cursor-pointer underline transition-all hover:text-white">
+ upgrade your subscription
+ </span>
+ </Link>
+ ) : (
+ <a
+ href="https://infisical.com/scheduledemo"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="cursor-pointer underline transition-all hover:text-white"
+ >
+ upgrade your subscription
+ </a>
+ )}{" "}
+ to view sync logs.
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
diff --cc frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index e42dbec6cd,89c1e5d860..9da7563559
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@@ -322,12 -320,12 +331,18 @@@ export const projectRoleFormSchema = z.
})
.array()
.default([]),
+ [ProjectPermissionSub.AppConnections]: AppConnectionPolicyActionSchema.extend({
+ inverted: z.boolean().optional(),
+ conditions: ConditionSchema
+ })
+ .array()
+ .default([]),
+ [ProjectPermissionSub.PkiSyncs]: PkiSyncPolicyActionSchema.extend({
+ inverted: z.boolean().optional(),
+ conditions: ConditionSchema
+ })
+ .array()
+ .default([]),
[ProjectPermissionSub.Commits]: CommitPolicyActionSchema.array().default([]),
[ProjectPermissionSub.Member]: MemberPolicyActionSchema.array().default([]),
@@@ -410,8 -408,8 +425,9 @@@ type TConditionalFields
| ProjectPermissionSub.SecretRotation
| ProjectPermissionSub.Identity
| ProjectPermissionSub.SecretSyncs
+ | ProjectPermissionSub.PkiSyncs
- | ProjectPermissionSub.SecretEvents;
+ | ProjectPermissionSub.SecretEvents
+ | ProjectPermissionSub.AppConnections;
export const isConditionalSubjects = (
subject: ProjectPermissionSub
@@@ -426,8 -424,8 +442,9 @@@
subject === ProjectPermissionSub.PkiSubscribers ||
subject === ProjectPermissionSub.CertificateTemplates ||
subject === ProjectPermissionSub.SecretSyncs ||
+ subject === ProjectPermissionSub.PkiSyncs ||
- subject === ProjectPermissionSub.SecretEvents;
+ subject === ProjectPermissionSub.SecretEvents ||
+ subject === ProjectPermissionSub.AppConnections;
const convertCaslConditionToFormOperator = (caslConditions: TPermissionCondition) => {
const formConditions: z.infer<typeof ConditionSchema> = [];
@@@ -534,8 -532,8 +551,9 @@@ export const rolePermission2Form = (per
ProjectPermissionSub.SshCertificates,
ProjectPermissionSub.SshHostGroups,
ProjectPermissionSub.SecretSyncs,
+ ProjectPermissionSub.PkiSyncs,
- ProjectPermissionSub.SecretEvents
+ ProjectPermissionSub.SecretEvents,
+ ProjectPermissionSub.AppConnections
].includes(subject)
) {
// from above statement we are sure it won't be undefined
diff --cc frontend/src/pages/secret-manager/IntegrationsListPage/IntegrationsListPage.tsx
index 9d3e34df4e,26263f0adb..1b89edc6fb
--- a/frontend/src/pages/secret-manager/IntegrationsListPage/IntegrationsListPage.tsx
+++ b/frontend/src/pages/secret-manager/IntegrationsListPage/IntegrationsListPage.tsx
@@@ -28,11 -28,9 +28,11 @@@ export const IntegrationsListPage = ()
const updateSelectedTab = (tab: string) => {
navigate({
to: ROUTE_PATHS.SecretManager.IntegrationsListPage.path,
- search: (prev) => ({ ...prev, selectedTab: tab as IntegrationsListPageTabs }),
+ search: {
+ selectedTab: tab as IntegrationsListPageTabs
+ },
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}
});
};
diff --cc frontend/src/routeTree.gen.ts
index d0d23210eb,4d01ff47dc..5e6bd24179
--- a/frontend/src/routeTree.gen.ts
+++ b/frontend/src/routeTree.gen.ts
@@@ -3892,9 -3867,9 +3937,10 @@@ interface certManagerLayoutRouteChildre
certManagerCertificatesPageRouteRoute: typeof certManagerCertificatesPageRouteRoute
certManagerSettingsPageRouteRoute: typeof certManagerSettingsPageRouteRoute
projectAccessControlPageRouteCertManagerRoute: typeof projectAccessControlPageRouteCertManagerRoute
+ projectAppConnectionsPageRouteCertManagerRoute: typeof projectAppConnectionsPageRouteCertManagerRoute
projectAuditLogsPageRouteCertManagerRoute: typeof projectAuditLogsPageRouteCertManagerRoute
AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutCertificateTemplatesRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutCertificateTemplatesRouteWithChildren
+ AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutIntegrationsRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutIntegrationsRouteWithChildren
AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutSubscribersRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutSubscribersRouteWithChildren
certManagerCertAuthDetailsByIDPageRouteRoute: typeof certManagerCertAuthDetailsByIDPageRouteRoute
projectGroupDetailsByIDPageRouteCertManagerRoute: typeof projectGroupDetailsByIDPageRouteCertManagerRoute
@@@ -4762,9 -4743,9 +4816,10 @@@ export interface FileRoutesByFullPath
'/projects/ssh/$projectId/overview': typeof sshSshHostsPageRouteRoute
'/projects/ssh/$projectId/settings': typeof sshSettingsPageRouteRoute
'/projects/cert-management/$projectId/access-management': typeof projectAccessControlPageRouteCertManagerRoute
+ '/projects/cert-management/$projectId/app-connections': typeof projectAppConnectionsPageRouteCertManagerRoute
'/projects/cert-management/$projectId/audit-logs': typeof projectAuditLogsPageRouteCertManagerRoute
'/projects/cert-management/$projectId/certificate-templates': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutCertificateTemplatesRouteWithChildren
+ '/projects/cert-management/$projectId/integrations': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutIntegrationsRouteWithChildren
'/projects/cert-management/$projectId/subscribers': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutSubscribersRouteWithChildren
'/projects/kms/$projectId/access-management': typeof projectAccessControlPageRouteKmsRoute
'/projects/kms/$projectId/audit-logs': typeof projectAuditLogsPageRouteKmsRoute
@@@ -5206,9 -5188,9 +5266,10 @@@ export interface FileRoutesById
'/_authenticate/_inject-org-details/_org-layout/projects/ssh/$projectId/_ssh-layout/overview': typeof sshSshHostsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/projects/ssh/$projectId/_ssh-layout/settings': typeof sshSettingsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/access-management': typeof projectAccessControlPageRouteCertManagerRoute
+ '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/app-connections': typeof projectAppConnectionsPageRouteCertManagerRoute
'/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/audit-logs': typeof projectAuditLogsPageRouteCertManagerRoute
'/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/certificate-templates': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutCertificateTemplatesRouteWithChildren
+ '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/integrations': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutIntegrationsRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/subscribers': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutSubscribersRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/projects/kms/$projectId/_kms-layout/access-management': typeof projectAccessControlPageRouteKmsRoute
'/_authenticate/_inject-org-details/_org-layout/projects/kms/$projectId/_kms-layout/audit-logs': typeof projectAuditLogsPageRouteKmsRoute
@@@ -5432,9 -5414,9 +5495,10 @@@ export interface FileRouteTypes
| '/projects/ssh/$projectId/overview'
| '/projects/ssh/$projectId/settings'
| '/projects/cert-management/$projectId/access-management'
+ | '/projects/cert-management/$projectId/app-connections'
| '/projects/cert-management/$projectId/audit-logs'
| '/projects/cert-management/$projectId/certificate-templates'
+ | '/projects/cert-management/$projectId/integrations'
| '/projects/cert-management/$projectId/subscribers'
| '/projects/kms/$projectId/access-management'
| '/projects/kms/$projectId/audit-logs'
@@@ -5873,9 -5856,9 +5942,10 @@@
| '/_authenticate/_inject-org-details/_org-layout/projects/ssh/$projectId/_ssh-layout/overview'
| '/_authenticate/_inject-org-details/_org-layout/projects/ssh/$projectId/_ssh-layout/settings'
| '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/access-management'
+ | '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/app-connections'
| '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/audit-logs'
| '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/certificate-templates'
+ | '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/integrations'
| '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/subscribers'
| '/_authenticate/_inject-org-details/_org-layout/projects/kms/$projectId/_kms-layout/access-management'
| '/_authenticate/_inject-org-details/_org-layout/projects/kms/$projectId/_kms-layout/audit-logs'
@@@ -6477,9 -6460,9 +6549,10 @@@ export const routeTree = rootRout
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/certificates",
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/settings",
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/access-management",
+ "/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/app-connections",
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/audit-logs",
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/certificate-templates",
+ "/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/integrations",
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/subscribers",
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/ca/$caName",
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/groups/$groupId",