diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts index 49310044b..da1d93bf7 100644 --- a/backend/src/@types/fastify.d.ts +++ b/backend/src/@types/fastify.d.ts @@ -52,6 +52,8 @@ import { TIntegrationAuthServiceFactory } from "@app/services/integration-auth/i import { TOrgRoleServiceFactory } from "@app/services/org/org-role-service"; import { TOrgServiceFactory } from "@app/services/org/org-service"; import { TOrgAdminServiceFactory } from "@app/services/org-admin/org-admin-service"; +import { TPkiAlertServiceFactory } from "@app/services/pki-alert/pki-alert-service"; +import { TPkiCollectionServiceFactory } from "@app/services/pki-collection/pki-collection-service"; import { TProjectServiceFactory } from "@app/services/project/project-service"; import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service"; import { TProjectEnvServiceFactory } from "@app/services/project-env/project-env-service"; @@ -116,6 +118,7 @@ declare module "fastify" { group: TGroupServiceFactory; groupProject: TGroupProjectServiceFactory; apiKey: TApiKeyServiceFactory; + pkiAlert: TPkiAlertServiceFactory; project: TProjectServiceFactory; projectMembership: TProjectMembershipServiceFactory; projectEnv: TProjectEnvServiceFactory; @@ -155,6 +158,7 @@ declare module "fastify" { certificate: TCertificateServiceFactory; certificateAuthority: TCertificateAuthorityServiceFactory; certificateAuthorityCrl: TCertificateAuthorityCrlServiceFactory; + pkiCollection: TPkiCollectionServiceFactory; secretScanning: TSecretScanningServiceFactory; license: TLicenseServiceFactory; trustedIp: TTrustedIpServiceFactory; diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts index 5b2f1f2c8..0dc781092 100644 --- a/backend/src/@types/knex.d.ts +++ b/backend/src/@types/knex.d.ts @@ -161,6 +161,15 @@ import { TOrgRoles, TOrgRolesInsert, TOrgRolesUpdate, + TPkiAlerts, + TPkiAlertsInsert, + TPkiAlertsUpdate, + TPkiCollectionItems, + TPkiCollectionItemsInsert, + TPkiCollectionItemsUpdate, + TPkiCollections, + TPkiCollectionsInsert, + TPkiCollectionsUpdate, TProjectBots, TProjectBotsInsert, TProjectBotsUpdate, @@ -365,6 +374,17 @@ declare module "knex/types/tables" { TCertificateSecretsInsert, TCertificateSecretsUpdate >; + [TableName.PkiAlert]: KnexOriginal.CompositeTableType; + [TableName.PkiCollection]: KnexOriginal.CompositeTableType< + TPkiCollections, + TPkiCollectionsInsert, + TPkiCollectionsUpdate + >; + [TableName.PkiCollectionItem]: KnexOriginal.CompositeTableType< + TPkiCollectionItems, + TPkiCollectionItemsInsert, + TPkiCollectionItemsUpdate + >; [TableName.UserGroupMembership]: KnexOriginal.CompositeTableType< TUserGroupMembership, TUserGroupMembershipInsert, diff --git a/backend/src/db/migrations/20240818024923_cert-alerting.ts b/backend/src/db/migrations/20240818024923_cert-alerting.ts new file mode 100644 index 000000000..f60ce8c02 --- /dev/null +++ b/backend/src/db/migrations/20240818024923_cert-alerting.ts @@ -0,0 +1,62 @@ +import { Knex } from "knex"; + +import { TableName } from "../schemas"; +import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils"; + +export async function up(knex: Knex): Promise { + if (!(await knex.schema.hasTable(TableName.PkiCollection))) { + await knex.schema.createTable(TableName.PkiCollection, (t) => { + t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid()); + t.timestamps(true, true, true); + t.string("projectId").notNullable(); + t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE"); + t.string("name").notNullable(); + t.string("description").notNullable(); + }); + } + + await createOnUpdateTrigger(knex, TableName.PkiCollection); + + if (!(await knex.schema.hasTable(TableName.PkiCollectionItem))) { + await knex.schema.createTable(TableName.PkiCollectionItem, (t) => { + t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid()); + t.timestamps(true, true, true); + t.uuid("pkiCollectionId").notNullable(); + t.foreign("pkiCollectionId").references("id").inTable(TableName.PkiCollection).onDelete("CASCADE"); + t.uuid("caId").nullable(); + t.foreign("caId").references("id").inTable(TableName.CertificateAuthority).onDelete("CASCADE"); + t.uuid("certId").nullable(); + t.foreign("certId").references("id").inTable(TableName.Certificate).onDelete("CASCADE"); + }); + } + + await createOnUpdateTrigger(knex, TableName.PkiCollectionItem); + + if (!(await knex.schema.hasTable(TableName.PkiAlert))) { + await knex.schema.createTable(TableName.PkiAlert, (t) => { + t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid()); + t.timestamps(true, true, true); + t.string("projectId").notNullable(); + t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE"); + t.uuid("pkiCollectionId").notNullable(); + t.foreign("pkiCollectionId").references("id").inTable(TableName.PkiCollection).onDelete("CASCADE"); + t.string("name").notNullable(); + t.integer("alertBeforeDays").notNullable(); + t.string("recipientEmails").notNullable(); + t.unique(["name", "projectId"]); + }); + } + + await createOnUpdateTrigger(knex, TableName.PkiAlert); +} + +export async function down(knex: Knex): Promise { + await knex.schema.dropTableIfExists(TableName.PkiAlert); + await dropOnUpdateTrigger(knex, TableName.PkiAlert); + + await knex.schema.dropTableIfExists(TableName.PkiCollectionItem); + await dropOnUpdateTrigger(knex, TableName.PkiCollectionItem); + + await knex.schema.dropTableIfExists(TableName.PkiCollection); + await dropOnUpdateTrigger(knex, TableName.PkiCollection); +} diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts index 61031f910..03146f204 100644 --- a/backend/src/db/schemas/index.ts +++ b/backend/src/db/schemas/index.ts @@ -52,6 +52,9 @@ export * from "./org-bots"; export * from "./org-memberships"; export * from "./org-roles"; export * from "./organizations"; +export * from "./pki-alerts"; +export * from "./pki-collection-items"; +export * from "./pki-collections"; export * from "./project-bots"; export * from "./project-environments"; export * from "./project-keys"; diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts index 2e91608e3..ebbead70c 100644 --- a/backend/src/db/schemas/models.ts +++ b/backend/src/db/schemas/models.ts @@ -9,6 +9,9 @@ export enum TableName { Certificate = "certificates", CertificateBody = "certificate_bodies", CertificateSecret = "certificate_secrets", + PkiAlert = "pki_alerts", + PkiCollection = "pki_collections", + PkiCollectionItem = "pki_collection_items", Groups = "groups", GroupProjectMembership = "group_project_memberships", GroupProjectMembershipRole = "group_project_membership_roles", diff --git a/backend/src/db/schemas/pki-alerts.ts b/backend/src/db/schemas/pki-alerts.ts new file mode 100644 index 000000000..7bc9d2d7c --- /dev/null +++ b/backend/src/db/schemas/pki-alerts.ts @@ -0,0 +1,23 @@ +// Code generated by automation script, DO NOT EDIT. +// Automated by pulling database and generating zod schema +// To update. Just run npm run generate:schema +// Written by akhilmhdh. + +import { z } from "zod"; + +import { TImmutableDBKeys } from "./models"; + +export const PkiAlertsSchema = z.object({ + id: z.string().uuid(), + createdAt: z.date(), + updatedAt: z.date(), + projectId: z.string(), + pkiCollectionId: z.string().uuid(), + name: z.string(), + alertBeforeDays: z.number(), + recipientEmails: z.string() +}); + +export type TPkiAlerts = z.infer; +export type TPkiAlertsInsert = Omit, TImmutableDBKeys>; +export type TPkiAlertsUpdate = Partial, TImmutableDBKeys>>; diff --git a/backend/src/db/schemas/pki-collection-items.ts b/backend/src/db/schemas/pki-collection-items.ts new file mode 100644 index 000000000..f04f5a1ee --- /dev/null +++ b/backend/src/db/schemas/pki-collection-items.ts @@ -0,0 +1,21 @@ +// Code generated by automation script, DO NOT EDIT. +// Automated by pulling database and generating zod schema +// To update. Just run npm run generate:schema +// Written by akhilmhdh. + +import { z } from "zod"; + +import { TImmutableDBKeys } from "./models"; + +export const PkiCollectionItemsSchema = z.object({ + id: z.string().uuid(), + createdAt: z.date(), + updatedAt: z.date(), + pkiCollectionId: z.string().uuid(), + caId: z.string().uuid().nullable().optional(), + certId: z.string().uuid().nullable().optional() +}); + +export type TPkiCollectionItems = z.infer; +export type TPkiCollectionItemsInsert = Omit, TImmutableDBKeys>; +export type TPkiCollectionItemsUpdate = Partial, TImmutableDBKeys>>; diff --git a/backend/src/db/schemas/pki-collections.ts b/backend/src/db/schemas/pki-collections.ts new file mode 100644 index 000000000..0f9a5675f --- /dev/null +++ b/backend/src/db/schemas/pki-collections.ts @@ -0,0 +1,21 @@ +// Code generated by automation script, DO NOT EDIT. +// Automated by pulling database and generating zod schema +// To update. Just run npm run generate:schema +// Written by akhilmhdh. + +import { z } from "zod"; + +import { TImmutableDBKeys } from "./models"; + +export const PkiCollectionsSchema = z.object({ + id: z.string().uuid(), + createdAt: z.date(), + updatedAt: z.date(), + projectId: z.string(), + name: z.string(), + description: z.string() +}); + +export type TPkiCollections = z.infer; +export type TPkiCollectionsInsert = Omit, TImmutableDBKeys>; +export type TPkiCollectionsUpdate = Partial, TImmutableDBKeys>>; diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts index d5eb9ef43..ff4689ebc 100644 --- a/backend/src/ee/services/audit-log/audit-log-types.ts +++ b/backend/src/ee/services/audit-log/audit-log-types.ts @@ -2,6 +2,7 @@ import { TProjectPermission } from "@app/lib/types"; import { ActorType } from "@app/services/auth/auth-type"; import { CaStatus } from "@app/services/certificate-authority/certificate-authority-types"; import { TIdentityTrustedIp } from "@app/services/identity/identity-types"; +import { PkiItemType } from "@app/services/pki-collection/pki-collection-types"; export type TListProjectAuditLogDTO = { auditLogActor?: string; @@ -143,6 +144,17 @@ export enum EventType { DELETE_CERT = "delete-cert", REVOKE_CERT = "revoke-cert", GET_CERT_BODY = "get-cert-body", + CREATE_PKI_ALERT = "create-pki-alert", + GET_PKI_ALERT = "get-pki-alert", + UPDATE_PKI_ALERT = "update-pki-alert", + DELETE_PKI_ALERT = "delete-pki-alert", + CREATE_PKI_COLLECTION = "create-pki-collection", + GET_PKI_COLLECTION = "get-pki-collection", + UPDATE_PKI_COLLECTION = "update-pki-collection", + DELETE_PKI_COLLECTION = "delete-pki-collection", + GET_PKI_COLLECTION_ITEMS = "get-pki-collection-items", + ADD_PKI_COLLECTION_ITEM = "add-pki-collection-item", + DELETE_PKI_COLLECTION_ITEM = "delete-pki-collection-item", CREATE_KMS = "create-kms", UPDATE_KMS = "update-kms", DELETE_KMS = "delete-kms", @@ -1209,6 +1221,95 @@ interface GetCertBody { }; } +interface CreatePkiAlert { + type: EventType.CREATE_PKI_ALERT; + metadata: { + pkiAlertId: string; + pkiCollectionId: string; + name: string; + alertBeforeDays: number; + recipientEmails: string; + }; +} +interface GetPkiAlert { + type: EventType.GET_PKI_ALERT; + metadata: { + pkiAlertId: string; + }; +} + +interface UpdatePkiAlert { + type: EventType.UPDATE_PKI_ALERT; + metadata: { + pkiAlertId: string; + pkiCollectionId?: string; + name?: string; + alertBeforeDays?: number; + recipientEmails?: string; + }; +} +interface DeletePkiAlert { + type: EventType.DELETE_PKI_ALERT; + metadata: { + pkiAlertId: string; + }; +} + +interface CreatePkiCollection { + type: EventType.CREATE_PKI_COLLECTION; + metadata: { + pkiCollectionId: string; + name: string; + }; +} + +interface GetPkiCollection { + type: EventType.GET_PKI_COLLECTION; + metadata: { + pkiCollectionId: string; + }; +} + +interface UpdatePkiCollection { + type: EventType.UPDATE_PKI_COLLECTION; + metadata: { + pkiCollectionId: string; + name?: string; + }; +} + +interface DeletePkiCollection { + type: EventType.DELETE_PKI_COLLECTION; + metadata: { + pkiCollectionId: string; + }; +} + +interface GetPkiCollectionItems { + type: EventType.GET_PKI_COLLECTION_ITEMS; + metadata: { + pkiCollectionId: string; + }; +} + +interface AddPkiCollectionItem { + type: EventType.ADD_PKI_COLLECTION_ITEM; + metadata: { + pkiCollectionItemId: string; + pkiCollectionId: string; + type: PkiItemType; + itemId: string; + }; +} + +interface DeletePkiCollectionItem { + type: EventType.DELETE_PKI_COLLECTION_ITEM; + metadata: { + pkiCollectionItemId: string; + pkiCollectionId: string; + }; +} + interface CreateKmsEvent { type: EventType.CREATE_KMS; metadata: { @@ -1380,6 +1481,17 @@ export type Event = | DeleteCert | RevokeCert | GetCertBody + | CreatePkiAlert + | GetPkiAlert + | UpdatePkiAlert + | DeletePkiAlert + | CreatePkiCollection + | GetPkiCollection + | UpdatePkiCollection + | DeletePkiCollection + | GetPkiCollectionItems + | AddPkiCollectionItem + | DeletePkiCollectionItem | CreateKmsEvent | UpdateKmsEvent | DeleteKmsEvent diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts index b942cdd83..7ea2ba39f 100644 --- a/backend/src/ee/services/permission/project-permission.ts +++ b/backend/src/ee/services/permission/project-permission.ts @@ -30,6 +30,8 @@ export enum ProjectPermissionSub { Identity = "identity", CertificateAuthorities = "certificate-authorities", Certificates = "certificates", + PkiAlerts = "pki-alerts", + PkiCollections = "pki-collections", Kms = "kms" } @@ -63,6 +65,8 @@ export type ProjectPermissionSet = | [ProjectPermissionActions, ProjectPermissionSub.Identity] | [ProjectPermissionActions, ProjectPermissionSub.CertificateAuthorities] | [ProjectPermissionActions, ProjectPermissionSub.Certificates] + | [ProjectPermissionActions, ProjectPermissionSub.PkiAlerts] + | [ProjectPermissionActions, ProjectPermissionSub.PkiCollections] | [ProjectPermissionActions.Delete, ProjectPermissionSub.Project] | [ProjectPermissionActions.Edit, ProjectPermissionSub.Project] | [ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback] @@ -161,6 +165,16 @@ const buildAdminPermissionRules = () => { can(ProjectPermissionActions.Edit, ProjectPermissionSub.Certificates); can(ProjectPermissionActions.Delete, ProjectPermissionSub.Certificates); + can(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts); + can(ProjectPermissionActions.Create, ProjectPermissionSub.PkiAlerts); + can(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiAlerts); + can(ProjectPermissionActions.Delete, ProjectPermissionSub.PkiAlerts); + + can(ProjectPermissionActions.Read, ProjectPermissionSub.PkiCollections); + can(ProjectPermissionActions.Create, ProjectPermissionSub.PkiCollections); + can(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiCollections); + can(ProjectPermissionActions.Delete, ProjectPermissionSub.PkiCollections); + can(ProjectPermissionActions.Edit, ProjectPermissionSub.Project); can(ProjectPermissionActions.Delete, ProjectPermissionSub.Project); @@ -237,6 +251,9 @@ const buildMemberPermissionRules = () => { can(ProjectPermissionActions.Edit, ProjectPermissionSub.Certificates); can(ProjectPermissionActions.Delete, ProjectPermissionSub.Certificates); + can(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts); + can(ProjectPermissionActions.Read, ProjectPermissionSub.PkiCollections); + return rules; }; diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts index ab6a8e7ef..b3aa089ab 100644 --- a/backend/src/lib/api-docs/constants.ts +++ b/backend/src/lib/api-docs/constants.ts @@ -1089,6 +1089,7 @@ export const CERTIFICATE_AUTHORITIES = { }, ISSUE_CERT: { caId: "The ID of the CA to issue the certificate from", + pkiCollectionId: "The ID of the PKI collection to add the certificate to", friendlyName: "A friendly name for the certificate", commonName: "The common name (CN) for the certificate", altNames: @@ -1104,6 +1105,7 @@ export const CERTIFICATE_AUTHORITIES = { }, SIGN_CERT: { caId: "The ID of the CA to issue the certificate from", + pkiCollectionId: "The ID of the PKI collection to add the certificate to", csr: "The pem-encoded CSR to sign with the CA to be used for certificate issuance", friendlyName: "A friendly name for the certificate", commonName: "The common name (CN) for the certificate", @@ -1145,6 +1147,65 @@ export const CERTIFICATES = { } }; +export const ALERTS = { + CREATE: { + projectId: "The ID of the project to create the alert in", + pkiCollectionId: "The ID of the PKI collection to bind to the alert", + name: "The name of the alert", + alertBeforeDays: "The number of days before the certificate expires to trigger the alert", + emails: "The email addresses to send the alert email to" + }, + GET: { + alertId: "The ID of the alert to get" + }, + UPDATE: { + alertId: "The ID of the alert to update", + name: "The name of the alert to update to", + alertBeforeDays: "The number of days before the certificate expires to trigger the alert to update to", + pkiCollectionId: "The ID of the PKI collection to bind to the alert to update to", + emails: "The email addresses to send the alert email to update to" + }, + DELETE: { + alertId: "The ID of the alert to delete" + } +}; + +export const PKI_COLLECTIONS = { + CREATE: { + projectId: "The ID of the project to create the PKI collection in", + name: "The name of the PKI collection", + description: "A description for the PKI collection" + }, + GET: { + collectionId: "The ID of the PKI collection to get" + }, + UPDATE: { + collectionId: "The ID of the PKI collection to update", + name: "The name of the PKI collection to update to", + description: "The description for the PKI collection to update to" + }, + DELETE: { + collectionId: "The ID of the PKI collection to delete" + }, + LIST_ITEMS: { + collectionId: "The ID of the PKI collection to list items from", + type: "The type of the PKI collection item to list", + offset: "The offset to start from", + limit: "The number of items to return" + }, + ADD_ITEM: { + collectionId: "The ID of the PKI collection to add the item to", + type: "The type of the PKI collection item to add", + itemId: "The resource ID of the PKI collection item to add" + }, + DELETE_ITEM: { + collectionId: "The ID of the PKI collection to delete the item from", + collectionItemId: "The ID of the PKI collection item to delete", + type: "The type of the deleted PKI collection item", + itemId: "The resource ID of the deleted PKI collection item" + } +}; + export const PROJECT_ROLE = { CREATE: { projectSlug: "Slug of the project to create the role for.", diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts index ec222f0fa..48330cf04 100644 --- a/backend/src/queue/queue-service.ts +++ b/backend/src/queue/queue-service.ts @@ -16,6 +16,7 @@ export enum QueueName { // TODO(akhilmhdh): This will get removed later. For now this is kept to stop the repeatable queue AuditLogPrune = "audit-log-prune", DailyResourceCleanUp = "daily-resource-cleanup", + DailyExpiringPkiItemAlert = "daily-expiring-pki-item-alert", TelemetryInstanceStats = "telemtry-self-hosted-stats", IntegrationSync = "sync-integrations", SecretWebhook = "secret-webhook", @@ -36,6 +37,7 @@ export enum QueueJobs { // TODO(akhilmhdh): This will get removed later. For now this is kept to stop the repeatable queue AuditLogPrune = "audit-log-prune-job", DailyResourceCleanUp = "daily-resource-cleanup-job", + DailyExpiringPkiItemAlert = "daily-expiring-pki-item-alert", SecWebhook = "secret-webhook-trigger", TelemetryInstanceStats = "telemetry-self-hosted-stats", IntegrationSync = "secret-integration-pull", @@ -71,6 +73,10 @@ export type TQueueJobTypes = { name: QueueJobs.DailyResourceCleanUp; payload: undefined; }; + [QueueName.DailyExpiringPkiItemAlert]: { + name: QueueJobs.DailyExpiringPkiItemAlert; + payload: undefined; + }; [QueueName.AuditLogPrune]: { name: QueueJobs.AuditLogPrune; payload: undefined; diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts index 03a99bdd3..1aa1e18fc 100644 --- a/backend/src/server/routes/index.ts +++ b/backend/src/server/routes/index.ts @@ -131,6 +131,12 @@ import { orgRoleServiceFactory } from "@app/services/org/org-role-service"; import { orgServiceFactory } from "@app/services/org/org-service"; import { orgAdminServiceFactory } from "@app/services/org-admin/org-admin-service"; import { orgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal"; +import { dailyExpiringPkiItemAlertQueueServiceFactory } from "@app/services/pki-alert/expiring-pki-item-alert-queue"; +import { pkiAlertDALFactory } from "@app/services/pki-alert/pki-alert-dal"; +import { pkiAlertServiceFactory } from "@app/services/pki-alert/pki-alert-service"; +import { pkiCollectionDALFactory } from "@app/services/pki-collection/pki-collection-dal"; +import { pkiCollectionItemDALFactory } from "@app/services/pki-collection/pki-collection-item-dal"; +import { pkiCollectionServiceFactory } from "@app/services/pki-collection/pki-collection-service"; import { projectDALFactory } from "@app/services/project/project-dal"; import { projectQueueFactory } from "@app/services/project/project-queue"; import { projectServiceFactory } from "@app/services/project/project-service"; @@ -585,6 +591,10 @@ export const registerRoutes = async ( const certificateDAL = certificateDALFactory(db); const certificateBodyDAL = certificateBodyDALFactory(db); + const pkiAlertDAL = pkiAlertDALFactory(db); + const pkiCollectionDAL = pkiCollectionDALFactory(db); + const pkiCollectionItemDAL = pkiCollectionItemDALFactory(db); + const certificateService = certificateServiceFactory({ certificateDAL, certificateBodyDAL, @@ -615,6 +625,8 @@ export const registerRoutes = async ( certificateAuthorityQueue, certificateDAL, certificateBodyDAL, + pkiCollectionDAL, + pkiCollectionItemDAL, projectDAL, kmsService, permissionService @@ -629,6 +641,21 @@ export const registerRoutes = async ( licenseService }); + const pkiAlertService = pkiAlertServiceFactory({ + pkiAlertDAL, + pkiCollectionDAL, + permissionService, + smtpService + }); + + const pkiCollectionService = pkiCollectionServiceFactory({ + pkiCollectionDAL, + pkiCollectionItemDAL, + certificateAuthorityDAL, + certificateDAL, + permissionService + }); + const projectService = projectServiceFactory({ permissionService, projectDAL, @@ -645,6 +672,8 @@ export const registerRoutes = async ( licenseService, certificateAuthorityDAL, certificateDAL, + pkiAlertDAL, + pkiCollectionDAL, projectUserMembershipRoleDAL, identityProjectMembershipRoleDAL, keyStore, @@ -1044,6 +1073,11 @@ export const registerRoutes = async ( identityUniversalAuthClientSecretDAL: identityUaClientSecretDAL }); + const dailyExpiringPkiItemAlert = dailyExpiringPkiItemAlertQueueServiceFactory({ + queueService, + pkiAlertService + }); + const oidcService = oidcConfigServiceFactory({ orgDAL, orgMembershipDAL, @@ -1068,6 +1102,7 @@ export const registerRoutes = async ( await telemetryQueue.startTelemetryCheck(); await dailyResourceCleanUp.startCleanUp(); + await dailyExpiringPkiItemAlert.startSendingAlerts(); await kmsService.startService(); // inject all services @@ -1126,6 +1161,8 @@ export const registerRoutes = async ( certificate: certificateService, certificateAuthority: certificateAuthorityService, certificateAuthorityCrl: certificateAuthorityCrlService, + pkiAlert: pkiAlertService, + pkiCollection: pkiCollectionService, secretScanning: secretScanningService, license: licenseService, trustedIp: trustedIpService, diff --git a/backend/src/server/routes/v1/certificate-authority-router.ts b/backend/src/server/routes/v1/certificate-authority-router.ts index 103d430c0..35de2b953 100644 --- a/backend/src/server/routes/v1/certificate-authority-router.ts +++ b/backend/src/server/routes/v1/certificate-authority-router.ts @@ -556,6 +556,7 @@ export const registerCaRouter = async (server: FastifyZodProvider) => { }), body: z .object({ + pkiCollectionId: z.string().trim().optional().describe(CERTIFICATE_AUTHORITIES.ISSUE_CERT.pkiCollectionId), friendlyName: z.string().trim().optional().describe(CERTIFICATE_AUTHORITIES.ISSUE_CERT.friendlyName), commonName: z.string().trim().min(1).describe(CERTIFICATE_AUTHORITIES.ISSUE_CERT.commonName), altNames: validateAltNamesField.describe(CERTIFICATE_AUTHORITIES.ISSUE_CERT.altNames), @@ -635,6 +636,7 @@ export const registerCaRouter = async (server: FastifyZodProvider) => { body: z .object({ csr: z.string().trim().min(1).describe(CERTIFICATE_AUTHORITIES.SIGN_CERT.csr), + pkiCollectionId: z.string().trim().optional().describe(CERTIFICATE_AUTHORITIES.SIGN_CERT.pkiCollectionId), friendlyName: z.string().trim().optional().describe(CERTIFICATE_AUTHORITIES.SIGN_CERT.friendlyName), commonName: z.string().trim().min(1).optional().describe(CERTIFICATE_AUTHORITIES.SIGN_CERT.commonName), altNames: validateAltNamesField.describe(CERTIFICATE_AUTHORITIES.SIGN_CERT.altNames), diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.ts index 6c988d995..01bec65ad 100644 --- a/backend/src/server/routes/v1/index.ts +++ b/backend/src/server/routes/v1/index.ts @@ -18,6 +18,8 @@ import { registerInviteOrgRouter } from "./invite-org-router"; import { registerOrgAdminRouter } from "./org-admin-router"; import { registerOrgRouter } from "./organization-router"; import { registerPasswordRouter } from "./password-router"; +import { registerPkiAlertRouter } from "./pki-alert-router"; +import { registerPkiCollectionRouter } from "./pki-collection-router"; import { registerProjectEnvRouter } from "./project-env-router"; import { registerProjectKeyRouter } from "./project-key-router"; import { registerProjectMembershipRouter } from "./project-membership-router"; @@ -74,6 +76,8 @@ export const registerV1Routes = async (server: FastifyZodProvider) => { async (pkiRouter) => { await pkiRouter.register(registerCaRouter, { prefix: "/ca" }); await pkiRouter.register(registerCertRouter, { prefix: "/certificates" }); + await pkiRouter.register(registerPkiAlertRouter, { prefix: "/alerts" }); + await pkiRouter.register(registerPkiCollectionRouter, { prefix: "/collections" }); }, { prefix: "/pki" } ); diff --git a/backend/src/server/routes/v1/pki-alert-router.ts b/backend/src/server/routes/v1/pki-alert-router.ts new file mode 100644 index 000000000..f64ec9e47 --- /dev/null +++ b/backend/src/server/routes/v1/pki-alert-router.ts @@ -0,0 +1,198 @@ +import { z } from "zod"; + +import { PkiAlertsSchema } from "@app/db/schemas"; +import { EventType } from "@app/ee/services/audit-log/audit-log-types"; +import { ALERTS } from "@app/lib/api-docs"; +import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; +import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; +import { AuthMode } from "@app/services/auth/auth-type"; + +export const registerPkiAlertRouter = async (server: FastifyZodProvider) => { + server.route({ + method: "POST", + url: "/", + config: { + rateLimit: writeLimit + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + schema: { + description: "Create PKI alert", + body: z.object({ + projectId: z.string().trim().describe(ALERTS.CREATE.projectId), + pkiCollectionId: z.string().trim().describe(ALERTS.CREATE.pkiCollectionId), + name: z.string().trim().describe(ALERTS.CREATE.name), + alertBeforeDays: z.number().describe(ALERTS.CREATE.alertBeforeDays), + emails: z + .array(z.string().trim().email({ message: "Invalid email address" })) + .min(1, { message: "You must specify at least 1 email" }) + .max(5, { message: "You can specify a maximum of 5 emails" }) + .describe(ALERTS.CREATE.emails) + }), + response: { + 200: PkiAlertsSchema + } + }, + handler: async (req) => { + const alert = await server.services.pkiAlert.createPkiAlert({ + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + ...req.body + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: alert.projectId, + event: { + type: EventType.CREATE_PKI_ALERT, + metadata: { + pkiAlertId: alert.id, + pkiCollectionId: alert.pkiCollectionId, + name: alert.name, + alertBeforeDays: alert.alertBeforeDays, + recipientEmails: alert.recipientEmails + } + } + }); + + return alert; + } + }); + + server.route({ + method: "GET", + url: "/:alertId", + config: { + rateLimit: readLimit + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + schema: { + description: "Get PKI alert", + params: z.object({ + alertId: z.string().trim().describe(ALERTS.GET.alertId) + }), + response: { + 200: PkiAlertsSchema + } + }, + handler: async (req) => { + const alert = await server.services.pkiAlert.getPkiAlertById({ + alertId: req.params.alertId, + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: alert.projectId, + event: { + type: EventType.GET_PKI_ALERT, + metadata: { + pkiAlertId: alert.id + } + } + }); + + return alert; + } + }); + + server.route({ + method: "PATCH", + url: "/:alertId", + config: { + rateLimit: readLimit + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + schema: { + description: "Update PKI alert", + params: z.object({ + alertId: z.string().trim().describe(ALERTS.UPDATE.alertId) + }), + body: z.object({ + name: z.string().trim().optional().describe(ALERTS.UPDATE.name), + alertBeforeDays: z.number().optional().describe(ALERTS.UPDATE.alertBeforeDays), + pkiCollectionId: z.string().trim().optional().describe(ALERTS.UPDATE.pkiCollectionId), + emails: z + .array(z.string().trim().email({ message: "Invalid email address" })) + .min(1, { message: "You must specify at least 1 email" }) + .max(5, { message: "You can specify a maximum of 5 emails" }) + .optional() + .describe(ALERTS.UPDATE.emails) + }), + response: { + 200: PkiAlertsSchema + } + }, + handler: async (req) => { + const alert = await server.services.pkiAlert.updatePkiAlert({ + alertId: req.params.alertId, + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + ...req.body + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: alert.projectId, + event: { + type: EventType.UPDATE_PKI_ALERT, + metadata: { + pkiAlertId: alert.id, + pkiCollectionId: alert.pkiCollectionId, + name: alert.name, + alertBeforeDays: alert.alertBeforeDays, + recipientEmails: alert.recipientEmails + } + } + }); + + return alert; + } + }); + + server.route({ + method: "DELETE", + url: "/:alertId", + config: { + rateLimit: writeLimit + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + schema: { + description: "Delete PKI alert", + params: z.object({ + alertId: z.string().trim().describe(ALERTS.DELETE.alertId) + }), + response: { + 200: PkiAlertsSchema + } + }, + handler: async (req) => { + const alert = await server.services.pkiAlert.deletePkiAlert({ + alertId: req.params.alertId, + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: alert.projectId, + event: { + type: EventType.DELETE_PKI_ALERT, + metadata: { + pkiAlertId: alert.id + } + } + }); + + return alert; + } + }); +}; diff --git a/backend/src/server/routes/v1/pki-collection-router.ts b/backend/src/server/routes/v1/pki-collection-router.ts new file mode 100644 index 000000000..2f2add5c1 --- /dev/null +++ b/backend/src/server/routes/v1/pki-collection-router.ts @@ -0,0 +1,338 @@ +import { z } from "zod"; + +import { PkiCollectionItemsSchema, PkiCollectionsSchema } from "@app/db/schemas"; +import { EventType } from "@app/ee/services/audit-log/audit-log-types"; +import { PKI_COLLECTIONS } from "@app/lib/api-docs"; +import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; +import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; +import { AuthMode } from "@app/services/auth/auth-type"; +import { PkiItemType } from "@app/services/pki-collection/pki-collection-types"; + +export const registerPkiCollectionRouter = async (server: FastifyZodProvider) => { + server.route({ + method: "POST", + url: "/", + config: { + rateLimit: writeLimit + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + schema: { + description: "Create PKI collection", + body: z.object({ + projectId: z.string().trim().describe(PKI_COLLECTIONS.CREATE.projectId), + name: z.string().trim().describe(PKI_COLLECTIONS.CREATE.name), + description: z.string().trim().default("").describe(PKI_COLLECTIONS.CREATE.description) + }), + response: { + 200: PkiCollectionsSchema + } + }, + handler: async (req) => { + const pkiCollection = await server.services.pkiCollection.createPkiCollection({ + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + ...req.body + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: pkiCollection.projectId, + event: { + type: EventType.CREATE_PKI_COLLECTION, + metadata: { + pkiCollectionId: pkiCollection.id, + name: pkiCollection.name + } + } + }); + + return pkiCollection; + } + }); + + server.route({ + method: "GET", + url: "/:collectionId", + config: { + rateLimit: readLimit + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + schema: { + description: "Get PKI collection", + params: z.object({ + collectionId: z.string().trim().describe(PKI_COLLECTIONS.GET.collectionId) + }), + response: { + 200: PkiCollectionsSchema + } + }, + handler: async (req) => { + const pkiCollection = await server.services.pkiCollection.getPkiCollectionById({ + collectionId: req.params.collectionId, + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: pkiCollection.projectId, + event: { + type: EventType.GET_PKI_COLLECTION, + metadata: { + pkiCollectionId: pkiCollection.id + } + } + }); + + return pkiCollection; + } + }); + + server.route({ + method: "PATCH", + url: "/:collectionId", + config: { + rateLimit: writeLimit + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + schema: { + description: "Update PKI collection", + params: z.object({ + collectionId: z.string().trim().describe(PKI_COLLECTIONS.UPDATE.collectionId) + }), + body: z.object({ + name: z.string().trim().optional().describe(PKI_COLLECTIONS.UPDATE.name), + description: z.string().trim().optional().describe(PKI_COLLECTIONS.UPDATE.description) + }), + response: { + 200: PkiCollectionsSchema + } + }, + handler: async (req) => { + const pkiCollection = await server.services.pkiCollection.updatePkiCollection({ + collectionId: req.params.collectionId, + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + ...req.body + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: pkiCollection.projectId, + event: { + type: EventType.UPDATE_PKI_COLLECTION, + metadata: { + pkiCollectionId: pkiCollection.id, + name: pkiCollection.name + } + } + }); + + return pkiCollection; + } + }); + + server.route({ + method: "DELETE", + url: "/:collectionId", + config: { + rateLimit: writeLimit + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + schema: { + description: "Delete PKI collection", + params: z.object({ + collectionId: z.string().trim().describe(PKI_COLLECTIONS.DELETE.collectionId) + }), + response: { + 200: PkiCollectionsSchema + } + }, + handler: async (req) => { + const pkiCollection = await server.services.pkiCollection.deletePkiCollection({ + collectionId: req.params.collectionId, + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: pkiCollection.projectId, + event: { + type: EventType.DELETE_PKI_COLLECTION, + metadata: { + pkiCollectionId: pkiCollection.id + } + } + }); + + return pkiCollection; + } + }); + + server.route({ + method: "GET", + url: "/:collectionId/items", + config: { + rateLimit: writeLimit + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + schema: { + description: "Get items in PKI collection", + params: z.object({ + collectionId: z.string().trim().describe(PKI_COLLECTIONS.LIST_ITEMS.collectionId) + }), + querystring: z.object({ + type: z.nativeEnum(PkiItemType).optional().describe(PKI_COLLECTIONS.LIST_ITEMS.type), + offset: z.coerce.number().min(0).max(100).default(0).describe(PKI_COLLECTIONS.LIST_ITEMS.offset), + limit: z.coerce.number().min(1).max(100).default(25).describe(PKI_COLLECTIONS.LIST_ITEMS.limit) + }), + response: { + 200: z.object({ + collectionItems: z.array( + PkiCollectionItemsSchema.omit({ caId: true, certId: true }).extend({ + type: z.nativeEnum(PkiItemType), + itemId: z.string().trim(), + notBefore: z.date(), + notAfter: z.date(), + friendlyName: z.string().trim() + }) + ), + totalCount: z.number() + }) + } + }, + handler: async (req) => { + const { pkiCollection, pkiCollectionItems, totalCount } = + await server.services.pkiCollection.getPkiCollectionItems({ + collectionId: req.params.collectionId, + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + ...req.query + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: pkiCollection.projectId, + event: { + type: EventType.GET_PKI_COLLECTION_ITEMS, + metadata: { + pkiCollectionId: pkiCollection.id + } + } + }); + + return { + collectionItems: pkiCollectionItems, + totalCount + }; + } + }); + + server.route({ + method: "POST", + url: "/:collectionId/items", + config: { + rateLimit: writeLimit + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + schema: { + description: "Add item to PKI collection", + params: z.object({ + collectionId: z.string().trim().describe(PKI_COLLECTIONS.ADD_ITEM.collectionId) + }), + body: z.object({ + type: z.nativeEnum(PkiItemType).describe(PKI_COLLECTIONS.ADD_ITEM.type), + itemId: z.string().trim().describe(PKI_COLLECTIONS.ADD_ITEM.itemId) + }), + response: { + 200: PkiCollectionItemsSchema.omit({ caId: true, certId: true }).extend({ + type: z.nativeEnum(PkiItemType).describe(PKI_COLLECTIONS.ADD_ITEM.type), + itemId: z.string().trim().describe(PKI_COLLECTIONS.ADD_ITEM.itemId) + }) + } + }, + handler: async (req) => { + const { pkiCollection, pkiCollectionItem } = await server.services.pkiCollection.addItemToPkiCollection({ + collectionId: req.params.collectionId, + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + ...req.body + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: pkiCollection.projectId, + event: { + type: EventType.ADD_PKI_COLLECTION_ITEM, + metadata: { + pkiCollectionId: pkiCollection.id, + pkiCollectionItemId: pkiCollectionItem.id, + type: pkiCollectionItem.type, + itemId: pkiCollectionItem.itemId + } + } + }); + + return pkiCollectionItem; + } + }); + + server.route({ + method: "DELETE", + url: "/:collectionId/items/:collectionItemId", + config: { + rateLimit: writeLimit + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + schema: { + description: "Remove item from PKI collection", + params: z.object({ + collectionId: z.string().trim().describe(PKI_COLLECTIONS.DELETE_ITEM.collectionId), + collectionItemId: z.string().trim().describe(PKI_COLLECTIONS.DELETE_ITEM.collectionItemId) + }), + response: { + 200: PkiCollectionItemsSchema.omit({ caId: true, certId: true }).extend({ + type: z.nativeEnum(PkiItemType).describe(PKI_COLLECTIONS.DELETE_ITEM.type), + itemId: z.string().trim().describe(PKI_COLLECTIONS.DELETE_ITEM.itemId) + }) + } + }, + handler: async (req) => { + const { pkiCollection, pkiCollectionItem } = await server.services.pkiCollection.removeItemFromPkiCollection({ + collectionId: req.params.collectionId, + itemId: req.params.collectionItemId, + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: pkiCollection.projectId, + event: { + type: EventType.DELETE_PKI_COLLECTION_ITEM, + metadata: { + pkiCollectionId: pkiCollection.id, + pkiCollectionItemId: pkiCollectionItem.id + } + } + }); + + return pkiCollectionItem; + } + }); +}; diff --git a/backend/src/server/routes/v2/project-router.ts b/backend/src/server/routes/v2/project-router.ts index 8cfb2c19b..a45cb51fa 100644 --- a/backend/src/server/routes/v2/project-router.ts +++ b/backend/src/server/routes/v2/project-router.ts @@ -1,7 +1,13 @@ import slugify from "@sindresorhus/slugify"; import { z } from "zod"; -import { CertificateAuthoritiesSchema, CertificatesSchema, ProjectKeysSchema } from "@app/db/schemas"; +import { + CertificateAuthoritiesSchema, + CertificatesSchema, + PkiAlertsSchema, + PkiCollectionsSchema, + ProjectKeysSchema +} from "@app/db/schemas"; import { EventType } from "@app/ee/services/audit-log/audit-log-types"; import { PROJECTS } from "@app/lib/api-docs"; import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; @@ -392,4 +398,64 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => { return { certificates, totalCount }; } }); + + server.route({ + method: "GET", + url: "/:projectId/pki-alerts", + config: { + rateLimit: readLimit + }, + schema: { + params: z.object({ + projectId: z.string().trim() + }), + response: { + 200: z.object({ + alerts: z.array(PkiAlertsSchema) + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + handler: async (req) => { + const { alerts } = await server.services.project.listProjectAlerts({ + projectId: req.params.projectId, + actorId: req.permission.id, + actorOrgId: req.permission.orgId, + actorAuthMethod: req.permission.authMethod, + actor: req.permission.type + }); + + return { alerts }; + } + }); + + server.route({ + method: "GET", + url: "/:projectId/pki-collections", + config: { + rateLimit: readLimit + }, + schema: { + params: z.object({ + projectId: z.string().trim() + }), + response: { + 200: z.object({ + collections: z.array(PkiCollectionsSchema) + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + handler: async (req) => { + const { pkiCollections } = await server.services.project.listProjectPkiCollections({ + projectId: req.params.projectId, + actorId: req.permission.id, + actorOrgId: req.permission.orgId, + actorAuthMethod: req.permission.authMethod, + actor: req.permission.type + }); + + return { collections: pkiCollections }; + } + }); }; diff --git a/backend/src/services/certificate-authority/certificate-authority-fns.ts b/backend/src/services/certificate-authority/certificate-authority-fns.ts index 4e3df1173..b1fd87a26 100644 --- a/backend/src/services/certificate-authority/certificate-authority-fns.ts +++ b/backend/src/services/certificate-authority/certificate-authority-fns.ts @@ -1,7 +1,7 @@ import * as x509 from "@peculiar/x509"; import crypto from "crypto"; -import { BadRequestError } from "@app/lib/errors"; +import { NotFoundError } from "@app/lib/errors"; import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns"; import { CertKeyAlgorithm, CertStatus } from "../certificate/certificate-types"; @@ -106,10 +106,10 @@ export const getCaCredentials = async ({ kmsService }: TGetCaCredentialsDTO) => { const ca = await certificateAuthorityDAL.findById(caId); - if (!ca) throw new BadRequestError({ message: "CA not found" }); + if (!ca) throw new NotFoundError({ message: "CA not found" }); const caSecret = await certificateAuthoritySecretDAL.findOne({ caId }); - if (!caSecret) throw new BadRequestError({ message: "CA secret not found" }); + if (!caSecret) throw new NotFoundError({ message: "CA secret not found" }); const keyId = await getProjectKmsCertificateKeyId({ projectId: ca.projectId, @@ -158,7 +158,7 @@ export const getCaCertChains = async ({ kmsService }: TGetCaCertChainsDTO) => { const ca = await certificateAuthorityDAL.findById(caId); - if (!ca) throw new BadRequestError({ message: "CA not found" }); + if (!ca) throw new NotFoundError({ message: "CA not found" }); const keyId = await getProjectKmsCertificateKeyId({ projectId: ca.projectId, @@ -205,7 +205,7 @@ export const getCaCertChain = async ({ kmsService }: TGetCaCertChainDTO) => { const caCert = await certificateAuthorityCertDAL.findById(caCertId); - if (!caCert) throw new BadRequestError({ message: "CA certificate not found" }); + if (!caCert) throw new NotFoundError({ message: "CA certificate not found" }); const ca = await certificateAuthorityDAL.findById(caCert.caId); const keyId = await getProjectKmsCertificateKeyId({ @@ -249,7 +249,7 @@ export const rebuildCaCrl = async ({ kmsService }: TRebuildCaCrlDTO) => { const ca = await certificateAuthorityDAL.findById(caId); - if (!ca) throw new BadRequestError({ message: "CA not found" }); + if (!ca) throw new NotFoundError({ message: "CA not found" }); const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: ca.id }); diff --git a/backend/src/services/certificate-authority/certificate-authority-service.ts b/backend/src/services/certificate-authority/certificate-authority-service.ts index b63ec9ba9..88f686089 100644 --- a/backend/src/services/certificate-authority/certificate-authority-service.ts +++ b/backend/src/services/certificate-authority/certificate-authority-service.ts @@ -7,10 +7,12 @@ import { z } from "zod"; import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service"; import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission"; -import { BadRequestError } from "@app/lib/errors"; +import { BadRequestError, NotFoundError } from "@app/lib/errors"; import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal"; import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal"; 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 { TProjectDALFactory } from "@app/services/project/project-dal"; import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns"; @@ -60,6 +62,8 @@ type TCertificateAuthorityServiceFactoryDep = { certificateAuthorityQueue: TCertificateAuthorityQueueFactory; // TODO: Pick certificateDAL: Pick; certificateBodyDAL: Pick; + pkiCollectionDAL: Pick; + pkiCollectionItemDAL: Pick; projectDAL: Pick; kmsService: Pick; permissionService: Pick; @@ -74,6 +78,8 @@ export const certificateAuthorityServiceFactory = ({ certificateAuthorityCrlDAL, certificateDAL, certificateBodyDAL, + pkiCollectionDAL, + pkiCollectionItemDAL, projectDAL, kmsService, permissionService @@ -1007,6 +1013,7 @@ export const certificateAuthorityServiceFactory = ({ */ const issueCertFromCa = async ({ caId, + pkiCollectionId, friendlyName, commonName, altNames, @@ -1039,6 +1046,13 @@ export const certificateAuthorityServiceFactory = ({ throw new BadRequestError({ message: "CA is expired" }); } + // check PKI collection + if (pkiCollectionId) { + const pkiCollection = await pkiCollectionDAL.findById(pkiCollectionId); + if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); + if (pkiCollection.projectId !== ca.projectId) throw new BadRequestError({ message: "Invalid PKI collection" }); + } + const certificateManagerKmsId = await getProjectKmsCertificateKeyId({ projectId: ca.projectId, projectDAL, @@ -1186,6 +1200,16 @@ export const certificateAuthorityServiceFactory = ({ tx ); + if (pkiCollectionId) { + await pkiCollectionItemDAL.create( + { + pkiCollectionId, + certId: cert.id + }, + tx + ); + } + return cert; }); @@ -1214,6 +1238,7 @@ export const certificateAuthorityServiceFactory = ({ const signCertFromCa = async ({ caId, csr, + pkiCollectionId, friendlyName, commonName, altNames, @@ -1247,6 +1272,13 @@ export const certificateAuthorityServiceFactory = ({ throw new BadRequestError({ message: "CA is expired" }); } + // check PKI collection + if (pkiCollectionId) { + const pkiCollection = await pkiCollectionDAL.findById(pkiCollectionId); + if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); + if (pkiCollection.projectId !== ca.projectId) throw new BadRequestError({ message: "Invalid PKI collection" }); + } + const certificateManagerKmsId = await getProjectKmsCertificateKeyId({ projectId: ca.projectId, projectDAL, @@ -1390,6 +1422,16 @@ export const certificateAuthorityServiceFactory = ({ tx ); + if (pkiCollectionId) { + await pkiCollectionItemDAL.create( + { + pkiCollectionId, + certId: cert.id + }, + tx + ); + } + return cert; }); diff --git a/backend/src/services/certificate-authority/certificate-authority-types.ts b/backend/src/services/certificate-authority/certificate-authority-types.ts index 31a6e1629..3fef204bf 100644 --- a/backend/src/services/certificate-authority/certificate-authority-types.ts +++ b/backend/src/services/certificate-authority/certificate-authority-types.ts @@ -87,6 +87,7 @@ export type TImportCertToCaDTO = { export type TIssueCertFromCaDTO = { caId: string; + pkiCollectionId?: string; friendlyName?: string; commonName: string; altNames: string; @@ -98,6 +99,7 @@ export type TIssueCertFromCaDTO = { export type TSignCertFromCaDTO = { caId: string; csr: string; + pkiCollectionId?: string; friendlyName?: string; commonName?: string; altNames: string; diff --git a/backend/src/services/pki-alert/expiring-pki-item-alert-queue.ts b/backend/src/services/pki-alert/expiring-pki-item-alert-queue.ts new file mode 100644 index 000000000..a592e9271 --- /dev/null +++ b/backend/src/services/pki-alert/expiring-pki-item-alert-queue.ts @@ -0,0 +1,48 @@ +import { logger } from "@app/lib/logger"; +import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue"; +import { TPkiAlertServiceFactory } from "@app/services/pki-alert/pki-alert-service"; + +type TDailyExpiringPkiItemAlertQueueServiceFactoryDep = { + queueService: TQueueServiceFactory; + pkiAlertService: Pick; +}; + +export type TDailyExpiringPkiItemAlertQueueServiceFactory = ReturnType< + typeof dailyExpiringPkiItemAlertQueueServiceFactory +>; + +export const dailyExpiringPkiItemAlertQueueServiceFactory = ({ + queueService, + pkiAlertService +}: TDailyExpiringPkiItemAlertQueueServiceFactoryDep) => { + queueService.start(QueueName.DailyExpiringPkiItemAlert, async () => { + logger.info(`${QueueName.DailyExpiringPkiItemAlert}: queue task started`); + await pkiAlertService.sendPkiItemExpiryNotices(); + logger.info(`${QueueName.DailyExpiringPkiItemAlert}: queue task completed`); + }); + + // we do a repeat cron job in utc timezone at 12 Midnight each day + const startSendingAlerts = async () => { + // clear previous job + await queueService.stopRepeatableJob( + QueueName.DailyExpiringPkiItemAlert, + QueueJobs.DailyExpiringPkiItemAlert, + { pattern: "0 0 * * *", utc: true }, + QueueName.DailyExpiringPkiItemAlert // just a job id + ); + + await queueService.queue(QueueName.DailyExpiringPkiItemAlert, QueueJobs.DailyExpiringPkiItemAlert, undefined, { + delay: 5000, + jobId: QueueName.DailyExpiringPkiItemAlert, + repeat: { pattern: "0 0 * * *", utc: true } + }); + }; + + queueService.listen(QueueName.DailyExpiringPkiItemAlert, "failed", (_, err) => { + logger.error(err, `${QueueName.DailyExpiringPkiItemAlert}: Expiring PKI item alert failed`); + }); + + return { + startSendingAlerts + }; +}; diff --git a/backend/src/services/pki-alert/pki-alert-dal.ts b/backend/src/services/pki-alert/pki-alert-dal.ts new file mode 100644 index 000000000..d4d4fa987 --- /dev/null +++ b/backend/src/services/pki-alert/pki-alert-dal.ts @@ -0,0 +1,84 @@ +import { TDbClient } from "@app/db"; +import { TableName } from "@app/db/schemas"; +import { DatabaseError } from "@app/lib/errors"; +import { ormify } from "@app/lib/knex"; + +import { PkiItemType } from "../pki-collection/pki-collection-types"; + +export type TPkiAlertDALFactory = ReturnType; + +export const pkiAlertDALFactory = (db: TDbClient) => { + const pkiAlertOrm = ormify(db, TableName.PkiAlert); + + const getExpiringPkiCollectionItemsForAlerting = async () => { + try { + type AlertItem = { + type: PkiItemType; + id: string; // id of the CA or certificate + expiryDate: Date; + serialNumber: string; + friendlyName: string; + pkiCollectionId: string; + alertId: string; + alertName: string; + alertBeforeDays: number; + recipientEmails: string; + }; + + // gets CAs and certificates as part of PKI collection items + const combinedQuery = db + .replicaNode() + .select( + db.raw("? as type", [PkiItemType.CA]), + `${PkiItemType.CA}.id`, + `${PkiItemType.CA}.notAfter as expiryDate`, + `${PkiItemType.CA}.serialNumber`, + `${PkiItemType.CA}.friendlyName`, + "pci.pkiCollectionId" + ) + .from(`${TableName.CertificateAuthority} as ${PkiItemType.CA}`) + .join(`${TableName.PkiCollectionItem} as pci`, `${PkiItemType.CA}.id`, "pci.caId") + .unionAll((qb) => { + void qb + .select( + db.raw("? as type", [PkiItemType.CERTIFICATE]), + `${PkiItemType.CERTIFICATE}.id`, + `${PkiItemType.CERTIFICATE}.notAfter as expiryDate`, + `${PkiItemType.CERTIFICATE}.serialNumber`, + `${PkiItemType.CERTIFICATE}.friendlyName`, + "pci.pkiCollectionId" + ) + .from(`${TableName.Certificate} as ${PkiItemType.CERTIFICATE}`) + .join(`${TableName.PkiCollectionItem} as pci`, `${PkiItemType.CERTIFICATE}.id`, "pci.certId"); + }); + + /** + * Gets alerts to send based on alertBeforeDays on PKI alerts connected to PKI collection items + * Note: Results are clamped to 1-day window to avoid sending multiple alerts for the same item + */ + const alertQuery = db + .replicaNode() + .select("combined.*", "pa.id as alertId", "pa.name as alertName", "pa.alertBeforeDays", "pa.recipientEmails") + .from(db.raw("(?) as combined", [combinedQuery])) + .join(`${TableName.PkiAlert} as pa`, "combined.pkiCollectionId", "pa.pkiCollectionId") + .whereRaw( + ` + combined."expiryDate" <= CURRENT_TIMESTAMP + (pa."alertBeforeDays" * INTERVAL '1 day') + AND combined."expiryDate" > CURRENT_TIMESTAMP + ((pa."alertBeforeDays" - 1) * INTERVAL '1 day') + ` + ) + .orderBy("combined.expiryDate"); + + const results = (await alertQuery) as AlertItem[]; + + return results; + } catch (error) { + throw new DatabaseError({ error, name: "Get expiring PKI collection items for alerting" }); + } + }; + + return { + getExpiringPkiCollectionItemsForAlerting, + ...pkiAlertOrm + }; +}; diff --git a/backend/src/services/pki-alert/pki-alert-service.ts b/backend/src/services/pki-alert/pki-alert-service.ts new file mode 100644 index 000000000..26ab380fb --- /dev/null +++ b/backend/src/services/pki-alert/pki-alert-service.ts @@ -0,0 +1,182 @@ +import { ForbiddenError } from "@casl/ability"; + +import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service"; +import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission"; +import { NotFoundError, UnauthorizedError } from "@app/lib/errors"; +import { groupBy } from "@app/lib/fn"; +import { TPkiCollectionDALFactory } from "@app/services/pki-collection/pki-collection-dal"; +import { pkiItemTypeToNameMap } from "@app/services/pki-collection/pki-collection-types"; +import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service"; + +import { TPkiAlertDALFactory } from "./pki-alert-dal"; +import { TCreateAlertDTO, TDeleteAlertDTO, TGetAlertByIdDTO, TUpdateAlertDTO } from "./pki-alert-types"; + +type TPkiAlertServiceFactoryDep = { + pkiAlertDAL: Pick< + TPkiAlertDALFactory, + "create" | "findById" | "updateById" | "deleteById" | "getExpiringPkiCollectionItemsForAlerting" + >; + pkiCollectionDAL: Pick; + permissionService: Pick; + smtpService: Pick; +}; + +export type TPkiAlertServiceFactory = ReturnType; + +export const pkiAlertServiceFactory = ({ + pkiAlertDAL, + pkiCollectionDAL, + permissionService, + smtpService +}: TPkiAlertServiceFactoryDep) => { + const sendPkiItemExpiryNotices = async () => { + const allAlertItems = await pkiAlertDAL.getExpiringPkiCollectionItemsForAlerting(); + + const flattenedResults = allAlertItems.flatMap(({ recipientEmails, ...item }) => + recipientEmails.split(",").map((email) => ({ + ...item, + recipientEmail: email.trim() + })) + ); + + const groupedByEmail = groupBy(flattenedResults, (item) => item.recipientEmail); + + for await (const [email, items] of Object.entries(groupedByEmail)) { + const groupedByAlert = groupBy(items, (item) => item.alertId); + for await (const [, alertItems] of Object.entries(groupedByAlert)) { + await smtpService.sendMail({ + recipients: [email], + subjectLine: `Infisical CA/Certificate expiration notice: ${alertItems[0].alertName}`, + substitutions: { + alertName: alertItems[0].alertName, + alertBeforeDays: items[0].alertBeforeDays, + items: alertItems.map((alertItem) => ({ + ...alertItem, + type: pkiItemTypeToNameMap[alertItem.type], + expiryDate: new Date(alertItem.expiryDate).toString() + })) + }, + template: SmtpTemplates.PkiExpirationAlert + }); + } + } + }; + + const createPkiAlert = async ({ + projectId, + name, + pkiCollectionId, + alertBeforeDays, + emails, + actorId, + actorAuthMethod, + actor, + actorOrgId + }: TCreateAlertDTO) => { + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.PkiAlerts); + + const pkiCollection = await pkiCollectionDAL.findById(pkiCollectionId); + if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); + if (pkiCollection.projectId !== projectId) + throw new UnauthorizedError({ message: "PKI collection not found in project" }); + + const alert = await pkiAlertDAL.create({ + projectId, + pkiCollectionId, + name, + alertBeforeDays, + recipientEmails: emails.join(",") + }); + return alert; + }; + + const getPkiAlertById = async ({ alertId, actorId, actorAuthMethod, actor, actorOrgId }: TGetAlertByIdDTO) => { + const alert = await pkiAlertDAL.findById(alertId); + if (!alert) throw new NotFoundError({ message: "Alert not found" }); + + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + alert.projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts); + return alert; + }; + + const updatePkiAlert = async ({ + alertId, + name, + pkiCollectionId, + alertBeforeDays, + emails, + actorId, + actorAuthMethod, + actor, + actorOrgId + }: TUpdateAlertDTO) => { + let alert = await pkiAlertDAL.findById(alertId); + if (!alert) throw new NotFoundError({ message: "Alert not found" }); + + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + alert.projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiAlerts); + + if (pkiCollectionId) { + const pkiCollection = await pkiCollectionDAL.findById(pkiCollectionId); + if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); + if (pkiCollection.projectId !== alert.projectId) + throw new UnauthorizedError({ message: "PKI collection not found in project" }); + } + + alert = await pkiAlertDAL.updateById(alertId, { + name, + alertBeforeDays, + ...(pkiCollectionId && { pkiCollectionId }), + ...(emails && { recipientEmails: emails.join(",") }) + }); + + return alert; + }; + + const deletePkiAlert = async ({ alertId, actorId, actorAuthMethod, actor, actorOrgId }: TDeleteAlertDTO) => { + let alert = await pkiAlertDAL.findById(alertId); + if (!alert) throw new NotFoundError({ message: "Alert not found" }); + + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + alert.projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Delete, ProjectPermissionSub.PkiAlerts); + alert = await pkiAlertDAL.deleteById(alertId); + return alert; + }; + + return { + sendPkiItemExpiryNotices, + createPkiAlert, + getPkiAlertById, + updatePkiAlert, + deletePkiAlert + }; +}; diff --git a/backend/src/services/pki-alert/pki-alert-types.ts b/backend/src/services/pki-alert/pki-alert-types.ts new file mode 100644 index 000000000..c00be0e03 --- /dev/null +++ b/backend/src/services/pki-alert/pki-alert-types.ts @@ -0,0 +1,24 @@ +import { TProjectPermission } from "@app/lib/types"; + +export type TCreateAlertDTO = { + name: string; + pkiCollectionId: string; + alertBeforeDays: number; + emails: string[]; +} & TProjectPermission; + +export type TGetAlertByIdDTO = { + alertId: string; +} & Omit; + +export type TUpdateAlertDTO = { + alertId: string; + name?: string; + pkiCollectionId?: string; + alertBeforeDays?: number; + emails?: string[]; +} & Omit; + +export type TDeleteAlertDTO = { + alertId: string; +} & Omit; diff --git a/backend/src/services/pki-collection/pki-collection-dal.ts b/backend/src/services/pki-collection/pki-collection-dal.ts new file mode 100644 index 000000000..382b4c6ef --- /dev/null +++ b/backend/src/services/pki-collection/pki-collection-dal.ts @@ -0,0 +1,13 @@ +import { TDbClient } from "@app/db"; +import { TableName } from "@app/db/schemas"; +import { ormify } from "@app/lib/knex"; + +export type TPkiCollectionDALFactory = ReturnType; + +export const pkiCollectionDALFactory = (db: TDbClient) => { + const pkiCollectionOrm = ormify(db, TableName.PkiCollection); + + return { + ...pkiCollectionOrm + }; +}; diff --git a/backend/src/services/pki-collection/pki-collection-fns.ts b/backend/src/services/pki-collection/pki-collection-fns.ts new file mode 100644 index 000000000..2b74bcf5b --- /dev/null +++ b/backend/src/services/pki-collection/pki-collection-fns.ts @@ -0,0 +1,30 @@ +import { TPkiCollectionItems } from "@app/db/schemas"; + +import { PkiItemType } from "./pki-collection-types"; + +/** + * Transforms a PKI Collection Item from the database to the expected API response format + */ +export const transformPkiCollectionItem = (pkiCollectionItem: TPkiCollectionItems) => { + let type: PkiItemType; + let itemId: string; + + if (pkiCollectionItem.caId) { + type = PkiItemType.CA; + itemId = pkiCollectionItem.caId; + } else if (pkiCollectionItem.certId) { + type = PkiItemType.CERTIFICATE; + itemId = pkiCollectionItem.certId; + } else { + throw new Error("Invalid PKI Collection Item: must have either caId or certId"); + } + + return { + id: pkiCollectionItem.id, + pkiCollectionId: pkiCollectionItem.pkiCollectionId, + type, + itemId, + createdAt: pkiCollectionItem.createdAt, + updatedAt: pkiCollectionItem.updatedAt + }; +}; diff --git a/backend/src/services/pki-collection/pki-collection-item-dal.ts b/backend/src/services/pki-collection/pki-collection-item-dal.ts new file mode 100644 index 000000000..de896e15c --- /dev/null +++ b/backend/src/services/pki-collection/pki-collection-item-dal.ts @@ -0,0 +1,93 @@ +import { TDbClient } from "@app/db"; +import { TableName, TPkiCollectionItems } from "@app/db/schemas"; +import { DatabaseError } from "@app/lib/errors"; +import { ormify } from "@app/lib/knex"; + +import { PkiItemType } from "./pki-collection-types"; + +export type TPkiCollectionItemDALFactory = ReturnType; + +export const pkiCollectionItemDALFactory = (db: TDbClient) => { + const pkiCollectionItemOrm = ormify(db, TableName.PkiCollectionItem); + + const findPkiCollectionItems = async ({ + collectionId, + type, + offset, + limit + }: { + collectionId: string; + type?: PkiItemType; + offset?: number; + limit?: number; + }) => { + try { + const query = db + .replicaNode()(TableName.PkiCollectionItem) + .select( + "pki_collection_items.*", + db.raw( + `COALESCE("${TableName.CertificateAuthority}"."notBefore", "${TableName.Certificate}"."notBefore") as "notBefore"` + ), + db.raw( + `COALESCE("${TableName.CertificateAuthority}"."notAfter", "${TableName.Certificate}"."notAfter") as "notAfter"` + ), + db.raw( + `COALESCE("${TableName.CertificateAuthority}"."friendlyName", "${TableName.Certificate}"."friendlyName") as "friendlyName"` + ) + ) + .leftJoin( + TableName.CertificateAuthority, + `${TableName.PkiCollectionItem}.caId`, + `${TableName.CertificateAuthority}.id` + ) + .leftJoin(TableName.Certificate, `${TableName.PkiCollectionItem}.certId`, `${TableName.Certificate}.id`) + .where((builder) => { + void builder.where(`${TableName.PkiCollectionItem}.pkiCollectionId`, collectionId); + if (type === PkiItemType.CA) { + void builder.whereNull(`${TableName.PkiCollectionItem}.certId`); + } else if (type === PkiItemType.CERTIFICATE) { + void builder.whereNull(`${TableName.PkiCollectionItem}.caId`); + } + }); + + if (offset) { + void query.offset(offset); + } + if (limit) { + void query.limit(limit); + } + + void query.orderBy(`${TableName.PkiCollectionItem}.createdAt`, "desc"); + + const result = await query; + return result as (TPkiCollectionItems & { notAfter: Date; notBefore: Date; friendlyName: string })[]; + } catch (error) { + throw new DatabaseError({ error, name: "Find all PKI collection items" }); + } + }; + + const countItemsInPkiCollection = async (collectionId: string) => { + try { + interface CountResult { + count: string; + } + + const query = db + .replicaNode()(TableName.PkiCollectionItem) + .where(`${TableName.PkiCollectionItem}.pkiCollectionId`, collectionId); + + const count = await query.count("*").first(); + + return parseInt((count as unknown as CountResult).count || "0", 10); + } catch (error) { + throw new DatabaseError({ error, name: "Count all PKI collection items" }); + } + }; + + return { + ...pkiCollectionItemOrm, + findPkiCollectionItems, + countItemsInPkiCollection + }; +}; diff --git a/backend/src/services/pki-collection/pki-collection-service.ts b/backend/src/services/pki-collection/pki-collection-service.ts new file mode 100644 index 000000000..f2a3fa0c4 --- /dev/null +++ b/backend/src/services/pki-collection/pki-collection-service.ts @@ -0,0 +1,331 @@ +import { ForbiddenError } from "@casl/ability"; + +import { TPkiCollectionItems } from "@app/db/schemas"; +import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service"; +import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission"; +import { BadRequestError, NotFoundError } from "@app/lib/errors"; +import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal"; +import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal"; + +import { TPkiCollectionDALFactory } from "./pki-collection-dal"; +import { transformPkiCollectionItem } from "./pki-collection-fns"; +import { TPkiCollectionItemDALFactory } from "./pki-collection-item-dal"; +import { + PkiItemType, + TAddItemToPkiCollectionDTO, + TCreatePkiCollectionDTO, + TDeletePkiCollectionDTO, + TGetPkiCollectionByIdDTO, + TGetPkiCollectionItems, + TRemoveItemFromPkiCollectionDTO, + TUpdatePkiCollectionDTO +} from "./pki-collection-types"; + +type TPkiCollectionServiceFactoryDep = { + pkiCollectionDAL: Pick; + pkiCollectionItemDAL: Pick< + TPkiCollectionItemDALFactory, + "findOne" | "create" | "deleteById" | "findPkiCollectionItems" | "countItemsInPkiCollection" + >; + certificateAuthorityDAL: Pick; + certificateDAL: Pick; + permissionService: Pick; +}; + +export type TPkiCollectionServiceFactory = ReturnType; + +export const pkiCollectionServiceFactory = ({ + pkiCollectionDAL, + pkiCollectionItemDAL, + certificateAuthorityDAL, + certificateDAL, + permissionService +}: TPkiCollectionServiceFactoryDep) => { + const createPkiCollection = async ({ + name, + description, + projectId, + actorId, + actorAuthMethod, + actor, + actorOrgId + }: TCreatePkiCollectionDTO) => { + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionActions.Create, + ProjectPermissionSub.PkiCollections + ); + + const pkiCollection = await pkiCollectionDAL.create({ + projectId, + name, + description + }); + + return pkiCollection; + }; + + const getPkiCollectionById = async ({ + collectionId, + actorId, + actorAuthMethod, + actor, + actorOrgId + }: TGetPkiCollectionByIdDTO) => { + const pkiCollection = await pkiCollectionDAL.findById(collectionId); + if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); + + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + pkiCollection.projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiCollections); + return pkiCollection; + }; + + const updatePkiCollection = async ({ + collectionId, + name, + description, + actorId, + actorAuthMethod, + actor, + actorOrgId + }: TUpdatePkiCollectionDTO) => { + let pkiCollection = await pkiCollectionDAL.findById(collectionId); + if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); + + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + pkiCollection.projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiCollections); + pkiCollection = await pkiCollectionDAL.updateById(collectionId, { + name, + description + }); + + return pkiCollection; + }; + + const deletePkiCollection = async ({ + collectionId, + actorId, + actorAuthMethod, + actor, + actorOrgId + }: TDeletePkiCollectionDTO) => { + let pkiCollection = await pkiCollectionDAL.findById(collectionId); + if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); + + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + pkiCollection.projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionActions.Delete, + ProjectPermissionSub.PkiCollections + ); + pkiCollection = await pkiCollectionDAL.deleteById(collectionId); + return pkiCollection; + }; + + const getPkiCollectionItems = async ({ + collectionId, + type, + offset = 0, + limit = 25, + actorId, + actorAuthMethod, + actor, + actorOrgId + }: TGetPkiCollectionItems) => { + const pkiCollection = await pkiCollectionDAL.findById(collectionId); + if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); + + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + pkiCollection.projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiCollections); + + const pkiCollectionItems = await pkiCollectionItemDAL.findPkiCollectionItems({ + collectionId, + type, + offset, + limit + }); + + const count = await pkiCollectionItemDAL.countItemsInPkiCollection(collectionId); + + return { + pkiCollection, + pkiCollectionItems: pkiCollectionItems.map((p) => ({ + ...transformPkiCollectionItem(p), + notBefore: p.notBefore, + notAfter: p.notAfter, + friendlyName: p.friendlyName + })), + totalCount: count + }; + }; + + const addItemToPkiCollection = async ({ + collectionId, + actorId, + actorAuthMethod, + actor, + actorOrgId, + type, + itemId + }: TAddItemToPkiCollectionDTO) => { + const pkiCollection = await pkiCollectionDAL.findById(collectionId); + if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); + + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + pkiCollection.projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionActions.Create, + ProjectPermissionSub.PkiCollections + ); + + let pkiCollectionItem: TPkiCollectionItems; + switch (type) { + case PkiItemType.CA: { + // validate that CA has not already been added to PKI collection + const isCaAdded = await pkiCollectionItemDAL.findOne({ + pkiCollectionId: collectionId, + caId: itemId + }); + + if (isCaAdded) throw new BadRequestError({ message: "CA is already part of the PKI collection" }); + + // validate that there exists a CA in same project as PKI collection + const ca = await certificateAuthorityDAL.findOne({ + id: itemId, + projectId: pkiCollection.projectId + }); + + if (!ca) throw new NotFoundError({ message: "CA not found" }); + + pkiCollectionItem = await pkiCollectionItemDAL.create({ + pkiCollectionId: collectionId, + caId: itemId + }); + break; + } + case PkiItemType.CERTIFICATE: { + // validate that certificate has not already been added to PKI collection + const isCertAdded = await pkiCollectionItemDAL.findOne({ + pkiCollectionId: collectionId, + certId: itemId + }); + if (isCertAdded) throw new BadRequestError({ message: "Certificate already part of the PKI collection" }); + + // validate that there exists a certificate in same project as PKI collection + const cas = await certificateAuthorityDAL.find({ projectId: pkiCollection.projectId }); + + // TODO: consider making this more efficient + const [certificate] = await certificateDAL.find({ + $in: { + caId: cas.map((ca) => ca.id) + }, + id: itemId + }); + if (!certificate) throw new NotFoundError({ message: "Certificate not found" }); + + pkiCollectionItem = await pkiCollectionItemDAL.create({ + pkiCollectionId: collectionId, + certId: itemId + }); + break; + } + default: { + throw new BadRequestError({ message: "Invalid PKI item type" }); + } + } + + return { + pkiCollection, + pkiCollectionItem: transformPkiCollectionItem(pkiCollectionItem) + }; + }; + + const removeItemFromPkiCollection = async ({ + collectionId, + actorId, + actorAuthMethod, + actor, + actorOrgId, + itemId + }: TRemoveItemFromPkiCollectionDTO) => { + const pkiCollection = await pkiCollectionDAL.findById(collectionId); + if (!pkiCollection) throw new NotFoundError({ message: "PKI collection not found" }); + + let pkiCollectionItem = await pkiCollectionItemDAL.findOne({ + pkiCollectionId: collectionId, + id: itemId + }); + + if (!pkiCollectionItem) throw new NotFoundError({ message: "PKI collection item not found" }); + + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + pkiCollection.projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionActions.Delete, + ProjectPermissionSub.PkiCollections + ); + + pkiCollectionItem = await pkiCollectionItemDAL.deleteById(itemId); + + return { + pkiCollection, + pkiCollectionItem: transformPkiCollectionItem(pkiCollectionItem) + }; + }; + + return { + createPkiCollection, + getPkiCollectionById, + updatePkiCollection, + deletePkiCollection, + getPkiCollectionItems, + addItemToPkiCollection, + removeItemFromPkiCollection + }; +}; diff --git a/backend/src/services/pki-collection/pki-collection-types.ts b/backend/src/services/pki-collection/pki-collection-types.ts new file mode 100644 index 000000000..e82ca31d0 --- /dev/null +++ b/backend/src/services/pki-collection/pki-collection-types.ts @@ -0,0 +1,48 @@ +import { TProjectPermission } from "@app/lib/types"; + +export type TCreatePkiCollectionDTO = { + name: string; + description: string; +} & TProjectPermission; + +export type TGetPkiCollectionByIdDTO = { + collectionId: string; +} & Omit; + +export type TUpdatePkiCollectionDTO = { + collectionId: string; + name?: string; + description?: string; +} & Omit; + +export type TDeletePkiCollectionDTO = { + collectionId: string; +} & Omit; + +export enum PkiItemType { + CERTIFICATE = "certificate", + CA = "ca" +} + +export const pkiItemTypeToNameMap: { [K in PkiItemType]: string } = { + [PkiItemType.CA]: "CA", + [PkiItemType.CERTIFICATE]: "Certificate" +}; + +export type TGetPkiCollectionItems = { + collectionId: string; + type?: PkiItemType; + offset: number; + limit: number; +} & Omit; + +export type TAddItemToPkiCollectionDTO = { + collectionId: string; + type: PkiItemType; + itemId: string; +} & Omit; + +export type TRemoveItemFromPkiCollectionDTO = { + collectionId: string; + itemId: string; +} & Omit; diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.ts index fd22349db..9416a66a9 100644 --- a/backend/src/services/project/project-service.ts +++ b/backend/src/services/project/project-service.ts @@ -22,6 +22,8 @@ import { TIdentityProjectMembershipRoleDALFactory } from "../identity-project/id import { TKmsServiceFactory } from "../kms/kms-service"; import { TOrgDALFactory } from "../org/org-dal"; import { TOrgServiceFactory } from "../org/org-service"; +import { TPkiAlertDALFactory } from "../pki-alert/pki-alert-dal"; +import { TPkiCollectionDALFactory } from "../pki-collection/pki-collection-dal"; import { TProjectBotDALFactory } from "../project-bot/project-bot-dal"; import { TProjectEnvDALFactory } from "../project-env/project-env-dal"; import { TProjectKeyDALFactory } from "../project-key/project-key-dal"; @@ -37,6 +39,7 @@ import { TDeleteProjectDTO, TGetProjectDTO, TGetProjectKmsKey, + TListProjectAlertsDTO, TListProjectCasDTO, TListProjectCertsDTO, TLoadProjectKmsBackupDTO, @@ -70,6 +73,8 @@ type TProjectServiceFactoryDep = { projectUserMembershipRoleDAL: Pick; certificateAuthorityDAL: Pick; certificateDAL: Pick; + pkiAlertDAL: Pick; + pkiCollectionDAL: Pick; permissionService: TPermissionServiceFactory; orgService: Pick; licenseService: Pick; @@ -107,6 +112,8 @@ export const projectServiceFactory = ({ identityProjectMembershipRoleDAL, certificateAuthorityDAL, certificateDAL, + pkiCollectionDAL, + pkiAlertDAL, keyStore, kmsService, projectBotDAL @@ -676,6 +683,60 @@ export const projectServiceFactory = ({ }; }; + /** + * Return list of (PKI) alerts configured for project + */ + const listProjectAlerts = async ({ + projectId, + actor, + actorId, + actorAuthMethod, + actorOrgId + }: TListProjectAlertsDTO) => { + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts); + + const alerts = await pkiAlertDAL.find({ projectId }); + + return { + alerts + }; + }; + + /** + * Return list of PKI collections for project + */ + const listProjectPkiCollections = async ({ + projectId, + actor, + actorId, + actorAuthMethod, + actorOrgId + }: TListProjectAlertsDTO) => { + const { permission } = await permissionService.getProjectPermission( + actor, + actorId, + projectId, + actorAuthMethod, + actorOrgId + ); + + ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiCollections); + + const pkiCollections = await pkiCollectionDAL.find({ projectId }); + + return { + pkiCollections + }; + }; + const updateProjectKmsKey = async ({ projectId, kms, @@ -794,6 +855,8 @@ export const projectServiceFactory = ({ upgradeProject, listProjectCas, listProjectCertificates, + listProjectAlerts, + listProjectPkiCollections, updateVersionLimit, updateAuditLogsRetention, updateProjectKmsKey, diff --git a/backend/src/services/project/project-types.ts b/backend/src/services/project/project-types.ts index 1c2279c7a..ac53b3f71 100644 --- a/backend/src/services/project/project-types.ts +++ b/backend/src/services/project/project-types.ts @@ -106,6 +106,8 @@ export type TListProjectCertsDTO = { commonName?: string; } & Omit; +export type TListProjectAlertsDTO = TProjectPermission; + export type TUpdateProjectKmsDTO = { kms: { type: KmsType.Internal } | { type: KmsType.External; kmsId: string }; } & TProjectPermission; diff --git a/backend/src/services/smtp/smtp-service.ts b/backend/src/services/smtp/smtp-service.ts index 95407d0b0..94d84b98c 100644 --- a/backend/src/services/smtp/smtp-service.ts +++ b/backend/src/services/smtp/smtp-service.ts @@ -31,7 +31,8 @@ export enum SmtpTemplates { ResetPassword = "passwordReset.handlebars", SecretLeakIncident = "secretLeakIncident.handlebars", WorkspaceInvite = "workspaceInvitation.handlebars", - ScimUserProvisioned = "scimUserProvisioned.handlebars" + ScimUserProvisioned = "scimUserProvisioned.handlebars", + PkiExpirationAlert = "pkiExpirationAlert.handlebars" } export enum SmtpHost { diff --git a/backend/src/services/smtp/templates/pkiExpirationAlert.handlebars b/backend/src/services/smtp/templates/pkiExpirationAlert.handlebars new file mode 100644 index 000000000..77d2543ae --- /dev/null +++ b/backend/src/services/smtp/templates/pkiExpirationAlert.handlebars @@ -0,0 +1,31 @@ + + + + + Infisical CA/Certificate expiration notice + + +

Hello,

+

This is an automated alert for "{{alertName}}" triggered for CAs/Certificates expiring in + {{alertBeforeDays}} + days.

+ +

Expiring Items:

+
    + {{#each items}} +
  • + {{type}}: + {{friendlyName}} +
    Serial Number: + {{serialNumber}} +
    Expires On: + {{expiryDate}} +
  • + {{/each}} +
+ +

Please take necessary actions to renew these items before they expire.

+ +

For more details, please log in to your Infisical account and check your PKI management section.

+ + \ No newline at end of file diff --git a/docs/api-reference/endpoints/pki-alerts/create.mdx b/docs/api-reference/endpoints/pki-alerts/create.mdx new file mode 100644 index 000000000..458f0cd48 --- /dev/null +++ b/docs/api-reference/endpoints/pki-alerts/create.mdx @@ -0,0 +1,4 @@ +--- +title: "Create" +openapi: "POST /api/v1/pki/alerts" +--- diff --git a/docs/api-reference/endpoints/pki-alerts/delete.mdx b/docs/api-reference/endpoints/pki-alerts/delete.mdx new file mode 100644 index 000000000..c0918d1fe --- /dev/null +++ b/docs/api-reference/endpoints/pki-alerts/delete.mdx @@ -0,0 +1,4 @@ +--- +title: "Delete" +openapi: "DELETE /api/v1/pki/alerts/{alertId}" +--- diff --git a/docs/api-reference/endpoints/pki-alerts/read.mdx b/docs/api-reference/endpoints/pki-alerts/read.mdx new file mode 100644 index 000000000..928afdbc5 --- /dev/null +++ b/docs/api-reference/endpoints/pki-alerts/read.mdx @@ -0,0 +1,4 @@ +--- +title: "Retrieve" +openapi: "GET /api/v1/pki/alerts/{alertId}" +--- diff --git a/docs/api-reference/endpoints/pki-alerts/update.mdx b/docs/api-reference/endpoints/pki-alerts/update.mdx new file mode 100644 index 000000000..829f8c57b --- /dev/null +++ b/docs/api-reference/endpoints/pki-alerts/update.mdx @@ -0,0 +1,4 @@ +--- +title: "Update" +openapi: "PATCH /api/v1/pki/alerts/{alertId}" +--- diff --git a/docs/api-reference/endpoints/pki-collections/add-item.mdx b/docs/api-reference/endpoints/pki-collections/add-item.mdx new file mode 100644 index 000000000..7a7da9c2e --- /dev/null +++ b/docs/api-reference/endpoints/pki-collections/add-item.mdx @@ -0,0 +1,4 @@ +--- +title: "Add Collection Item" +openapi: "POST /api/v1/pki/collections/{collectionId}/items" +--- diff --git a/docs/api-reference/endpoints/pki-collections/create.mdx b/docs/api-reference/endpoints/pki-collections/create.mdx new file mode 100644 index 000000000..7211b622c --- /dev/null +++ b/docs/api-reference/endpoints/pki-collections/create.mdx @@ -0,0 +1,4 @@ +--- +title: "Create" +openapi: "POST /api/v1/pki/collections" +--- diff --git a/docs/api-reference/endpoints/pki-collections/delete-item.mdx b/docs/api-reference/endpoints/pki-collections/delete-item.mdx new file mode 100644 index 000000000..e5805618b --- /dev/null +++ b/docs/api-reference/endpoints/pki-collections/delete-item.mdx @@ -0,0 +1,4 @@ +--- +title: "Delete Collection Item" +openapi: "DELETE /api/v1/pki/collections/{collectionId}/items/{collectionItemId}" +--- diff --git a/docs/api-reference/endpoints/pki-collections/delete.mdx b/docs/api-reference/endpoints/pki-collections/delete.mdx new file mode 100644 index 000000000..46e67bc4f --- /dev/null +++ b/docs/api-reference/endpoints/pki-collections/delete.mdx @@ -0,0 +1,4 @@ +--- +title: "Delete" +openapi: "DELETE /api/v1/pki/collections/{collectionId}" +--- diff --git a/docs/api-reference/endpoints/pki-collections/list-items.mdx b/docs/api-reference/endpoints/pki-collections/list-items.mdx new file mode 100644 index 000000000..dc2e1f04b --- /dev/null +++ b/docs/api-reference/endpoints/pki-collections/list-items.mdx @@ -0,0 +1,4 @@ +--- +title: "Retrieve" +openapi: "GET /api/v1/pki/collections/{collectionId}/items" +--- diff --git a/docs/api-reference/endpoints/pki-collections/read.mdx b/docs/api-reference/endpoints/pki-collections/read.mdx new file mode 100644 index 000000000..de83f7996 --- /dev/null +++ b/docs/api-reference/endpoints/pki-collections/read.mdx @@ -0,0 +1,4 @@ +--- +title: "Retrieve" +openapi: "GET /api/v1/pki/collections/{collectionId}" +--- diff --git a/docs/api-reference/endpoints/pki-collections/update.mdx b/docs/api-reference/endpoints/pki-collections/update.mdx new file mode 100644 index 000000000..7d24214e0 --- /dev/null +++ b/docs/api-reference/endpoints/pki-collections/update.mdx @@ -0,0 +1,4 @@ +--- +title: "Update" +openapi: "PATCH /api/v1/pki/collections/{collectionId}" +--- diff --git a/docs/documentation/platform/pki/alerting.mdx b/docs/documentation/platform/pki/alerting.mdx new file mode 100644 index 000000000..158c47877 --- /dev/null +++ b/docs/documentation/platform/pki/alerting.mdx @@ -0,0 +1,149 @@ +--- +title: "Alerting" +description: "Learn how to set up alerting for expiring certificates with Infisical" +--- + +## Concept + +In order to ensure that your certificates are always up-to-date and not expired, you can set up alerting for expiring CA and leaf certificates in Infisical. + +## Workflow + +A typical alerting workflow for expiring certificates consists of the following steps: + +1. Creating a PKI/Certificate collection and adding certificates that you wish to monitor for expiration to it. +2. Creating an alert and binding it to the PKI/Certificate collection. As part of the configuration, you specify when the alert should trigger based on the number of days before certificate expiration and the email addresses of the recipients to notify. + +## Guide to Creating an Alert + + + + + + To create a PKI/Certificate collection, head to your Project > Internal + PKI > Alerting > Certificate Collection and press **Create**. + + ![pki create collection](/images/platform/pki/alerting/collection-create.png) + + Give the collection a name and proceed to create the empty collection. + + ![pki create collection](/images/platform/pki/alerting/collection-create-2.png) + + Next, in the Collection Page, add the certificate authorities and leaf certificates + that you wish to monitor for expiration to the collection. + + ![pki add cert to collection](/images/platform/pki/alerting/collection-add-cert.png) + + + To create an alert, head to your Project > Internal PKI > Alerting > Alerts and press **Create**. + + ![pki create alert](/images/platform/pki/alerting/alert-create.png) + + Here, set the **Certificate Collection** to the PKI/Certificate collection you created in the previous step and fill out details for the alert. + + ![pki create alert](/images/platform/pki/alerting/alert-create-2.png) + + Here's some guidance on each field: + + - Name: A name for the alert. + - Collection Collection: The PKI/Certificate collection to bind the alert to from the previous step. + - Alert Before / Unit: The time before certificate expiration to trigger the alert. + - Emails to Alert: A comma-delimited list of email addresses to notify when the alert triggers. + + Finally, press **Create** to create the alert. + + ![pki alerts](/images/platform/pki/alerting/alerts.png) + + Great! You've successfully created a PKI/Certificate collection and an alert to monitor the expiring certificates in the collection. Once the alert triggers, the specified email addresses will be notified. + + + + + + + + 1.1. To create a PKI/Certificate collection, make an API request to the [Create PKI Collection](/api-reference/endpoints/pki-collections/create) API endpoint. + + ### Sample request + + ```bash Request + curl --location --request POST 'https://app.infisical.com/api/v1/pki/collections' \ + --header 'Authorization: Bearer ' \ + --header 'Content-Type: application/json' \ + --data-raw '{ + "projectId": "", + "name": "My Certificate Collection" + }' + ``` + + ### Sample response + + ```bash Response + { + id: "", + name: "My Certificate Collection", + ... + } + ``` + + 1.2. Next, make an API request to the [Add Collection Item](/api-reference/endpoints/pki-collections/add-item) API endpoint to add a certificate to the collection. + + ### Sample request + + ```bash Request + curl --location --request POST 'https://app.infisical.com/api/v1/pki/collections//items' \ + --header 'Authorization: Bearer ' \ + --header 'Content-Type: application/json' \ + --data-raw '{ + "type": "certificate", + "itemId": "id-of-certificate" + }' + ``` + + ### Sample response + + ```bash Response + { + id: "", + type: "certificate", + itemId: "id-of-certificate" + ... + } + ``` + + + To create an alert, make an API request to the [Create Alert](/api-reference/endpoints/pki-alerts/create) API endpoint, specifying the PKI/Certificate collection to bind the alert to, the alert configuration, and the email addresses to notify. + + ### Sample request + + ```bash Request + curl --location --request POST 'https://app.infisical.com/api/v1/pki/alerts' \ + --header 'Authorization: Bearer ' \ + --header 'Content-Type: application/json' \ + --data-raw '{ + "projectId": "", + "pkiCollectionId": "", + "name": "My Alert", + "alertBeforeDays": 30, + "emails": ["johndoe@gmail.com", "janedoe@gmail.com"] + }' + ``` + + ### Sample response + + ```bash Response + { + id: "", + name: "My Alert", + alertBeforeDays: 30, + recipientEmails: "johndoe@gmail.com,janedoe@gmail.com" + ... + } + ``` + + Great! You've successfully created a PKI/Certificate collection and an alert to monitor the expiring certificate in the collection. Once the alert triggers, the specified email addresses will be notified. + + + + + diff --git a/docs/images/platform/pki/alerting/alert-create-2.png b/docs/images/platform/pki/alerting/alert-create-2.png new file mode 100644 index 000000000..812f253f8 Binary files /dev/null and b/docs/images/platform/pki/alerting/alert-create-2.png differ diff --git a/docs/images/platform/pki/alerting/alert-create.png b/docs/images/platform/pki/alerting/alert-create.png new file mode 100644 index 000000000..4a7b3227f Binary files /dev/null and b/docs/images/platform/pki/alerting/alert-create.png differ diff --git a/docs/images/platform/pki/alerting/alerts.png b/docs/images/platform/pki/alerting/alerts.png new file mode 100644 index 000000000..c7a5096ce Binary files /dev/null and b/docs/images/platform/pki/alerting/alerts.png differ diff --git a/docs/images/platform/pki/alerting/collection-add-cert.png b/docs/images/platform/pki/alerting/collection-add-cert.png new file mode 100644 index 000000000..6300cc892 Binary files /dev/null and b/docs/images/platform/pki/alerting/collection-add-cert.png differ diff --git a/docs/images/platform/pki/alerting/collection-create-2.png b/docs/images/platform/pki/alerting/collection-create-2.png new file mode 100644 index 000000000..53378ef05 Binary files /dev/null and b/docs/images/platform/pki/alerting/collection-create-2.png differ diff --git a/docs/images/platform/pki/alerting/collection-create.png b/docs/images/platform/pki/alerting/collection-create.png new file mode 100644 index 000000000..7c4883201 Binary files /dev/null and b/docs/images/platform/pki/alerting/collection-create.png differ diff --git a/docs/mint.json b/docs/mint.json index defe3c201..123b33bb5 100644 --- a/docs/mint.json +++ b/docs/mint.json @@ -107,7 +107,8 @@ "pages": [ "documentation/platform/pki/overview", "documentation/platform/pki/private-ca", - "documentation/platform/pki/certificates" + "documentation/platform/pki/certificates", + "documentation/platform/pki/alerting" ] }, { @@ -702,6 +703,27 @@ "api-reference/endpoints/certificates/delete", "api-reference/endpoints/certificates/cert-body" ] + }, + { + "group": "Certificate Collections", + "pages": [ + "api-reference/endpoints/pki-collections/create", + "api-reference/endpoints/pki-collections/read", + "api-reference/endpoints/pki-collections/update", + "api-reference/endpoints/pki-collections/delete", + "api-reference/endpoints/pki-collections/add-item", + "api-reference/endpoints/pki-collections/list-items", + "api-reference/endpoints/pki-collections/delete-item" + ] + }, + { + "group": "PKI Alerting", + "pages": [ + "api-reference/endpoints/pki-alerts/create", + "api-reference/endpoints/pki-alerts/read", + "api-reference/endpoints/pki-alerts/update", + "api-reference/endpoints/pki-alerts/delete" + ] } ] }, diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts index 557b3cd17..c307688d6 100644 --- a/frontend/src/context/ProjectPermissionContext/types.ts +++ b/frontend/src/context/ProjectPermissionContext/types.ts @@ -28,6 +28,8 @@ export enum ProjectPermissionSub { Identity = "identity", CertificateAuthorities = "certificate-authorities", Certificates = "certificates", + PkiAlerts = "pki-alerts", + PkiCollections = "pki-collections", Kms = "kms" } @@ -57,6 +59,8 @@ export type ProjectPermissionSet = | [ProjectPermissionActions, ProjectPermissionSub.SecretRotation] | [ProjectPermissionActions, ProjectPermissionSub.CertificateAuthorities] | [ProjectPermissionActions, ProjectPermissionSub.Certificates] + | [ProjectPermissionActions, ProjectPermissionSub.PkiAlerts] + | [ProjectPermissionActions, ProjectPermissionSub.PkiCollections] | [ProjectPermissionActions.Delete, ProjectPermissionSub.Workspace] | [ProjectPermissionActions.Edit, ProjectPermissionSub.Workspace] | [ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback] diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx index 819c36c20..8aadda2d8 100644 --- a/frontend/src/hooks/api/auditLogs/constants.tsx +++ b/frontend/src/hooks/api/auditLogs/constants.tsx @@ -57,6 +57,17 @@ export const eventToNameMap: { [K in EventType]: string } = { [EventType.DELETE_CERT]: "Delete certificate", [EventType.REVOKE_CERT]: "Revoke certificate", [EventType.GET_CERT_BODY]: "Get certificate body", + [EventType.CREATE_PKI_ALERT]: "Create PKI alert", + [EventType.GET_PKI_ALERT]: "Get PKI alert", + [EventType.UPDATE_PKI_ALERT]: "Update PKI alert", + [EventType.DELETE_PKI_ALERT]: "Delete PKI alert", + [EventType.CREATE_PKI_COLLECTION]: "Create PKI collection", + [EventType.GET_PKI_COLLECTION]: "Get PKI collection", + [EventType.UPDATE_PKI_COLLECTION]: "Update PKI collection", + [EventType.DELETE_PKI_COLLECTION]: "Delete PKI collection", + [EventType.GET_PKI_COLLECTION_ITEMS]: "Get PKI collection items", + [EventType.ADD_PKI_COLLECTION_ITEM]: "Add PKI collection item", + [EventType.DELETE_PKI_COLLECTION_ITEM]: "Delete PKI collection item", [EventType.ORG_ADMIN_ACCESS_PROJECT]: "Org admin accessed project" }; diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx index 94963f640..a6a2ada93 100644 --- a/frontend/src/hooks/api/auditLogs/enums.tsx +++ b/frontend/src/hooks/api/auditLogs/enums.tsx @@ -71,5 +71,16 @@ export enum EventType { DELETE_CERT = "delete-cert", REVOKE_CERT = "revoke-cert", GET_CERT_BODY = "get-cert-body", + CREATE_PKI_ALERT = "create-pki-alert", + GET_PKI_ALERT = "get-pki-alert", + UPDATE_PKI_ALERT = "update-pki-alert", + DELETE_PKI_ALERT = "delete-pki-alert", + CREATE_PKI_COLLECTION = "create-pki-collection", + GET_PKI_COLLECTION = "get-pki-collection", + UPDATE_PKI_COLLECTION = "update-pki-collection", + DELETE_PKI_COLLECTION = "delete-pki-collection", + GET_PKI_COLLECTION_ITEMS = "get-pki-collection-items", + ADD_PKI_COLLECTION_ITEM = "add-pki-collection-item", + DELETE_PKI_COLLECTION_ITEM = "delete-pki-collection-item", ORG_ADMIN_ACCESS_PROJECT = "org-admin-accessed-project" } diff --git a/frontend/src/hooks/api/auditLogs/types.tsx b/frontend/src/hooks/api/auditLogs/types.tsx index 1d80d6128..0a34186f6 100644 --- a/frontend/src/hooks/api/auditLogs/types.tsx +++ b/frontend/src/hooks/api/auditLogs/types.tsx @@ -1,5 +1,6 @@ import { CaStatus } from "../ca"; import { IdentityTrustedIp } from "../identities/types"; +import { PkiItemType } from "../pkiCollections/constants"; import { ActorType, EventType, UserAgentType } from "./enums"; interface UserActorMetadata { @@ -579,6 +580,95 @@ interface GetCertBody { }; } +interface CreatePkiAlert { + type: EventType.CREATE_PKI_ALERT; + metadata: { + pkiAlertId: string; + pkiCollectionId: string; + name: string; + alertBeforeDays: number; + recipientEmails: string; + }; +} +interface GetPkiAlert { + type: EventType.GET_PKI_ALERT; + metadata: { + pkiAlertId: string; + }; +} + +interface UpdatePkiAlert { + type: EventType.UPDATE_PKI_ALERT; + metadata: { + pkiAlertId: string; + pkiCollectionId?: string; + name?: string; + alertBeforeDays?: number; + recipientEmails?: string; + }; +} +interface DeletePkiAlert { + type: EventType.DELETE_PKI_ALERT; + metadata: { + pkiAlertId: string; + }; +} + +interface CreatePkiCollection { + type: EventType.CREATE_PKI_COLLECTION; + metadata: { + pkiCollectionId: string; + name: string; + }; +} + +interface GetPkiCollection { + type: EventType.GET_PKI_COLLECTION; + metadata: { + pkiCollectionId: string; + }; +} + +interface UpdatePkiCollection { + type: EventType.UPDATE_PKI_COLLECTION; + metadata: { + pkiCollectionId: string; + name?: string; + }; +} + +interface DeletePkiCollection { + type: EventType.DELETE_PKI_COLLECTION; + metadata: { + pkiCollectionId: string; + }; +} + +interface GetPkiCollectionItems { + type: EventType.GET_PKI_COLLECTION_ITEMS; + metadata: { + pkiCollectionId: string; + }; +} + +interface AddPkiCollectionItem { + type: EventType.ADD_PKI_COLLECTION_ITEM; + metadata: { + pkiCollectionItemId: string; + pkiCollectionId: string; + type: PkiItemType; + itemId: string; + }; +} + +interface DeletePkiCollectionItem { + type: EventType.DELETE_PKI_COLLECTION_ITEM; + metadata: { + pkiCollectionItemId: string; + pkiCollectionId: string; + }; +} + interface OrgAdminAccessProjectEvent { type: EventType.ORG_ADMIN_ACCESS_PROJECT; metadata: { @@ -646,6 +736,17 @@ export type Event = | DeleteCert | RevokeCert | GetCertBody + | CreatePkiAlert + | GetPkiAlert + | UpdatePkiAlert + | DeletePkiAlert + | CreatePkiCollection + | GetPkiCollection + | UpdatePkiCollection + | DeletePkiCollection + | GetPkiCollectionItems + | AddPkiCollectionItem + | DeletePkiCollectionItem | OrgAdminAccessProjectEvent; export type AuditLog = { diff --git a/frontend/src/hooks/api/ca/constants.tsx b/frontend/src/hooks/api/ca/constants.tsx index e77dfe2b8..9bb7b89d5 100644 --- a/frontend/src/hooks/api/ca/constants.tsx +++ b/frontend/src/hooks/api/ca/constants.tsx @@ -11,7 +11,7 @@ export const caStatusToNameMap: { [K in CaStatus]: string } = { [CaStatus.PENDING_CERTIFICATE]: "Pending Certificate" }; -export const getStatusBadgeVariant = (status: CaStatus) => { +export const getCaStatusBadgeVariant = (status: CaStatus) => { switch (status) { case CaStatus.ACTIVE: return "success"; diff --git a/frontend/src/hooks/api/ca/types.ts b/frontend/src/hooks/api/ca/types.ts index 7513070c8..692714871 100644 --- a/frontend/src/hooks/api/ca/types.ts +++ b/frontend/src/hooks/api/ca/types.ts @@ -80,6 +80,7 @@ export type TImportCaCertificateResponse = { export type TCreateCertificateDTO = { projectSlug: string; caId: string; + pkiCollectionId?: string; friendlyName?: string; commonName: string; altNames: string; // sans diff --git a/frontend/src/hooks/api/certificates/constants.tsx b/frontend/src/hooks/api/certificates/constants.tsx index e5a9b7a43..2f2972bbc 100644 --- a/frontend/src/hooks/api/certificates/constants.tsx +++ b/frontend/src/hooks/api/certificates/constants.tsx @@ -1,10 +1,21 @@ -import { CertKeyAlgorithm, CertStatus,CrlReason } from "./enums"; +import { CertKeyAlgorithm, CertStatus, CrlReason } from "./enums"; export const certStatusToNameMap: { [K in CertStatus]: string } = { [CertStatus.ACTIVE]: "Active", [CertStatus.REVOKED]: "Revoked" }; +export const getCertStatusBadgeVariant = (status: CertStatus) => { + switch (status) { + case CertStatus.ACTIVE: + return "success"; + case CertStatus.REVOKED: + return "danger"; + default: + return "primary"; + } +}; + export const certKeyAlgorithmToNameMap: { [K in CertKeyAlgorithm]: string } = { [CertKeyAlgorithm.RSA_2048]: "RSA 2048", [CertKeyAlgorithm.RSA_4096]: "RSA 4096", diff --git a/frontend/src/hooks/api/index.tsx b/frontend/src/hooks/api/index.tsx index 5cbd1fb27..94037cb62 100644 --- a/frontend/src/hooks/api/index.tsx +++ b/frontend/src/hooks/api/index.tsx @@ -21,6 +21,8 @@ export * from "./ldapConfig"; export * from "./oidcConfig"; export * from "./orgAdmin"; export * from "./organization"; +export * from "./pkiAlerts"; +export * from "./pkiCollections"; export * from "./projectUserAdditionalPrivilege"; export * from "./rateLimit"; export * from "./roles"; diff --git a/frontend/src/hooks/api/pkiAlerts/index.tsx b/frontend/src/hooks/api/pkiAlerts/index.tsx new file mode 100644 index 000000000..f88f71679 --- /dev/null +++ b/frontend/src/hooks/api/pkiAlerts/index.tsx @@ -0,0 +1,2 @@ +export { useCreatePkiAlert, useDeletePkiAlert, useUpdatePkiAlert } from "./mutations"; +export { useGetPkiAlertById } from "./queries"; diff --git a/frontend/src/hooks/api/pkiAlerts/mutations.tsx b/frontend/src/hooks/api/pkiAlerts/mutations.tsx new file mode 100644 index 000000000..b8406e95d --- /dev/null +++ b/frontend/src/hooks/api/pkiAlerts/mutations.tsx @@ -0,0 +1,51 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; + +import { apiRequest } from "@app/config/request"; + +import { workspaceKeys } from "../workspace/queries"; +import { pkiAlertKeys } from "./queries"; +import { TCreatePkiAlertDTO, TDeletePkiAlertDTO, TPkiAlert, TUpdatePkiAlertDTO } from "./types"; + +export const useCreatePkiAlert = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async (body) => { + const { data: alert } = await apiRequest.post("/api/v1/pki/alerts", body); + return alert; + }, + onSuccess: (_, { projectId }) => { + queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiAlerts(projectId)); + } + }); +}; + +export const useUpdatePkiAlert = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async ({ alertId, ...body }) => { + const { data: alert } = await apiRequest.patch( + `/api/v1/pki/alerts/${alertId}`, + body + ); + return alert; + }, + onSuccess: (_, { projectId, alertId }) => { + queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiAlerts(projectId)); + queryClient.invalidateQueries(pkiAlertKeys.getPkiAlertById(alertId)); + } + }); +}; + +export const useDeletePkiAlert = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async ({ alertId }) => { + const { data: alert } = await apiRequest.delete(`/api/v1/pki/alerts/${alertId}`); + return alert; + }, + onSuccess: (_, { projectId, alertId }) => { + queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiAlerts(projectId)); + queryClient.invalidateQueries(pkiAlertKeys.getPkiAlertById(alertId)); + } + }); +}; diff --git a/frontend/src/hooks/api/pkiAlerts/queries.tsx b/frontend/src/hooks/api/pkiAlerts/queries.tsx new file mode 100644 index 000000000..db324e96d --- /dev/null +++ b/frontend/src/hooks/api/pkiAlerts/queries.tsx @@ -0,0 +1,20 @@ +import { useQuery } from "@tanstack/react-query"; + +import { apiRequest } from "@app/config/request"; + +import { TPkiAlert } from "./types"; + +export const pkiAlertKeys = { + getPkiAlertById: (alertId: string) => [{ alertId }, "alert"] +}; + +export const useGetPkiAlertById = (alertId: string) => { + return useQuery({ + queryKey: pkiAlertKeys.getPkiAlertById(alertId), + queryFn: async () => { + const { data: alert } = await apiRequest.get(`/api/v1/pki/alerts/${alertId}`); + return alert; + }, + enabled: Boolean(alertId) + }); +}; diff --git a/frontend/src/hooks/api/pkiAlerts/types.ts b/frontend/src/hooks/api/pkiAlerts/types.ts new file mode 100644 index 000000000..744c4e598 --- /dev/null +++ b/frontend/src/hooks/api/pkiAlerts/types.ts @@ -0,0 +1,32 @@ +export type TPkiAlert = { + id: string; + name: string; + projectId: string; + pkiCollectionId: string; + alertBeforeDays: number; + recipientEmails: string; + createdAt: string; + updatedAt: string; +}; + +export type TCreatePkiAlertDTO = { + projectId: string; + name: string; + pkiCollectionId: string; + alertBeforeDays: number; + emails: string[]; +}; + +export type TUpdatePkiAlertDTO = { + alertId: string; + projectId: string; + pkiCollectionId?: string; + name?: string; + alertBeforeDays?: number; + emails?: string[]; +}; + +export type TDeletePkiAlertDTO = { + alertId: string; + projectId: string; +}; diff --git a/frontend/src/hooks/api/pkiCollections/constants.tsx b/frontend/src/hooks/api/pkiCollections/constants.tsx new file mode 100644 index 000000000..c103dc386 --- /dev/null +++ b/frontend/src/hooks/api/pkiCollections/constants.tsx @@ -0,0 +1,9 @@ +export enum PkiItemType { + CERTIFICATE = "certificate", + CA = "ca" +} + +export const pkiItemTypeToNameMap: { [K in PkiItemType]: string } = { + [PkiItemType.CA]: "CA", + [PkiItemType.CERTIFICATE]: "Certificate" +}; diff --git a/frontend/src/hooks/api/pkiCollections/index.tsx b/frontend/src/hooks/api/pkiCollections/index.tsx new file mode 100644 index 000000000..cf638d8fa --- /dev/null +++ b/frontend/src/hooks/api/pkiCollections/index.tsx @@ -0,0 +1,7 @@ +export { + useAddItemToPkiCollection, + useCreatePkiCollection, + useDeletePkiCollection, + useRemoveItemFromPkiCollection, + useUpdatePkiCollection} from "./mutations"; +export { useGetPkiCollectionById, useListPkiCollectionItems } from "./queries"; diff --git a/frontend/src/hooks/api/pkiCollections/mutations.tsx b/frontend/src/hooks/api/pkiCollections/mutations.tsx new file mode 100644 index 000000000..df66dd8e2 --- /dev/null +++ b/frontend/src/hooks/api/pkiCollections/mutations.tsx @@ -0,0 +1,97 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; + +import { apiRequest } from "@app/config/request"; + +import { workspaceKeys } from "../workspace/queries"; +import { pkiCollectionKeys } from "./queries"; +import { + TAddItemToPkiCollectionDTO, + TCreatePkiCollectionDTO, + TDeletePkiCollectionDTO, + TPkiCollection, + TPkiCollectionItem, + TRemoveItemFromPkiCollectionDTO, + TUpdatePkiCollectionTO} from "./types"; + +export const useCreatePkiCollection = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async (body) => { + const { data: pkiCollection } = await apiRequest.post( + "/api/v1/pki/collections", + body + ); + return pkiCollection; + }, + onSuccess: (_, { projectId }) => { + queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiCollections(projectId)); + } + }); +}; + +export const useUpdatePkiCollection = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async ({ collectionId, ...body }) => { + const { data: pkiCollection } = await apiRequest.patch( + `/api/v1/pki/collections/${collectionId}`, + body + ); + return pkiCollection; + }, + onSuccess: (_, { projectId, collectionId }) => { + queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiCollections(projectId)); + queryClient.invalidateQueries(pkiCollectionKeys.getPkiCollectionById(collectionId)); + } + }); +}; + +export const useDeletePkiCollection = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async ({ collectionId }) => { + const { data: pkiCollection } = await apiRequest.delete( + `/api/v1/pki/collections/${collectionId}` + ); + return pkiCollection; + }, + onSuccess: (_, { projectId, collectionId }) => { + queryClient.invalidateQueries(workspaceKeys.getWorkspacePkiCollections(projectId)); + queryClient.invalidateQueries(pkiCollectionKeys.getPkiCollectionById(collectionId)); + } + }); +}; + +export const useAddItemToPkiCollection = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async ({ collectionId, type, itemId }) => { + const { data: pkiCollectionItem } = await apiRequest.post( + `/api/v1/pki/collections/${collectionId}/items`, + { + type, + itemId + } + ); + return pkiCollectionItem; + }, + onSuccess: (_, { collectionId }) => { + queryClient.invalidateQueries(pkiCollectionKeys.getPkiCollectionItems(collectionId)); + } + }); +}; + +export const useRemoveItemFromPkiCollection = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async ({ collectionId, itemId }) => { + const { data: pkiCollectionItem } = await apiRequest.delete( + `/api/v1/pki/collections/${collectionId}/items/${itemId}` + ); + return pkiCollectionItem; + }, + onSuccess: (_, { collectionId }) => { + queryClient.invalidateQueries(pkiCollectionKeys.getPkiCollectionItems(collectionId)); + } + }); +}; diff --git a/frontend/src/hooks/api/pkiCollections/queries.tsx b/frontend/src/hooks/api/pkiCollections/queries.tsx new file mode 100644 index 000000000..109862767 --- /dev/null +++ b/frontend/src/hooks/api/pkiCollections/queries.tsx @@ -0,0 +1,85 @@ +import { useQuery } from "@tanstack/react-query"; + +import { apiRequest } from "@app/config/request"; + +import { PkiItemType } from "./constants"; +import { TPkiCollection, TPkiCollectionItem } from "./types"; + +export const pkiCollectionKeys = { + getPkiCollectionById: (collectionId: string) => [{ collectionId }, "pki-collection"] as const, + getPkiCollectionItems: (collectionId: string) => + [{ collectionId }, "pki-collection-items"] as const, + specificPkiCollectionItems: ({ + collectionId, + type, + offset, + limit + }: { + collectionId: string; + type?: PkiItemType; + offset: number; + limit: number; + }) => + [ + ...pkiCollectionKeys.getPkiCollectionItems(collectionId), + { offset, limit, type }, + "pki-collection-items-2" + ] as const +}; + +export const useGetPkiCollectionById = (collectionId: string) => { + return useQuery({ + queryKey: pkiCollectionKeys.getPkiCollectionById(collectionId), + queryFn: async () => { + const { data: pkiCollection } = await apiRequest.get( + `/api/v1/pki/collections/${collectionId}` + ); + return pkiCollection; + }, + enabled: Boolean(collectionId) + }); +}; + +export const useListPkiCollectionItems = ({ + collectionId, + type, + offset, + limit +}: { + collectionId: string; + type?: PkiItemType; + offset: number; + limit: number; +}) => { + return useQuery({ + queryKey: pkiCollectionKeys.specificPkiCollectionItems({ + collectionId, + offset, + limit, + type + }), + queryFn: async () => { + const params = new URLSearchParams({ + offset: String(offset), + limit: String(limit), + ...(type ? { type } : {}) + }); + + const { + data: { collectionItems, totalCount } + } = await apiRequest.get<{ + collectionItems: (TPkiCollectionItem & { + notBefore: string; + notAfter: string; + friendlyName: string; + })[]; + totalCount: number; + }>(`/api/v1/pki/collections/${collectionId}/items`, { + params + }); + + return { collectionItems, totalCount }; + }, + enabled: Boolean(collectionId) + }); +}; diff --git a/frontend/src/hooks/api/pkiCollections/types.ts b/frontend/src/hooks/api/pkiCollections/types.ts new file mode 100644 index 000000000..98a98d520 --- /dev/null +++ b/frontend/src/hooks/api/pkiCollections/types.ts @@ -0,0 +1,46 @@ +export type TPkiCollection = { + id: string; + name: string; + description: string; + projectId: string; + createdAt: string; + updatedAt: string; +}; + +export type TCreatePkiCollectionDTO = { + projectId: string; + name: string; + description: string; +}; + +export type TUpdatePkiCollectionTO = { + collectionId: string; + projectId: string; + name?: string; + description?: string; +}; + +export type TDeletePkiCollectionDTO = { + collectionId: string; + projectId: string; +}; + +export type TPkiCollectionItem = { + id: string; + collectionId: string; + type: string; + itemId: string; + createdAt: string; + updatedAt: string; +}; + +export type TAddItemToPkiCollectionDTO = { + collectionId: string; + type: string; + itemId: string; +}; + +export type TRemoveItemFromPkiCollectionDTO = { + collectionId: string; + itemId: string; +}; diff --git a/frontend/src/hooks/api/workspace/index.tsx b/frontend/src/hooks/api/workspace/index.tsx index 7b528cfbd..3da83e1b8 100644 --- a/frontend/src/hooks/api/workspace/index.tsx +++ b/frontend/src/hooks/api/workspace/index.tsx @@ -3,7 +3,8 @@ export { useDeleteGroupFromWorkspace, useLeaveProject, useMigrateProjectToV3, - useUpdateGroupWorkspaceRole} from "./mutations"; + useUpdateGroupWorkspaceRole +} from "./mutations"; export { useAddIdentityToWorkspace, useCreateWorkspace, @@ -25,6 +26,8 @@ export { useListWorkspaceCas, useListWorkspaceCertificates, useListWorkspaceGroups, + useListWorkspacePkiAlerts, + useListWorkspacePkiCollections, useNameWorkspaceSecrets, useRenameWorkspace, useToggleAutoCapitalization, diff --git a/frontend/src/hooks/api/workspace/queries.tsx b/frontend/src/hooks/api/workspace/queries.tsx index 57087feb9..d971f06e2 100644 --- a/frontend/src/hooks/api/workspace/queries.tsx +++ b/frontend/src/hooks/api/workspace/queries.tsx @@ -10,6 +10,8 @@ import { identitiesKeys } from "../identities/queries"; import { IdentityMembership } from "../identities/types"; import { IntegrationAuth } from "../integrationAuth/types"; import { TIntegration } from "../integrations/types"; +import { TPkiAlert } from "../pkiAlerts/types"; +import { TPkiCollection } from "../pkiCollections/types"; import { EncryptedSecret } from "../secrets/types"; import { userKeys } from "../users/queries"; import { TWorkspaceUser } from "../users/types"; @@ -62,7 +64,11 @@ export const workspaceKeys = { slug: string; offset: number; limit: number; - }) => [...workspaceKeys.forWorkspaceCertificates(slug), { offset, limit }] as const + }) => [...workspaceKeys.forWorkspaceCertificates(slug), { offset, limit }] as const, + getWorkspacePkiAlerts: (workspaceId: string) => + [{ workspaceId }, "workspace-pki-alerts"] as const, + getWorkspacePkiCollections: (workspaceId: string) => + [{ workspaceId }, "workspace-pki-collections"] as const }; const fetchWorkspaceById = async (workspaceId: string) => { @@ -601,3 +607,35 @@ export const useListWorkspaceCertificates = ({ enabled: Boolean(projectSlug) }); }; + +export const useListWorkspacePkiAlerts = ({ workspaceId }: { workspaceId: string }) => { + return useQuery({ + queryKey: workspaceKeys.getWorkspacePkiAlerts(workspaceId), + queryFn: async () => { + const { + data: { alerts } + } = await apiRequest.get<{ alerts: TPkiAlert[] }>( + `/api/v2/workspace/${workspaceId}/pki-alerts` + ); + + return { alerts }; + }, + enabled: Boolean(workspaceId) + }); +}; + +export const useListWorkspacePkiCollections = ({ workspaceId }: { workspaceId: string }) => { + return useQuery({ + queryKey: workspaceKeys.getWorkspacePkiCollections(workspaceId), + queryFn: async () => { + const { + data: { collections } + } = await apiRequest.get<{ collections: TPkiCollection[] }>( + `/api/v2/workspace/${workspaceId}/pki-collections` + ); + + return { collections }; + }, + enabled: Boolean(workspaceId) + }); +}; diff --git a/frontend/src/pages/project/[id]/pki-collections/[collectionId]/index.tsx b/frontend/src/pages/project/[id]/pki-collections/[collectionId]/index.tsx new file mode 100644 index 000000000..10533fd31 --- /dev/null +++ b/frontend/src/pages/project/[id]/pki-collections/[collectionId]/index.tsx @@ -0,0 +1,20 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { useTranslation } from "react-i18next"; +import Head from "next/head"; + +import { PkiCollectionPage } from "@app/views/Project/PkiCollectionPage"; + +export default function PkiCollection() { + const { t } = useTranslation(); + return ( + <> + + {t("common.head-title", { title: "PKI Collection" })} + + + + + ); +} + +PkiCollection.requireAuth = true; diff --git a/frontend/src/views/Project/AuditLogsPage/components/LogsTableRow.tsx b/frontend/src/views/Project/AuditLogsPage/components/LogsTableRow.tsx index 668b5e5c6..f5e54ab47 100644 --- a/frontend/src/views/Project/AuditLogsPage/components/LogsTableRow.tsx +++ b/frontend/src/views/Project/AuditLogsPage/components/LogsTableRow.tsx @@ -323,6 +323,65 @@ export const LogsTableRow = ({ auditLog }: Props) => {

{`Email: ${event.metadata.email}`}

); + case EventType.CREATE_PKI_ALERT: + case EventType.UPDATE_PKI_ALERT: + return ( + +

{`Alert ID: ${event.metadata.pkiAlertId}`}

+

{`Name: ${event.metadata.name}`}

+

{`Alert Before Days: ${event.metadata.alertBeforeDays}`}

+ + ); + case EventType.GET_PKI_ALERT: + case EventType.DELETE_PKI_ALERT: + return ( + +

{`Alert ID: ${event.metadata.pkiAlertId}`}

+ + ); + case EventType.CREATE_PKI_COLLECTION: + return ( + +

{`Collection ID: ${event.metadata.pkiCollectionId}`}

+

{`Name: ${event.metadata.name}`}

+ + ); + case EventType.UPDATE_PKI_COLLECTION: + return ( + +

{`Collection ID: ${event.metadata.pkiCollectionId}`}

+

{`Name: ${event.metadata.name}`}

+ + ); + case EventType.GET_PKI_COLLECTION: + case EventType.DELETE_PKI_COLLECTION: + return ( + +

{`Collection ID: ${event.metadata.pkiCollectionId}`}

+ + ); + case EventType.GET_PKI_COLLECTION_ITEMS: + return ( + +

{`Collection ID: ${event.metadata.pkiCollectionId}`}

+ + ); + case EventType.ADD_PKI_COLLECTION_ITEM: + return ( + +

{`Collection ID: ${event.metadata.pkiCollectionId}`}

+

{`Collection Item ID: ${event.metadata.pkiCollectionItemId}`}

+

{`Type: ${event.metadata.type}`}

+

{`Item ID: ${event.metadata.itemId}`}

+ + ); + case EventType.DELETE_PKI_COLLECTION_ITEM: + return ( + +

{`Collection ID: ${event.metadata.pkiCollectionId}`}

+

{`Collection Item ID: ${event.metadata.pkiCollectionItemId}`}

+ + ); case EventType.CREATE_CA: case EventType.GET_CA: case EventType.UPDATE_CA: diff --git a/frontend/src/views/Project/CertificatesPage/CertificatesPage.tsx b/frontend/src/views/Project/CertificatesPage/CertificatesPage.tsx index 30e531277..82fa42871 100644 --- a/frontend/src/views/Project/CertificatesPage/CertificatesPage.tsx +++ b/frontend/src/views/Project/CertificatesPage/CertificatesPage.tsx @@ -2,11 +2,12 @@ import { Tab, TabList, TabPanel, Tabs } from "@app/components/v2"; import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context"; import { withProjectPermission } from "@app/hoc"; -import { CaTab, CertificatesTab } from "./components"; +import { CaTab, CertificatesTab,PkiAlertsTab } from "./components"; enum TabSections { Ca = "certificate-authorities", - Certificates = "certificates" + Certificates = "certificates", + Alerting = "alerting" } export const CertificatesPage = withProjectPermission( @@ -19,6 +20,7 @@ export const CertificatesPage = withProjectPermission( Certificates Certificate Authorities + Alerting @@ -26,6 +28,9 @@ export const CertificatesPage = withProjectPermission( + + + diff --git a/frontend/src/views/Project/CertificatesPage/components/CaTab/components/CaTable.tsx b/frontend/src/views/Project/CertificatesPage/components/CaTab/components/CaTable.tsx index f719365eb..2c0bc8706 100644 --- a/frontend/src/views/Project/CertificatesPage/components/CaTab/components/CaTable.tsx +++ b/frontend/src/views/Project/CertificatesPage/components/CaTab/components/CaTable.tsx @@ -39,7 +39,7 @@ import { CaStatus, useListWorkspaceCas } from "@app/hooks/api"; import { caStatusToNameMap, caTypeToNameMap, - getStatusBadgeVariant + getCaStatusBadgeVariant } from "@app/hooks/api/ca/constants"; import { UsePopUpState } from "@app/hooks/usePopUp"; @@ -92,7 +92,7 @@ export const CaTable = ({ handlePopUpOpen }: Props) => { > {ca.friendlyName} - + {caStatusToNameMap[ca.status]} @@ -100,9 +100,6 @@ export const CaTable = ({ handlePopUpOpen }: Props) => {

{ca.notAfter ? format(new Date(ca.notAfter), "yyyy-MM-dd") : "-"}

- {/* - Expires Soon - */}
diff --git a/frontend/src/views/Project/CertificatesPage/components/CertificatesTab/CertificatesTab.tsx b/frontend/src/views/Project/CertificatesPage/components/CertificatesTab/CertificatesTab.tsx index f054e2546..8dcd74348 100644 --- a/frontend/src/views/Project/CertificatesPage/components/CertificatesTab/CertificatesTab.tsx +++ b/frontend/src/views/Project/CertificatesPage/components/CertificatesTab/CertificatesTab.tsx @@ -1,5 +1,6 @@ import { motion } from "framer-motion"; +import { PkiCollectionSection } from "../PkiAlertsTab/components"; import { CertificatesSection } from "./components"; export const CertificatesTab = () => { @@ -11,6 +12,7 @@ export const CertificatesTab = () => { animate={{ opacity: 1, translateX: 0 }} exit={{ opacity: 0, translateX: 30 }} > + ); diff --git a/frontend/src/views/Project/CertificatesPage/components/CertificatesTab/components/CertificateModal.tsx b/frontend/src/views/Project/CertificatesPage/components/CertificatesTab/components/CertificateModal.tsx index 12bd8c47c..973934ce6 100644 --- a/frontend/src/views/Project/CertificatesPage/components/CertificatesTab/components/CertificateModal.tsx +++ b/frontend/src/views/Project/CertificatesPage/components/CertificatesTab/components/CertificateModal.tsx @@ -14,7 +14,13 @@ import { SelectItem } from "@app/components/v2"; import { useWorkspace } from "@app/context"; -import { CaStatus, useCreateCertificate, useGetCert, useListWorkspaceCas } from "@app/hooks/api"; +import { + CaStatus, + useCreateCertificate, + useGetCert, + useListWorkspaceCas, + useListWorkspacePkiCollections +} from "@app/hooks/api"; import { caTypeToNameMap } from "@app/hooks/api/ca/constants"; import { UsePopUpState } from "@app/hooks/usePopUp"; @@ -22,6 +28,7 @@ import { CertificateContent } from "./CertificateContent"; const schema = z.object({ caId: z.string(), + collectionId: z.string().optional(), friendlyName: z.string(), commonName: z.string().trim().min(1), altNames: z.string(), @@ -54,6 +61,10 @@ export const CertificateModal = ({ popUp, handlePopUpToggle }: Props) => { status: CaStatus.ACTIVE }); + const { data } = useListWorkspacePkiCollections({ + workspaceId: currentWorkspace?.id || "" + }); + const { mutateAsync: createCertificate } = useCreateCertificate(); const { @@ -86,13 +97,21 @@ export const CertificateModal = ({ popUp, handlePopUpToggle }: Props) => { } }, [cert]); - const onFormSubmit = async ({ caId, friendlyName, commonName, altNames, ttl }: FormData) => { + const onFormSubmit = async ({ + caId, + collectionId, + friendlyName, + commonName, + altNames, + ttl + }: FormData) => { try { if (!currentWorkspace?.slug) return; const { serialNumber, certificate, certificateChain, privateKey } = await createCertificate({ projectSlug: currentWorkspace.slug, caId, + pkiCollectionId: collectionId, friendlyName, commonName, altNames, @@ -167,6 +186,34 @@ export const CertificateModal = ({ popUp, handlePopUpToggle }: Props) => { )} /> + {!cert && ( + ( + + + + )} + /> + )} { }); return ( -
- - - - - - - - - - - {isLoading && } - {!isLoading && - data?.certificates.map((certificate) => { - return ( - - - - - - - ); - })} - -
Friendly NameStatusValid Until -
{certificate.friendlyName}{certStatusToNameMap[certificate.status]} - {certificate.notAfter - ? format(new Date(certificate.notAfter), "yyyy-MM-dd") - : "-"} - - - -
- - - -
-
- - - {(isAllowed) => ( - - handlePopUpOpen("certificateCert", { - serialNumber: certificate.serialNumber - }) - } - disabled={!isAllowed} - icon={} - > - Export Certificate - - )} - - - {(isAllowed) => ( - - handlePopUpOpen("certificate", { - serialNumber: certificate.serialNumber - }) - } - disabled={!isAllowed} - icon={} - > - View Details - - )} - - - {(isAllowed) => ( - - handlePopUpOpen("revokeCertificate", { - serialNumber: certificate.serialNumber - }) - } - disabled={!isAllowed} - icon={} - > - Revoke Certificate - - )} - - - {(isAllowed) => ( - - handlePopUpOpen("deleteCertificate", { - serialNumber: certificate.serialNumber, - commonName: certificate.commonName - }) - } - disabled={!isAllowed} - icon={} - > - Delete Certificate - - )} - - -
-
- {!isLoading && data?.totalCount !== undefined && data.totalCount >= PER_PAGE_INIT && ( - setPage(newPage)} - onChangePerPage={(newPerPage) => setPerPage(newPerPage)} - /> - )} - {!isLoading && !data?.certificates?.length && ( - - )} -
-
+ + + + + + + + + + + + {isLoading && } + {!isLoading && + data?.certificates.map((certificate) => { + const { variant, label } = getCertValidUntilBadgeDetails(certificate.notAfter); + return ( + + + + + + + + ); + })} + +
Friendly NameStatusNot BeforeNot After +
{certificate.friendlyName} + + {label} + + + {certificate.notBefore + ? format(new Date(certificate.notBefore), "yyyy-MM-dd") + : "-"} + + {certificate.notAfter + ? format(new Date(certificate.notAfter), "yyyy-MM-dd") + : "-"} + + + +
+ + + +
+
+ + + {(isAllowed) => ( + + handlePopUpOpen("certificateCert", { + serialNumber: certificate.serialNumber + }) + } + disabled={!isAllowed} + icon={} + > + Export Certificate + + )} + + + {(isAllowed) => ( + + handlePopUpOpen("certificate", { + serialNumber: certificate.serialNumber + }) + } + disabled={!isAllowed} + icon={} + > + View Details + + )} + + + {(isAllowed) => ( + + handlePopUpOpen("revokeCertificate", { + serialNumber: certificate.serialNumber + }) + } + disabled={!isAllowed} + icon={} + > + Revoke Certificate + + )} + + + {(isAllowed) => ( + + handlePopUpOpen("deleteCertificate", { + serialNumber: certificate.serialNumber, + commonName: certificate.commonName + }) + } + disabled={!isAllowed} + icon={} + > + Delete Certificate + + )} + + +
+
+ {!isLoading && data?.totalCount !== undefined && data.totalCount >= PER_PAGE_INIT && ( + setPage(newPage)} + onChangePerPage={(newPerPage) => setPerPage(newPerPage)} + /> + )} + {!isLoading && !data?.certificates?.length && ( + + )} +
); }; diff --git a/frontend/src/views/Project/CertificatesPage/components/CertificatesTab/components/CertificatesTable.utils.ts b/frontend/src/views/Project/CertificatesPage/components/CertificatesTab/components/CertificatesTable.utils.ts new file mode 100644 index 000000000..93b408bbe --- /dev/null +++ b/frontend/src/views/Project/CertificatesPage/components/CertificatesTab/components/CertificatesTable.utils.ts @@ -0,0 +1,28 @@ +import ms from "ms"; + +export const getCertValidUntilBadgeDetails = (notAfter: string) => { + const currentDate = new Date().getTime(); + const notAfterDate = new Date(notAfter).getTime(); + const diffInMs = notAfterDate - currentDate; + + let variant: "success" | "primary" | "danger" = "success"; + let label = "Healthy"; + + if (diffInMs > ms("60d")) { + variant = "success"; + } else if (diffInMs > ms("30d")) { + variant = "primary"; + } else { + variant = "danger"; + } + + if (diffInMs > ms("60d")) { + label = "Healthy"; + } else if (diffInMs > ms("0d")) { + label = `Expires in ${ms(diffInMs)}`; + } else { + label = "Expired"; + } + + return { variant, label }; +}; diff --git a/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/PkiAlertsTab.tsx b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/PkiAlertsTab.tsx new file mode 100644 index 000000000..3a5a04345 --- /dev/null +++ b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/PkiAlertsTab.tsx @@ -0,0 +1,17 @@ +import { motion } from "framer-motion"; + +import { PkiAlertsSection } from "./components"; + +export const PkiAlertsTab = () => { + return ( + + + + ); +}; diff --git a/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiAlertModal.tsx b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiAlertModal.tsx new file mode 100644 index 000000000..efb63bdf2 --- /dev/null +++ b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiAlertModal.tsx @@ -0,0 +1,291 @@ +import { useEffect } from "react"; +import { Controller, useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { z } from "zod"; + +import { createNotification } from "@app/components/notifications"; +import { + Button, + FormControl, + Input, + Modal, + ModalContent, + Select, + SelectItem +} from "@app/components/v2"; +import { useWorkspace } from "@app/context"; +import { + useCreatePkiAlert, + useGetPkiAlertById, + useListWorkspacePkiCollections, + useUpdatePkiAlert +} from "@app/hooks/api"; +import { UsePopUpState } from "@app/hooks/usePopUp"; + +enum TimeUnit { + DAY = "days", + WEEK = "weeks", + MONTH = "months", + YEAR = "years" +} + +const schema = z.object({ + name: z.string().trim().min(1), + pkiCollectionId: z.string(), + alertBefore: z.string(), + alertUnit: z.nativeEnum(TimeUnit), + emails: z.string().trim() +}); + +const convertToDays = (unit: TimeUnit, value: number) => { + switch (unit) { + case TimeUnit.DAY: + return value; + case TimeUnit.WEEK: + return value * 7; + case TimeUnit.MONTH: + return value * 30; + case TimeUnit.YEAR: + return value * 365; + default: + throw new Error(`Unknown time unit: ${unit}`); + } +}; + +export type FormData = z.infer; + +type Props = { + popUp: UsePopUpState<["pkiAlert"]>; + handlePopUpToggle: (popUpName: keyof UsePopUpState<["pkiAlert"]>, state?: boolean) => void; +}; + +export const PkiAlertModal = ({ popUp, handlePopUpToggle }: Props) => { + const { currentWorkspace } = useWorkspace(); + const projectId = currentWorkspace?.id || ""; + + const { data: alert } = useGetPkiAlertById( + (popUp?.pkiAlert?.data as { alertId: string })?.alertId || "" + ); + + const { data: pkiCollections } = useListWorkspacePkiCollections({ + workspaceId: projectId + }); + + const { mutateAsync: createPkiAlert } = useCreatePkiAlert(); + const { mutateAsync: updatePkiAlert } = useUpdatePkiAlert(); + + const { + control, + handleSubmit, + reset, + formState: { isSubmitting } + } = useForm({ + resolver: zodResolver(schema), + defaultValues: { + alertUnit: TimeUnit.DAY + } + }); + + useEffect(() => { + if (alert) { + reset({ + name: alert.name, + pkiCollectionId: alert.pkiCollectionId, + alertBefore: alert.alertBeforeDays.toString(), + alertUnit: TimeUnit.DAY, + emails: alert.recipientEmails + }); + } else { + // TODO: add default collection? + reset({ + name: "", + ...(pkiCollections?.collections?.[0] && { + pkiCollectionId: pkiCollections.collections[0].id + }) + }); + } + }, [alert, pkiCollections]); + + const onFormSubmit = async ({ + name, + pkiCollectionId, + alertBefore, + alertUnit, + emails + }: FormData) => { + try { + if (!projectId) return; + + const emailArray = emails + .split(",") + .map((email) => email.trim()) + .filter((email) => email.length > 0); + + const alertBeforeDays = convertToDays(alertUnit, Number(alertBefore)); + + if (alert) { + // update + await updatePkiAlert({ + alertId: alert.id, + pkiCollectionId, + name, + projectId, + alertBeforeDays, + emails: emailArray + }); + } else { + // create + await createPkiAlert({ + name, + projectId, + pkiCollectionId, + alertBeforeDays, + emails: emailArray + }); + } + + handlePopUpToggle("pkiAlert", false); + + reset(); + + createNotification({ + text: `Successfully ${alert ? "updated" : "created"} alert`, + type: "success" + }); + } catch (err) { + console.error(err); + createNotification({ + text: `Failed to ${alert ? "updated" : "created"} alert`, + type: "error" + }); + } + }; + + return ( + { + handlePopUpToggle("pkiAlert", isOpen); + reset(); + }} + > + +
+ ( + + + + )} + /> + ( + + + + )} + /> +
+ ( + + + + )} + /> + ( + + + + )} + /> +
+ ( + + + + )} + /> +
+ + +
+ +
+
+ ); +}; diff --git a/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiAlertRow.tsx b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiAlertRow.tsx new file mode 100644 index 000000000..2eef7e3dc --- /dev/null +++ b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiAlertRow.tsx @@ -0,0 +1,92 @@ +import { faEllipsis } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { twMerge } from "tailwind-merge"; + +import { ProjectPermissionCan } from "@app/components/permissions"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, + Td, + Tr +} from "@app/components/v2"; +import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context"; +import { useGetPkiCollectionById } from "@app/hooks/api"; +import { TPkiAlert } from "@app/hooks/api/pkiAlerts/types"; +import { UsePopUpState } from "@app/hooks/usePopUp"; + +type Props = { + alert: TPkiAlert; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["pkiAlert", "deletePkiAlert"]>, + data?: {} + ) => void; +}; + +export const PkiAlertRow = ({ alert, handlePopUpOpen }: Props) => { + const { data: pkiCollection } = useGetPkiCollectionById(alert.pkiCollectionId || ""); + return ( + + {alert.name} + {alert.alertBeforeDays} + {pkiCollection ? pkiCollection.name : "-"} + + + +
+ +
+
+ + + {(isAllowed) => ( + { + e.stopPropagation(); + handlePopUpOpen("pkiAlert", { + alertId: alert.id + }); + }} + disabled={!isAllowed} + > + Edit Alert + + )} + + + {(isAllowed) => ( + { + e.stopPropagation(); + handlePopUpOpen("deletePkiAlert", { + alertId: alert.id, + name: alert.name + }); + }} + disabled={!isAllowed} + > + Delete Alert + + )} + + +
+ + + ); +}; diff --git a/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiAlertsSection.tsx b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiAlertsSection.tsx new file mode 100644 index 000000000..af27c4b7a --- /dev/null +++ b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiAlertsSection.tsx @@ -0,0 +1,84 @@ +import { faPlus } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; + +import { createNotification } from "@app/components/notifications"; +import { ProjectPermissionCan } from "@app/components/permissions"; +import { Button, DeleteActionModal } from "@app/components/v2"; +import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context"; +import { useDeletePkiAlert } from "@app/hooks/api"; +import { usePopUp } from "@app/hooks/usePopUp"; + +import { PkiAlertModal } from "./PkiAlertModal"; +import { PkiAlertsTable } from "./PkiAlertsTable"; + +export const PkiAlertsSection = () => { + const { currentWorkspace } = useWorkspace(); + const projectId = currentWorkspace?.id || ""; + const { mutateAsync: deletePkiAlert } = useDeletePkiAlert(); + + const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([ + "pkiAlert", + "deletePkiAlert" + ] as const); + + const onRemoveAlertSubmit = async (alertId: string) => { + try { + if (!projectId) return; + + await deletePkiAlert({ + alertId, + projectId + }); + + createNotification({ + text: "Successfully deleted alert", + type: "success" + }); + + handlePopUpClose("deletePkiAlert"); + } catch (err) { + console.error(err); + createNotification({ + text: "Failed to delete alert", + type: "error" + }); + } + }; + + return ( +
+
+

Alerts

+ + {(isAllowed) => ( + + )} + +
+ + + handlePopUpToggle("deletePkiAlert", isOpen)} + deleteKey="confirm" + onDeleteApproved={() => + onRemoveAlertSubmit((popUp?.deletePkiAlert?.data as { alertId: string })?.alertId) + } + /> +
+ ); +}; diff --git a/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiAlertsTable.tsx b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiAlertsTable.tsx new file mode 100644 index 000000000..f31b246f1 --- /dev/null +++ b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiAlertsTable.tsx @@ -0,0 +1,64 @@ +import { faExclamationCircle } from "@fortawesome/free-solid-svg-icons"; + +import { + EmptyState, + Table, + TableContainer, + TableSkeleton, + TBody, + Th, + THead, + Tr +} from "@app/components/v2"; +import { useWorkspace } from "@app/context"; +import { useListWorkspacePkiAlerts } from "@app/hooks/api"; +import { UsePopUpState } from "@app/hooks/usePopUp"; + +import { PkiAlertRow } from "./PkiAlertRow"; + +type Props = { + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["pkiAlert", "deletePkiAlert"]>, + data?: {} + ) => void; +}; + +export const PkiAlertsTable = ({ handlePopUpOpen }: Props) => { + const { currentWorkspace } = useWorkspace(); + const projectId = currentWorkspace?.id || ""; + + const { data, isLoading } = useListWorkspacePkiAlerts({ + workspaceId: projectId + }); + + return ( + + + + + + + + + + + {isLoading && } + {!isLoading && + data?.alerts.map((alert) => { + return ( + + ); + })} + +
Alert NameAlert Before DaysCertificate Collection +
+ {!isLoading && !data?.alerts?.length && ( + + )} +
+ ); +}; diff --git a/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiCollectionModal.tsx b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiCollectionModal.tsx new file mode 100644 index 000000000..926d1cec9 --- /dev/null +++ b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiCollectionModal.tsx @@ -0,0 +1,160 @@ +import { useEffect } from "react"; +import { Controller, useForm } from "react-hook-form"; +import { useRouter } from "next/router"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { z } from "zod"; + +import { createNotification } from "@app/components/notifications"; +import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2"; +import { useWorkspace } from "@app/context"; +import { + useCreatePkiCollection, + useGetPkiCollectionById, + useUpdatePkiCollection +} from "@app/hooks/api"; +import { UsePopUpState } from "@app/hooks/usePopUp"; + +const schema = z.object({ + name: z.string().trim().min(1), + description: z.string() +}); + +export type FormData = z.infer; + +type Props = { + popUp: UsePopUpState<["pkiCollection"]>; + handlePopUpToggle: (popUpName: keyof UsePopUpState<["pkiCollection"]>, state?: boolean) => void; +}; + +export const PkiCollectionModal = ({ popUp, handlePopUpToggle }: Props) => { + const router = useRouter(); + const { currentWorkspace } = useWorkspace(); + const projectId = currentWorkspace?.id || ""; + + const { data: pkiCollection } = useGetPkiCollectionById( + (popUp?.pkiCollection?.data as { collectionId: string })?.collectionId || "" + ); + + const { mutateAsync: createPkiCollection } = useCreatePkiCollection(); + const { mutateAsync: updatePkiCollection } = useUpdatePkiCollection(); + + const { + control, + handleSubmit, + reset, + formState: { isSubmitting } + } = useForm({ + resolver: zodResolver(schema) + }); + + useEffect(() => { + if (pkiCollection) { + reset({ + name: pkiCollection.name, + description: pkiCollection.description + }); + } else { + reset({ + name: "", + description: "" + }); + } + }, [pkiCollection]); + + const onFormSubmit = async ({ name, description }: FormData) => { + try { + if (!projectId) return; + + if (pkiCollection) { + // update + await updatePkiCollection({ + collectionId: pkiCollection.id, + name, + description, + projectId + }); + } else { + // create + const { id: createdId } = await createPkiCollection({ + name, + description, + projectId + }); + + router.push(`/project/${projectId}/pki-collections/${createdId}`); + } + + handlePopUpToggle("pkiCollection", false); + + reset(); + + createNotification({ + text: `Successfully ${pkiCollection ? "updated" : "created"} PKI collection`, + type: "success" + }); + } catch (err) { + console.error(err); + createNotification({ + text: `Failed to ${pkiCollection ? "updated" : "created"} PKI collection`, + type: "error" + }); + } + }; + + return ( + { + handlePopUpToggle("pkiCollection", isOpen); + reset(); + }} + > + +
+ ( + + + + )} + /> + ( + + + + )} + /> +
+ + +
+ +
+
+ ); +}; diff --git a/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiCollectionSection.tsx b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiCollectionSection.tsx new file mode 100644 index 000000000..03788092d --- /dev/null +++ b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiCollectionSection.tsx @@ -0,0 +1,86 @@ +import { faPlus } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; + +import { createNotification } from "@app/components/notifications"; +import { ProjectPermissionCan } from "@app/components/permissions"; +import { Button, DeleteActionModal } from "@app/components/v2"; +import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context"; +import { useDeletePkiCollection } from "@app/hooks/api"; +import { usePopUp } from "@app/hooks/usePopUp"; + +import { PkiCollectionModal } from "./PkiCollectionModal"; +import { PkiCollectionTable } from "./PkiCollectionTable"; + +export const PkiCollectionSection = () => { + const { currentWorkspace } = useWorkspace(); + const projectId = currentWorkspace?.id || ""; + const { mutateAsync: deletePkiCollection } = useDeletePkiCollection(); + + const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([ + "pkiCollection", + "deletePkiCollection" + ] as const); + + const onRemovePkiCollectionSubmit = async (collectionId: string) => { + try { + if (!projectId) return; + + await deletePkiCollection({ + collectionId, + projectId + }); + + await createNotification({ + text: "Successfully deleted PKI collection", + type: "success" + }); + + handlePopUpClose("deletePkiCollection"); + } catch (err) { + console.error(err); + createNotification({ + text: "Failed to delete PKI collection", + type: "error" + }); + } + }; + + return ( +
+
+

Certificate Collections

+ + {(isAllowed) => ( + + )} + +
+ + + handlePopUpToggle("deletePkiCollection", isOpen)} + deleteKey="confirm" + onDeleteApproved={() => + onRemovePkiCollectionSubmit( + (popUp?.deletePkiCollection?.data as { collectionId: string })?.collectionId + ) + } + /> +
+ ); +}; diff --git a/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiCollectionTable.tsx b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiCollectionTable.tsx new file mode 100644 index 000000000..a27662449 --- /dev/null +++ b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/PkiCollectionTable.tsx @@ -0,0 +1,134 @@ +import { useRouter } from "next/router"; +import { faBoxesStacked, faEllipsis } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { twMerge } from "tailwind-merge"; + +import { ProjectPermissionCan } from "@app/components/permissions"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, + EmptyState, + Table, + TableContainer, + TableSkeleton, + TBody, + Td, + Th, + THead, + Tr +} from "@app/components/v2"; +import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context"; +import { useListWorkspacePkiCollections } from "@app/hooks/api"; +import { UsePopUpState } from "@app/hooks/usePopUp"; + +type Props = { + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["pkiCollection", "deletePkiCollection"]>, + data?: {} + ) => void; +}; + +export const PkiCollectionTable = ({ handlePopUpOpen }: Props) => { + const router = useRouter(); + const { currentWorkspace } = useWorkspace(); + const projectId = currentWorkspace?.id || ""; + + const { data, isLoading } = useListWorkspacePkiCollections({ + workspaceId: projectId + }); + + return ( +
+ + + + + + + + + + {isLoading && } + {!isLoading && + data?.collections.map((pkiCollection) => { + return ( + + router.push(`/project/${projectId}/pki-collections/${pkiCollection.id}`) + } + > + + + + + ); + })} + +
NameDescription +
{pkiCollection.name}{pkiCollection.description ? pkiCollection.description : "-"} + + +
+ +
+
+ + + {(isAllowed) => ( + { + e.stopPropagation(); + handlePopUpOpen("pkiCollection", { + collectionId: pkiCollection.id + }); + }} + disabled={!isAllowed} + > + Edit Collection + + )} + + + {(isAllowed) => ( + { + e.stopPropagation(); + handlePopUpOpen("deletePkiCollection", { + collectionId: pkiCollection.id, + name: pkiCollection.name + }); + }} + disabled={!isAllowed} + > + Delete Collection + + )} + + +
+
+ {!isLoading && !data?.collections?.length && ( + + )} +
+
+ ); +}; diff --git a/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/index.tsx b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/index.tsx new file mode 100644 index 000000000..7c4147777 --- /dev/null +++ b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/components/index.tsx @@ -0,0 +1,2 @@ +export { PkiAlertsSection } from "./PkiAlertsSection"; +export { PkiCollectionSection } from "./PkiCollectionSection"; diff --git a/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/index.tsx b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/index.tsx new file mode 100644 index 000000000..0acaf13d6 --- /dev/null +++ b/frontend/src/views/Project/CertificatesPage/components/PkiAlertsTab/index.tsx @@ -0,0 +1 @@ +export { PkiAlertsTab } from "./PkiAlertsTab"; diff --git a/frontend/src/views/Project/CertificatesPage/components/index.tsx b/frontend/src/views/Project/CertificatesPage/components/index.tsx index 9dbd8694f..851d403a0 100644 --- a/frontend/src/views/Project/CertificatesPage/components/index.tsx +++ b/frontend/src/views/Project/CertificatesPage/components/index.tsx @@ -1,2 +1,3 @@ export { CaTab } from "./CaTab"; export { CertificatesTab } from "./CertificatesTab"; +export { PkiAlertsTab } from "./PkiAlertsTab"; diff --git a/frontend/src/views/Project/PkiCollectionPage/PkiCollectionPage.tsx b/frontend/src/views/Project/PkiCollectionPage/PkiCollectionPage.tsx new file mode 100644 index 000000000..6964279d0 --- /dev/null +++ b/frontend/src/views/Project/PkiCollectionPage/PkiCollectionPage.tsx @@ -0,0 +1,169 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { useRouter } from "next/router"; +import { faChevronLeft, faEllipsis } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { twMerge } from "tailwind-merge"; + +import { createNotification } from "@app/components/notifications"; +import { ProjectPermissionCan } from "@app/components/permissions"; +import { + Button, + DeleteActionModal, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, + Tooltip +} from "@app/components/v2"; +import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context"; +import { withProjectPermission } from "@app/hoc"; +import { useDeletePkiCollection, useGetPkiCollectionById } from "@app/hooks/api"; +import { PkiItemType } from "@app/hooks/api/pkiCollections/constants"; +import { usePopUp } from "@app/hooks/usePopUp"; + +import { PkiCollectionModal } from "../CertificatesPage/components/PkiAlertsTab/components/PkiCollectionModal"; +import { PkiCollectionDetailsSection, PkiCollectionItemsSection } from "./components"; + +export const PkiCollectionPage = withProjectPermission( + () => { + const router = useRouter(); + const collectionId = router.query.collectionId as string; + const { currentWorkspace } = useWorkspace(); + const projectId = currentWorkspace?.id || ""; + + const { data } = useGetPkiCollectionById(collectionId); + const { mutateAsync: deletePkiCollection } = useDeletePkiCollection(); + + const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([ + "pkiCollection", + "deletePkiCollection" + ] as const); + + const onDeletePkiCollectionSubmit = async (collectionIdToDelete: string) => { + try { + if (!projectId) return; + + await deletePkiCollection({ + projectId, + collectionId: collectionIdToDelete + }); + + createNotification({ + text: "Successfully deleted PKI collection", + type: "success" + }); + handlePopUpClose("deletePkiCollection"); + router.push(`/project/${projectId}/certificates`); + } catch (err) { + console.error(err); + } + }; + + return ( +
+ {data && ( +
+ +
+

{data.name}

+ + +
+ + + +
+
+ + + {(isAllowed) => ( + { + handlePopUpOpen("pkiCollection", { + collectionId + }); + }} + disabled={!isAllowed} + > + Edit PKI Collection + + )} + + + {(isAllowed) => ( + + handlePopUpOpen("deletePkiCollection", { + collectionId: data.id, + name: data.name + }) + } + disabled={!isAllowed} + > + Delete PKI Collection + + )} + + +
+
+
+
+ +
+
+
+ +
+ +
+
+
+ )} + + handlePopUpToggle("deletePkiCollection", isOpen)} + deleteKey="confirm" + onDeleteApproved={() => + onDeletePkiCollectionSubmit( + (popUp.deletePkiCollection.data as { collectionId: string })?.collectionId + ) + } + /> +
+ ); + }, + { action: ProjectPermissionActions.Read, subject: ProjectPermissionSub.PkiCollections } +); diff --git a/frontend/src/views/Project/PkiCollectionPage/components/AddPkiCollectionItemModal.tsx b/frontend/src/views/Project/PkiCollectionPage/components/AddPkiCollectionItemModal.tsx new file mode 100644 index 000000000..f356f2190 --- /dev/null +++ b/frontend/src/views/Project/PkiCollectionPage/components/AddPkiCollectionItemModal.tsx @@ -0,0 +1,203 @@ +import { Controller, useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { z } from "zod"; + +import { createNotification } from "@app/components/notifications"; +import { Button, FormControl, Modal, ModalContent, Select, SelectItem } from "@app/components/v2"; +import { useWorkspace } from "@app/context"; +import { + CaStatus, + useAddItemToPkiCollection, + useListWorkspaceCas, + useListWorkspaceCertificates +} from "@app/hooks/api"; +import { PkiItemType, pkiItemTypeToNameMap } from "@app/hooks/api/pkiCollections/constants"; +import { UsePopUpState } from "@app/hooks/usePopUp"; + +const schema = z + .object({ + // type: z.nativeEnum(PkiItemType), + itemId: z.string() + }) + .required(); + +type FormData = z.infer; + +type Props = { + collectionId: string; + type: PkiItemType; + popUp: UsePopUpState<["addPkiCollectionItem"]>; + handlePopUpToggle: ( + popUpName: keyof UsePopUpState<["addPkiCollectionItem"]>, + state?: boolean + ) => void; +}; + +// note: this component should be optimized so it is easier +// to find certificates and CAs +export const AddPkiCollectionItemModal = ({ + collectionId, + type, + popUp, + handlePopUpToggle +}: Props) => { + const { currentWorkspace } = useWorkspace(); + + const { data: cas } = useListWorkspaceCas({ + projectSlug: currentWorkspace?.slug || "", + status: CaStatus.ACTIVE + }); + + const { data } = useListWorkspaceCertificates({ + projectSlug: currentWorkspace?.slug || "", + offset: 0, + limit: 25 + }); + + const { mutateAsync: addItemToPkiCollection } = useAddItemToPkiCollection(); + + const { + control, + handleSubmit, + reset, + formState: { isSubmitting } + } = useForm({ + resolver: zodResolver(schema) + // defaultValues: { + // type: PkiItemType.CA + // } + }); + + const onFormSubmit = async ({ itemId }: FormData) => { + try { + const item = await addItemToPkiCollection({ + collectionId, + type, + itemId + }); + + createNotification({ + text: `Successfully added ${ + pkiItemTypeToNameMap[item.type as PkiItemType] + } to PKI collection`, + type: "success" + }); + + reset(); + handlePopUpToggle("addPkiCollectionItem", false); + } catch (err) { + console.error(err); + } + }; + + return ( + { + handlePopUpToggle("addPkiCollectionItem", isOpen); + reset(); + }} + > + +
+ {/* ( + + + + )} + /> */} + {type === PkiItemType.CA && ( + ( + + + + )} + /> + )} + {type === PkiItemType.CERTIFICATE && ( + ( + + + + )} + /> + )} +
+ + +
+ +
+
+ ); +}; diff --git a/frontend/src/views/Project/PkiCollectionPage/components/PkiCollectionDetailsSection.tsx b/frontend/src/views/Project/PkiCollectionPage/components/PkiCollectionDetailsSection.tsx new file mode 100644 index 000000000..2b3482624 --- /dev/null +++ b/frontend/src/views/Project/PkiCollectionPage/components/PkiCollectionDetailsSection.tsx @@ -0,0 +1,87 @@ +import { faCheck, faCopy, faPencil } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; + +import { ProjectPermissionCan } from "@app/components/permissions"; +import { IconButton, Tooltip } from "@app/components/v2"; +import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context"; +import { useTimedReset } from "@app/hooks"; +import { useGetPkiCollectionById } from "@app/hooks/api"; +import { UsePopUpState } from "@app/hooks/usePopUp"; + +type Props = { + collectionId: string; + handlePopUpOpen: (popUpName: keyof UsePopUpState<["pkiCollection"]>, data?: {}) => void; +}; + +export const PkiCollectionDetailsSection = ({ collectionId, handlePopUpOpen }: Props) => { + const [copyTextId, isCopyingId, setCopyTextId] = useTimedReset({ + initialState: "Copy ID to clipboard" + }); + + const { data: pkiCollection } = useGetPkiCollectionById(collectionId); + + return pkiCollection ? ( +
+
+

Collection Details

+ + {(isAllowed) => { + return ( + + + handlePopUpOpen("pkiCollection", { + collectionId + }) + } + > + + + + ); + }} + +
+
+
+

PKI Collection ID

+
+

{pkiCollection.id}

+
+ + { + navigator.clipboard.writeText(pkiCollection.id); + setCopyTextId("Copied"); + }} + > + + + +
+
+
+
+

Name

+

{pkiCollection.name}

+
+
+

Description

+

{pkiCollection.description}

+
+
+
+ ) : ( +
+ ); +}; diff --git a/frontend/src/views/Project/PkiCollectionPage/components/PkiCollectionItemsSection.tsx b/frontend/src/views/Project/PkiCollectionPage/components/PkiCollectionItemsSection.tsx new file mode 100644 index 000000000..02df725d0 --- /dev/null +++ b/frontend/src/views/Project/PkiCollectionPage/components/PkiCollectionItemsSection.tsx @@ -0,0 +1,92 @@ +import { faPlus } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; + +import { createNotification } from "@app/components/notifications"; +import { DeleteActionModal, IconButton } from "@app/components/v2"; +import { useGetPkiCollectionById, useRemoveItemFromPkiCollection } from "@app/hooks/api"; +import { PkiItemType } from "@app/hooks/api/pkiCollections/constants"; +import { usePopUp } from "@app/hooks/usePopUp"; + +import { AddPkiCollectionItemModal } from "./AddPkiCollectionItemModal"; +import { PkiCollectionItemsTable } from "./PkiCollectionItemsTable"; + +type Props = { + collectionId: string; + type: PkiItemType; +}; + +export const PkiCollectionItemsSection = ({ collectionId, type }: Props) => { + const { data: pkiCollection } = useGetPkiCollectionById(collectionId); + const { mutateAsync: removeItemFromPkiCollection } = useRemoveItemFromPkiCollection(); + + const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([ + "deletePkiCollectionItem", + "addPkiCollectionItem" + ] as const); + + const onRemovePkiCollectionItemSubmit = async (itemId: string) => { + try { + await removeItemFromPkiCollection({ + itemId, + collectionId + }); + + createNotification({ + text: "Successfully removed item from PKI collection", + type: "success" + }); + + handlePopUpClose("deletePkiCollectionItem"); + } catch (err) { + console.error(err); + } + }; + + const sectionName = type === PkiItemType.CA ? "Certificate Authorities" : "Certificates"; + + return pkiCollection ? ( +
+
+

{sectionName}

+ { + handlePopUpOpen("addPkiCollectionItem"); + }} + > + + +
+
+ +
+ + handlePopUpToggle("deletePkiCollectionItem", isOpen)} + deleteKey="confirm" + onDeleteApproved={() => { + const popupData = popUp?.deletePkiCollectionItem?.data as { + itemId: string; + }; + + return onRemovePkiCollectionItemSubmit(popupData.itemId); + }} + /> +
+ ) : ( +
+ ); +}; diff --git a/frontend/src/views/Project/PkiCollectionPage/components/PkiCollectionItemsTable.tsx b/frontend/src/views/Project/PkiCollectionPage/components/PkiCollectionItemsTable.tsx new file mode 100644 index 000000000..d8518e6a2 --- /dev/null +++ b/frontend/src/views/Project/PkiCollectionPage/components/PkiCollectionItemsTable.tsx @@ -0,0 +1,118 @@ +import { useState } from "react"; +import { faBoxesStacked, faXmark } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { format } from "date-fns"; + +import { ProjectPermissionCan } from "@app/components/permissions"; +import { + EmptyState, + IconButton, + Pagination, + Table, + TableContainer, + TableSkeleton, + TBody, + Td, + Th, + THead, + Tooltip, + Tr +} from "@app/components/v2"; +import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context"; +import { useListPkiCollectionItems } from "@app/hooks/api"; +import { PkiItemType, pkiItemTypeToNameMap } from "@app/hooks/api/pkiCollections/constants"; +import { UsePopUpState } from "@app/hooks/usePopUp"; + +type Props = { + collectionId: string; + type: PkiItemType; + handlePopUpOpen: (popUpName: keyof UsePopUpState<["deletePkiCollectionItem"]>, data?: {}) => void; +}; + +const PER_PAGE_INIT = 25; + +export const PkiCollectionItemsTable = ({ collectionId, type, handlePopUpOpen }: Props) => { + const [page, setPage] = useState(1); + const [perPage, setPerPage] = useState(PER_PAGE_INIT); + + const { data, isLoading } = useListPkiCollectionItems({ + collectionId, + offset: (page - 1) * perPage, + limit: perPage, + type + }); + + return ( +
+ + + + + + + + + + + {isLoading && } + {!isLoading && + data?.collectionItems.map((collectionItem) => { + return ( + + + + + + + ); + })} + +
Friendly NameNot BeforeNot After +
{collectionItem.friendlyName}{format(new Date(collectionItem.notBefore), "yyyy-MM-dd")}{format(new Date(collectionItem.notAfter), "yyyy-MM-dd")} +
+ + {(isAllowed) => ( + + { + e.stopPropagation(); + handlePopUpOpen("deletePkiCollectionItem", { + collectionId, + itemId: collectionItem.id + }); + }} + > + + + + )} + +
+
+ {!isLoading && data?.totalCount !== undefined && data.totalCount >= PER_PAGE_INIT && ( + setPage(newPage)} + onChangePerPage={(newPerPage) => setPerPage(newPerPage)} + /> + )} + {!isLoading && !data?.collectionItems?.length && ( + + )} +
+
+ ); +}; diff --git a/frontend/src/views/Project/PkiCollectionPage/components/index.tsx b/frontend/src/views/Project/PkiCollectionPage/components/index.tsx new file mode 100644 index 000000000..97ec4c0e0 --- /dev/null +++ b/frontend/src/views/Project/PkiCollectionPage/components/index.tsx @@ -0,0 +1,2 @@ +export { PkiCollectionDetailsSection } from "./PkiCollectionDetailsSection"; +export { PkiCollectionItemsSection } from "./PkiCollectionItemsSection"; diff --git a/frontend/src/views/Project/PkiCollectionPage/index.tsx b/frontend/src/views/Project/PkiCollectionPage/index.tsx new file mode 100644 index 000000000..acc175c14 --- /dev/null +++ b/frontend/src/views/Project/PkiCollectionPage/index.tsx @@ -0,0 +1 @@ +export { PkiCollectionPage } from "./PkiCollectionPage"; diff --git a/frontend/src/views/Project/RolePage/components/RolePermissionsSection/ProjectRoleModifySection.utils.ts b/frontend/src/views/Project/RolePage/components/RolePermissionsSection/ProjectRoleModifySection.utils.ts index 7e27bde6b..abab188b8 100644 --- a/frontend/src/views/Project/RolePage/components/RolePermissionsSection/ProjectRoleModifySection.utils.ts +++ b/frontend/src/views/Project/RolePage/components/RolePermissionsSection/ProjectRoleModifySection.utils.ts @@ -51,6 +51,8 @@ export const formSchema = z.object({ "ip-allowlist": generalPermissionSchema, "certificate-authorities": generalPermissionSchema, certificates: generalPermissionSchema, + "pki-alerts": generalPermissionSchema, + "pki-collections": generalPermissionSchema, // akhilmhdh: refactor all keys like below [ProjectPermissionSub.SecretApproval]: generalPermissionSchema, workspace: z diff --git a/frontend/src/views/Project/RolePage/components/RolePermissionsSection/RolePermissionsSection.tsx b/frontend/src/views/Project/RolePage/components/RolePermissionsSection/RolePermissionsSection.tsx index e56c3d44e..40e4c260a 100644 --- a/frontend/src/views/Project/RolePage/components/RolePermissionsSection/RolePermissionsSection.tsx +++ b/frontend/src/views/Project/RolePage/components/RolePermissionsSection/RolePermissionsSection.tsx @@ -81,6 +81,14 @@ const SINGLE_PERMISSION_LIST = [ title: "Certificates", formName: "certificates" }, + { + title: "PKI Collections", + formName: "pki-collections" + }, + { + title: "PKI Alerts", + formName: "pki-alerts" + }, { title: "Secret Rollback", formName: "secret-rollback"