Skip to content

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

Add PKI applications

Carlos Monastyrski7fcea1a6aec2
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 9f2f129b11..678c7b90a4 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -131,6 +131,11 @@ 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 { TPkiAlertV2ServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-service";
+import { TCertManagerInstanceServiceFactory } from "@app/services/pki-application/cert-manager-instance-service";
+import { TCertManagerProjectResolverFactory } from "@app/services/pki-application/cert-manager-project-resolver";
+import { TPkiApplicationEnrollmentServiceFactory } from "@app/services/pki-application/pki-application-enrollment-service";
+import { TPkiApplicationMembershipServiceFactory } from "@app/services/pki-application/pki-application-membership-service";
+import { TPkiApplicationServiceFactory } from "@app/services/pki-application/pki-application-service";
import { TPkiCollectionServiceFactory } from "@app/services/pki-collection/pki-collection-service";
import { TPkiSubscriberServiceFactory } from "@app/services/pki-subscriber/pki-subscriber-service";
import { TPkiSyncServiceFactory } from "@app/services/pki-sync/pki-sync-service";
@@ -249,6 +254,7 @@ declare module "fastify" {
name: string;
};
auditLogInfo: Pick<TCreateAuditLogDTO, "userAgent" | "userAgentType" | "ipAddress" | "actor" | "orgId">;
+ certManagerProjectId: string;
ssoConfig: Awaited<ReturnType<TSamlConfigServiceFactory["getSaml"]>>;
ldapConfig: Awaited<ReturnType<TLdapConfigServiceFactory["getLdapCfg"]>> & {
allowedFields?: TAllowedFields[];
@@ -321,6 +327,11 @@ declare module "fastify" {
certificateTemplate: TCertificateTemplateServiceFactory;
certificatePolicy: TCertificatePolicyServiceFactory;
certificateProfile: TCertificateProfileServiceFactory;
+ pkiApplication: TPkiApplicationServiceFactory;
+ pkiApplicationMembership: TPkiApplicationMembershipServiceFactory;
+ pkiApplicationEnrollment: TPkiApplicationEnrollmentServiceFactory;
+ certManagerProjectResolver: TCertManagerProjectResolverFactory;
+ certManagerInstance: TCertManagerInstanceServiceFactory;
sshCertificateAuthority: TSshCertificateAuthorityServiceFactory;
sshCertificateTemplate: TSshCertificateTemplateServiceFactory;
sshHost: TSshHostServiceFactory;
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 0156cf33e7..806b4812e1 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -347,6 +347,12 @@ import {
TPkiApiEnrollmentConfigs,
TPkiApiEnrollmentConfigsInsert,
TPkiApiEnrollmentConfigsUpdate,
+ TPkiApplicationProfiles,
+ TPkiApplicationProfilesInsert,
+ TPkiApplicationProfilesUpdate,
+ TPkiApplications,
+ TPkiApplicationsInsert,
+ TPkiApplicationsUpdate,
TPkiCertificateInstallationCerts,
TPkiCertificateInstallationCertsInsert,
TPkiCertificateInstallationCertsUpdate,
@@ -883,6 +889,16 @@ declare module "knex/types/tables" {
TPkiCertificateProfilesInsert,
TPkiCertificateProfilesUpdate
>;
+ [TableName.PkiApplication]: KnexOriginal.CompositeTableType<
+ TPkiApplications,
+ TPkiApplicationsInsert,
+ TPkiApplicationsUpdate
+ >;
+ [TableName.PkiApplicationProfile]: KnexOriginal.CompositeTableType<
+ TPkiApplicationProfiles,
+ TPkiApplicationProfilesInsert,
+ TPkiApplicationProfilesUpdate
+ >;
[TableName.PkiEstEnrollmentConfig]: KnexOriginal.CompositeTableType<
TPkiEstEnrollmentConfigs,
TPkiEstEnrollmentConfigsInsert,
diff --git a/backend/src/db/migrations/20260504432352_cert-manager-applications.ts b/backend/src/db/migrations/20260504432352_cert-manager-applications.ts
new file mode 100644
index 0000000000..0b985f43d0
--- /dev/null
+++ b/backend/src/db/migrations/20260504432352_cert-manager-applications.ts
@@ -0,0 +1,227 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasColumn(TableName.Organization, "defaultCertManagerProjectId"))) {
+ await knex.schema.alterTable(TableName.Organization, (t) => {
+ t.string("defaultCertManagerProjectId", 36);
+ t.foreign("defaultCertManagerProjectId").references("id").inTable(TableName.Project).onDelete("SET NULL");
+ });
+ }
+
+ if (!(await knex.schema.hasTable(TableName.PkiApplication))) {
+ await knex.schema.createTable(TableName.PkiApplication, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.string("projectId").notNullable();
+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+ t.index("projectId");
+ t.string("name", 64).notNullable();
+ t.string("slug", 64).notNullable();
+ t.string("description", 256);
+ t.timestamps(true, true, true);
+ t.unique(["slug", "projectId"]);
+ });
+ await createOnUpdateTrigger(knex, TableName.PkiApplication);
+ }
+
+ if (!(await knex.schema.hasTable(TableName.PkiApplicationProfile))) {
+ await knex.schema.createTable(TableName.PkiApplicationProfile, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.uuid("applicationId").notNullable();
+ t.foreign("applicationId").references("id").inTable(TableName.PkiApplication).onDelete("CASCADE");
+ t.uuid("profileId").notNullable();
+ t.foreign("profileId").references("id").inTable(TableName.PkiCertificateProfile).onDelete("CASCADE");
+ t.uuid("estConfigId");
+ t.foreign("estConfigId").references("id").inTable(TableName.PkiEstEnrollmentConfig).onDelete("SET NULL");
+ t.uuid("apiConfigId");
+ t.foreign("apiConfigId").references("id").inTable(TableName.PkiApiEnrollmentConfig).onDelete("SET NULL");
+ t.uuid("acmeConfigId");
+ t.foreign("acmeConfigId").references("id").inTable(TableName.PkiAcmeEnrollmentConfig).onDelete("SET NULL");
+ t.uuid("scepConfigId");
+ t.foreign("scepConfigId").references("id").inTable(TableName.PkiScepEnrollmentConfig).onDelete("SET NULL");
+ t.timestamps(true, true, true);
+ t.unique(["applicationId", "profileId"]);
+ t.index("profileId");
+ });
+ await createOnUpdateTrigger(knex, TableName.PkiApplicationProfile);
+ }
+
+ if (!(await knex.schema.hasColumn(TableName.Membership, "scopeResourceType"))) {
+ await knex.schema.alterTable(TableName.Membership, (t) => {
+ t.string("scopeResourceType", 32);
+ t.string("scopeResourceId", 36);
+ });
+
+ await knex.schema.alterTable(TableName.Membership, (t) => {
+ t.dropChecks("scope_matches_id");
+ t.check(
+ `("scope" = 'project' AND "scopeProjectId" IS NOT NULL) OR ("scope" = 'organization') OR ("scope" = 'resource' AND "scopeProjectId" IS NOT NULL AND "scopeResourceType" IS NOT NULL AND "scopeResourceId" IS NOT NULL)`,
+ {},
+ "scope_matches_id"
+ );
+ });
+
+ await knex.schema.raw(`
+ CREATE UNIQUE INDEX IF NOT EXISTS membership_unique_user_resource
+ ON ${TableName.Membership} ("scopeProjectId", "scopeResourceType", "scopeResourceId", "actorUserId")
+ WHERE scope = 'resource' AND "actorUserId" IS NOT NULL;
+ `);
+ await knex.schema.raw(`
+ CREATE UNIQUE INDEX IF NOT EXISTS membership_unique_identity_resource
+ ON ${TableName.Membership} ("scopeProjectId", "scopeResourceType", "scopeResourceId", "actorIdentityId")
+ WHERE scope = 'resource' AND "actorIdentityId" IS NOT NULL;
+ `);
+ await knex.schema.raw(`
+ CREATE UNIQUE INDEX IF NOT EXISTS membership_unique_group_resource
+ ON ${TableName.Membership} ("scopeProjectId", "scopeResourceType", "scopeResourceId", "actorGroupId")
+ WHERE scope = 'resource' AND "actorGroupId" IS NOT NULL;
+ `);
+ await knex.schema.raw(`
+ CREATE INDEX IF NOT EXISTS membership_project_resource_idx
+ ON ${TableName.Membership} ("scopeProjectId", "scopeResourceType", "scopeResourceId")
+ WHERE scope = 'resource';
+ `);
+ }
+
+ if (!(await knex.schema.hasColumn(TableName.PkiAlertsV2, "applicationId"))) {
+ await knex.schema.alterTable(TableName.PkiAlertsV2, (t) => {
+ t.uuid("applicationId");
+ t.foreign("applicationId").references("id").inTable(TableName.PkiApplication).onDelete("CASCADE");
+ t.index(["projectId", "applicationId"]);
+ });
+ }
+
+ if (!(await knex.schema.hasColumn(TableName.PkiSync, "applicationId"))) {
+ await knex.schema.alterTable(TableName.PkiSync, (t) => {
+ t.uuid("applicationId");
+ t.foreign("applicationId").references("id").inTable(TableName.PkiApplication).onDelete("CASCADE");
+ t.index(["projectId", "applicationId"]);
+ });
+ }
+
+ if (!(await knex.schema.hasColumn(TableName.ApprovalPolicies, "applicationId"))) {
+ await knex.schema.alterTable(TableName.ApprovalPolicies, (t) => {
+ t.uuid("applicationId").nullable();
+ t.foreign("applicationId").references("id").inTable(TableName.PkiApplication).onDelete("CASCADE");
+ t.index("applicationId");
+ });
+ }
+
+ if (!(await knex.schema.hasColumn(TableName.ApprovalRequests, "applicationId"))) {
+ await knex.schema.alterTable(TableName.ApprovalRequests, (t) => {
+ t.uuid("applicationId").nullable();
+ t.foreign("applicationId").references("id").inTable(TableName.PkiApplication).onDelete("CASCADE");
+ t.index("applicationId");
+ });
+ }
+
+ if (!(await knex.schema.hasColumn(TableName.Certificate, "applicationId"))) {
+ await knex.schema.alterTable(TableName.Certificate, (t) => {
+ t.uuid("applicationId").nullable();
+ t.foreign("applicationId").references("id").inTable(TableName.PkiApplication).onDelete("SET NULL");
+ t.index(["projectId", "applicationId"]);
+ });
+ }
+
+ if (!(await knex.schema.hasColumn(TableName.PkiAcmeAccount, "applicationProfileId"))) {
+ await knex.schema.alterTable(TableName.PkiAcmeAccount, (t) => {
+ t.uuid("applicationProfileId").nullable();
+ t.foreign("applicationProfileId").references("id").inTable(TableName.PkiApplicationProfile).onDelete("CASCADE");
+ t.index("applicationProfileId");
+ });
+ }
+
+ if (!(await knex.schema.hasColumn(TableName.PkiScepTransaction, "applicationId"))) {
+ await knex.schema.alterTable(TableName.PkiScepTransaction, (t) => {
+ t.uuid("applicationId").nullable();
+ t.foreign("applicationId").references("id").inTable(TableName.PkiApplication).onDelete("CASCADE");
+ t.index("applicationId");
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasColumn(TableName.PkiScepTransaction, "applicationId")) {
+ await knex.schema.alterTable(TableName.PkiScepTransaction, (t) => {
+ t.dropForeign(["applicationId"]);
+ t.dropColumn("applicationId");
+ });
+ }
+
+ if (await knex.schema.hasColumn(TableName.PkiAcmeAccount, "applicationProfileId")) {
+ await knex.schema.alterTable(TableName.PkiAcmeAccount, (t) => {
+ t.dropForeign(["applicationProfileId"]);
+ t.dropColumn("applicationProfileId");
+ });
+ }
+
+ if (await knex.schema.hasColumn(TableName.Certificate, "applicationId")) {
+ await knex.schema.alterTable(TableName.Certificate, (t) => {
+ t.dropForeign(["applicationId"]);
+ t.dropColumn("applicationId");
+ });
+ }
+
+ if (await knex.schema.hasColumn(TableName.ApprovalRequests, "applicationId")) {
+ await knex.schema.alterTable(TableName.ApprovalRequests, (t) => {
+ t.dropForeign(["applicationId"]);
+ t.dropColumn("applicationId");
+ });
+ }
+
+ if (await knex.schema.hasColumn(TableName.ApprovalPolicies, "applicationId")) {
+ await knex.schema.alterTable(TableName.ApprovalPolicies, (t) => {
+ t.dropForeign(["applicationId"]);
+ t.dropColumn("applicationId");
+ });
+ }
+
+ if (await knex.schema.hasColumn(TableName.PkiSync, "applicationId")) {
+ await knex.schema.alterTable(TableName.PkiSync, (t) => {
+ t.dropForeign(["applicationId"]);
+ t.dropColumn("applicationId");
+ });
+ }
+
+ if (await knex.schema.hasColumn(TableName.PkiAlertsV2, "applicationId")) {
+ await knex.schema.alterTable(TableName.PkiAlertsV2, (t) => {
+ t.dropForeign(["applicationId"]);
+ t.dropColumn("applicationId");
+ });
+ }
+
+ await knex.schema.raw("DROP INDEX IF EXISTS membership_project_resource_idx;");
+ await knex.schema.raw("DROP INDEX IF EXISTS membership_unique_user_resource;");
+ await knex.schema.raw("DROP INDEX IF EXISTS membership_unique_identity_resource;");
+ await knex.schema.raw("DROP INDEX IF EXISTS membership_unique_group_resource;");
+
+ if (await knex.schema.hasColumn(TableName.Membership, "scopeResourceType")) {
+ await knex.schema.alterTable(TableName.Membership, (t) => {
+ t.dropChecks("scope_matches_id");
+ t.check(
+ `("scope" = 'project' AND "scopeProjectId" IS NOT NULL) OR ("scope" = 'organization')`,
+ {},
+ "scope_matches_id"
+ );
+ });
+ await knex.schema.alterTable(TableName.Membership, (t) => {
+ t.dropColumn("scopeResourceType");
+ t.dropColumn("scopeResourceId");
+ });
+ }
+
+ await dropOnUpdateTrigger(knex, TableName.PkiApplicationProfile);
+ await knex.schema.dropTableIfExists(TableName.PkiApplicationProfile);
+
+ await dropOnUpdateTrigger(knex, TableName.PkiApplication);
+ await knex.schema.dropTableIfExists(TableName.PkiApplication);
+
+ if (await knex.schema.hasColumn(TableName.Organization, "defaultCertManagerProjectId")) {
+ await knex.schema.alterTable(TableName.Organization, (t) => {
+ t.dropForeign(["defaultCertManagerProjectId"]);
+ t.dropColumn("defaultCertManagerProjectId");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/approval-policies.ts b/backend/src/db/schemas/approval-policies.ts
index 0cd8046781..1fc33caf95 100644
--- a/backend/src/db/schemas/approval-policies.ts
+++ b/backend/src/db/schemas/approval-policies.ts
@@ -19,7 +19,8 @@ export const ApprovalPoliciesSchema = z.object({
constraints: z.unknown(),
createdAt: z.date(),
updatedAt: z.date(),
- bypassForMachineIdentities: z.boolean().default(false).nullable().optional()
+ bypassForMachineIdentities: z.boolean().default(false).nullable().optional(),
+ applicationId: z.string().uuid().nullable().optional()
});
export type TApprovalPolicies = z.infer<typeof ApprovalPoliciesSchema>;
diff --git a/backend/src/db/schemas/approval-requests.ts b/backend/src/db/schemas/approval-requests.ts
index e93e684000..7da89eee22 100644
--- a/backend/src/db/schemas/approval-requests.ts
+++ b/backend/src/db/schemas/approval-requests.ts
@@ -23,7 +23,8 @@ export const ApprovalRequestsSchema = z.object({
expiresAt: z.date().nullable().optional(),
createdAt: z.date(),
updatedAt: z.date(),
- machineIdentityId: z.string().uuid().nullable().optional()
+ machineIdentityId: z.string().uuid().nullable().optional(),
+ applicationId: z.string().uuid().nullable().optional()
});
export type TApprovalRequests = z.infer<typeof ApprovalRequestsSchema>;
diff --git a/backend/src/db/schemas/certificates.ts b/backend/src/db/schemas/certificates.ts
index b69adb0601..3c1cd6b2c3 100644
--- a/backend/src/db/schemas/certificates.ts
+++ b/backend/src/db/schemas/certificates.ts
@@ -45,7 +45,8 @@ export const CertificatesSchema = z.object({
pathLength: z.number().nullable().optional(),
source: z.string().nullable().optional(),
discoveryMetadata: z.unknown().nullable().optional(),
- externalMetadata: z.unknown().nullable().optional()
+ externalMetadata: z.unknown().nullable().optional(),
+ applicationId: z.string().uuid().nullable().optional()
});
export type TCertificates = z.infer<typeof CertificatesSchema>;
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index c77e6dfa9e..7e4ff0b10b 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -143,6 +143,8 @@ export * from "./pki-alert-history-certificate";
export * from "./pki-alerts";
export * from "./pki-alerts-v2";
export * from "./pki-api-enrollment-configs";
+export * from "./pki-application-profiles";
+export * from "./pki-applications";
export * from "./pki-certificate-installation-certs";
export * from "./pki-certificate-installations";
export * from "./pki-certificate-policies";
diff --git a/backend/src/db/schemas/memberships.ts b/backend/src/db/schemas/memberships.ts
index a6c0b5d8e5..6e7f06a455 100644
--- a/backend/src/db/schemas/memberships.ts
+++ b/backend/src/db/schemas/memberships.ts
@@ -23,7 +23,9 @@ export const MembershipsSchema = z.object({
lastLoginTime: z.date().nullable().optional(),
projectFavorites: z.string().array().nullable().optional(),
createdAt: z.date(),
- updatedAt: z.date()
+ updatedAt: z.date(),
+ scopeResourceType: z.string().nullable().optional(),
+ scopeResourceId: z.string().nullable().optional()
});
export type TMemberships = z.infer<typeof MembershipsSchema>;
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 5ab22f2cea..b9d8641b70 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -28,6 +28,8 @@ export enum TableName {
PkiCertificateTemplateV2 = "pki_certificate_templates_v2",
PkiCertificatePolicy = "pki_certificate_policies",
PkiCertificateProfile = "pki_certificate_profiles",
+ PkiApplication = "pki_applications",
+ PkiApplicationProfile = "pki_application_profiles",
PkiEstEnrollmentConfig = "pki_est_enrollment_configs",
PkiApiEnrollmentConfig = "pki_api_enrollment_configs",
PkiAcmeEnrollmentConfig = "pki_acme_enrollment_configs",
@@ -320,7 +322,9 @@ export enum OrgMembershipRole {
Admin = "admin",
Member = "member",
NoAccess = "no-access",
- Custom = "custom"
+ Custom = "custom",
+ CertManagerAdmin = "cert-manager-admin",
+ CertManagerGuest = "cert-manager-guest"
}
export enum OrgMembershipStatus {
@@ -341,6 +345,17 @@ export enum ProjectMembershipRole {
KmsCryptographicOperator = "cryptographic-operator"
}
+export enum ApplicationMembershipRole {
+ Admin = "admin",
+ Operator = "operator",
+ Auditor = "auditor",
+ Custom = "custom"
+}
+
+export enum ResourceType {
+ CertificateApplication = "certificate-application"
+}
+
export enum SecretEncryptionAlgo {
AES_256_GCM = "aes-256-gcm"
}
@@ -432,6 +447,8 @@ export enum AccessScope {
Project = "project"
}
+export const RESOURCE_SCOPE = "resource";
+
export type AccessScopeData =
| {
scope: AccessScope.Organization;
diff --git a/backend/src/db/schemas/organizations.ts b/backend/src/db/schemas/organizations.ts
index 6ea136bb43..76ad1aa180 100644
--- a/backend/src/db/schemas/organizations.ts
+++ b/backend/src/db/schemas/organizations.ts
@@ -42,7 +42,8 @@ export const OrganizationsSchema = z.object({
parentOrgId: z.string().uuid().nullable().optional(),
rootOrgId: z.string().uuid().nullable().optional(),
blockDuplicateSecretSyncDestinations: z.boolean().default(false),
- secretShareBrandConfig: z.unknown().nullable().optional()
+ secretShareBrandConfig: z.unknown().nullable().optional(),
+ defaultCertManagerProjectId: z.string().nullable().optional()
});
export type TOrganizations = z.infer<typeof OrganizationsSchema>;
diff --git a/backend/src/db/schemas/pki-acme-accounts.ts b/backend/src/db/schemas/pki-acme-accounts.ts
index 69b1ffe499..df8ec1f080 100644
--- a/backend/src/db/schemas/pki-acme-accounts.ts
+++ b/backend/src/db/schemas/pki-acme-accounts.ts
@@ -15,7 +15,8 @@ export const PkiAcmeAccountsSchema = z.object({
publicKeyThumbprint: z.string(),
alg: z.string(),
createdAt: z.date(),
- updatedAt: z.date()
+ updatedAt: z.date(),
+ applicationProfileId: z.string().uuid().nullable().optional()
});
export type TPkiAcmeAccounts = z.infer<typeof PkiAcmeAccountsSchema>;
diff --git a/backend/src/db/schemas/pki-alerts-v2.ts b/backend/src/db/schemas/pki-alerts-v2.ts
index 25804d1fc8..dbf3f027ca 100644
--- a/backend/src/db/schemas/pki-alerts-v2.ts
+++ b/backend/src/db/schemas/pki-alerts-v2.ts
@@ -18,7 +18,8 @@ export const PkiAlertsV2Schema = z.object({
projectId: z.string(),
createdAt: z.date(),
updatedAt: z.date(),
- notificationConfig: z.unknown().nullable().optional()
+ notificationConfig: z.unknown().nullable().optional(),
+ applicationId: z.string().uuid().nullable().optional()
});
export type TPkiAlertsV2 = z.infer<typeof PkiAlertsV2Schema>;
diff --git a/backend/src/db/schemas/pki-application-profiles.ts b/backend/src/db/schemas/pki-application-profiles.ts
new file mode 100644
index 0000000000..1d84990391
--- /dev/null
+++ b/backend/src/db/schemas/pki-application-profiles.ts
@@ -0,0 +1,26 @@
+// 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 PkiApplicationProfilesSchema = z.object({
+ id: z.string().uuid(),
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid(),
+ estConfigId: z.string().uuid().nullable().optional(),
+ apiConfigId: z.string().uuid().nullable().optional(),
+ acmeConfigId: z.string().uuid().nullable().optional(),
+ scepConfigId: z.string().uuid().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TPkiApplicationProfiles = z.infer<typeof PkiApplicationProfilesSchema>;
+export type TPkiApplicationProfilesInsert = Omit<z.input<typeof PkiApplicationProfilesSchema>, TImmutableDBKeys>;
+export type TPkiApplicationProfilesUpdate = Partial<
+ Omit<z.input<typeof PkiApplicationProfilesSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/pki-applications.ts b/backend/src/db/schemas/pki-applications.ts
new file mode 100644
index 0000000000..65fb914ff5
--- /dev/null
+++ b/backend/src/db/schemas/pki-applications.ts
@@ -0,0 +1,22 @@
+// 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 PkiApplicationsSchema = z.object({
+ id: z.string().uuid(),
+ projectId: z.string(),
+ name: z.string(),
+ slug: z.string(),
+ description: z.string().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TPkiApplications = z.infer<typeof PkiApplicationsSchema>;
+export type TPkiApplicationsInsert = Omit<z.input<typeof PkiApplicationsSchema>, TImmutableDBKeys>;
+export type TPkiApplicationsUpdate = Partial<Omit<z.input<typeof PkiApplicationsSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/pki-scep-transactions.ts b/backend/src/db/schemas/pki-scep-transactions.ts
index 841e7623f3..970a5e5437 100644
--- a/backend/src/db/schemas/pki-scep-transactions.ts
+++ b/backend/src/db/schemas/pki-scep-transactions.ts
@@ -19,7 +19,8 @@ export const PkiScepTransactionsSchema = z.object({
clientCipherOid: z.string().nullable().optional(),
expiresAt: z.date(),
createdAt: z.date(),
- updatedAt: z.date()
+ updatedAt: z.date(),
+ applicationId: z.string().uuid().nullable().optional()
});
export type TPkiScepTransactions = z.infer<typeof PkiScepTransactionsSchema>;
diff --git a/backend/src/db/schemas/pki-syncs.ts b/backend/src/db/schemas/pki-syncs.ts
index d4ef2ed6da..79ad9a2092 100644
--- a/backend/src/db/schemas/pki-syncs.ts
+++ b/backend/src/db/schemas/pki-syncs.ts
@@ -32,7 +32,8 @@ export const PkiSyncsSchema = z.object({
removeStatus: z.string().nullable().optional(),
lastRemoveJobId: z.string().nullable().optional(),
lastRemoveMessage: z.string().nullable().optional(),
- lastRemovedAt: z.date().nullable().optional()
+ lastRemovedAt: z.date().nullable().optional(),
+ applicationId: z.string().uuid().nullable().optional()
});
export type TPkiSyncs = z.infer<typeof PkiSyncsSchema>;
diff --git a/backend/src/ee/routes/est/certificate-est-router.ts b/backend/src/ee/routes/est/certificate-est-router.ts
index ae216f32a9..aa67edf39c 100644
--- a/backend/src/ee/routes/est/certificate-est-router.ts
+++ b/backend/src/ee/routes/est/certificate-est-router.ts
@@ -55,6 +55,17 @@ export const registerCertificateEstRouter = async (server: FastifyZodProvider) =
}
});
+ server.addHook("onRequest", async (req, res) => {
+ const urlPath = req.url.split("?")[0];
+ const lastFragment = urlPath.split("/").pop() ?? "";
+ if (lastFragment === "simpleenroll" || lastFragment === "simplereenroll") {
+ const contentType = (req.headers["content-type"] ?? "").toString().toLowerCase().split(";")[0].trim();
+ if (contentType && contentType !== "application/pkcs10") {
+ await res.code(415).type("text/plain").send("Content-Type must be application/pkcs10");
+ }
+ }
+ });
+
// Authenticate EST client using Passphrase
// Using preHandler instead of onRequest ensures rate limiting (preValidation) runs first
server.addHook("preHandler", async (req, res) => {
@@ -64,9 +75,10 @@ export const registerCertificateEstRouter = async (server: FastifyZodProvider) =
// (e.g., /simpleenroll?foo=/cacerts would otherwise match "cacerts")
const urlPath = req.url.split("?")[0];
const urlFragments = urlPath.split("/");
+ const lastFragment = urlFragments[urlFragments.length - 1];
// cacerts endpoint should not have any authentication
- if (urlFragments[urlFragments.length - 1] === "cacerts") {
+ if (lastFragment === "cacerts") {
return;
}
@@ -93,28 +105,41 @@ export const registerCertificateEstRouter = async (server: FastifyZodProvider) =
return;
}
- const identifier = urlFragments.slice(-2)[0];
-
- const identifierType = await getIdentifierType(identifier);
- if (!identifierType) {
- res.raw.statusCode = 404;
- res.raw.setHeader("Content-Type", "text/plain");
- res.raw.write("Certificate template or profile not found");
- res.raw.flushHeaders();
- return;
- }
+ const appPathIdx = urlFragments.indexOf("applications");
+ const isAppScoped =
+ appPathIdx !== -1 && urlFragments[appPathIdx + 2] === "profiles" && urlFragments[appPathIdx + 4];
let estConfig;
- if (identifierType === "profile") {
+ if (isAppScoped) {
+ const applicationId = urlFragments[appPathIdx + 1];
+ const profileId = urlFragments[appPathIdx + 3];
estConfig = await server.services.certificateProfile.getEstConfigurationByProfile({
- profileId: identifier,
+ profileId,
+ applicationId,
isInternal: true
});
} else {
- estConfig = await server.services.certificateTemplate.getEstConfiguration({
- isInternal: true,
- certificateTemplateId: identifier
- });
+ const identifier = urlFragments.slice(-2)[0];
+ const identifierType = await getIdentifierType(identifier);
+ if (!identifierType) {
+ res.raw.statusCode = 404;
+ res.raw.setHeader("Content-Type", "text/plain");
+ res.raw.write("Certificate template or profile not found");
+ res.raw.flushHeaders();
+ return;
+ }
+
+ if (identifierType === "profile") {
+ estConfig = await server.services.certificateProfile.getEstConfigurationByProfile({
+ profileId: identifier,
+ isInternal: true
+ });
+ } else {
+ estConfig = await server.services.certificateTemplate.getEstConfiguration({
+ isInternal: true,
+ certificateTemplateId: identifier
+ });
+ }
}
if (!estConfig.isEnabled) {
@@ -262,4 +287,75 @@ export const registerCertificateEstRouter = async (server: FastifyZodProvider) =
});
}
});
+
+ server.route({
+ method: "POST",
+ url: "/applications/:applicationId/profiles/:profileId/simpleenroll",
+ config: { rateLimit: writeLimit },
+ schema: {
+ body: z.string().min(1),
+ params: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+ }),
+ response: { 200: z.string() }
+ },
+ handler: async (req, res) => {
+ void res.header("Content-Type", "application/pkcs7-mime; smime-type=certs-only");
+ void res.header("Content-Transfer-Encoding", "base64");
+ const { applicationId, profileId } = req.params;
+ return server.services.certificateEstV3.simpleEnrollByProfile({
+ csr: req.body,
+ profileId,
+ applicationId,
+ sslClientCert: req.headers[appCfg.SSL_CLIENT_CERTIFICATE_HEADER_KEY] as string
+ });
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/applications/:applicationId/profiles/:profileId/simplereenroll",
+ config: { rateLimit: writeLimit },
+ schema: {
+ body: z.string().min(1),
+ params: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+ }),
+ response: { 200: z.string() }
+ },
+ handler: async (req, res) => {
+ void res.header("Content-Type", "application/pkcs7-mime; smime-type=certs-only");
+ void res.header("Content-Transfer-Encoding", "base64");
+ const { applicationId, profileId } = req.params;
+ return server.services.certificateEstV3.simpleReenrollByProfile({
+ csr: req.body,
+ profileId,
+ applicationId,
+ sslClientCert: req.headers[appCfg.SSL_CLIENT_CERTIFICATE_HEADER_KEY] as string
+ });
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/applications/:applicationId/profiles/:profileId/cacerts",
+ config: { rateLimit: readLimit },
+ schema: {
+ params: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+ }),
+ response: { 200: z.string() }
+ },
+ handler: async (req, res) => {
+ void res.header("Content-Type", "application/pkcs7-mime; smime-type=certs-only");
+ void res.header("Content-Transfer-Encoding", "base64");
+ return server.services.certificateEstV3.getCaCertsByProfile({
+ profileId: req.params.profileId,
+ applicationId: req.params.applicationId
+ });
+ }
+ });
};
diff --git a/backend/src/ee/routes/scep/pki-scep-router.ts b/backend/src/ee/routes/scep/pki-scep-router.ts
index f7f27e1f37..8838bc12dc 100644
--- a/backend/src/ee/routes/scep/pki-scep-router.ts
+++ b/backend/src/ee/routes/scep/pki-scep-router.ts
@@ -158,4 +158,86 @@ export const registerPkiScepRouter = async (server: FastifyZodProvider) => {
return res.send(result.challenge);
}
});
+
+ server.route({
+ method: "GET",
+ url: "/applications/:applicationId/profiles/:profileId/pkiclient.exe",
+ config: { rateLimit: readLimit },
+ schema: {
+ params: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+ }),
+ querystring: z.object({
+ operation: z.string(),
+ message: z.string().optional()
+ })
+ },
+ handler: async (req, res) => {
+ const { applicationId, profileId } = req.params;
+ const { operation, message: messageBase64 } = req.query;
+
+ switch (operation) {
+ case "GetCACaps": {
+ const caps = await server.services.pkiScep.getCaCaps({ profileId, applicationId });
+ void res.header("Content-Type", "text/plain");
+ return caps;
+ }
+ case "GetCACert": {
+ const certBundle = await server.services.pkiScep.getCaCert({ profileId, applicationId });
+ void res.header("Content-Type", "application/x-x509-ca-ra-cert");
+ return res.send(certBundle);
+ }
+ case "PKIOperation": {
+ if (!messageBase64) {
+ throw new BadRequestError({ message: "Missing message parameter for PKIOperation" });
+ }
+ const messageBuffer = Buffer.from(messageBase64, "base64");
+ const clientIp = req.ip || "unknown";
+ const response = await server.services.pkiScep.handlePkiOperation({
+ profileId,
+ applicationId,
+ message: messageBuffer,
+ clientIp
+ });
+ void res.header("Content-Type", "application/x-pki-message");
+ return res.send(response);
+ }
+ default:
+ throw new BadRequestError({ message: `Unsupported SCEP operation: ${operation}` });
+ }
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/applications/:applicationId/profiles/:profileId/pkiclient.exe",
+ config: { rateLimit: writeLimit },
+ schema: {
+ params: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+ }),
+ querystring: z.object({ operation: z.string().optional() })
+ },
+ handler: async (req, res) => {
+ const { applicationId, profileId } = req.params;
+ const clientIp = req.ip || "unknown";
+ const body = req.body as Buffer;
+
+ if (!body || body.length === 0) {
+ throw new BadRequestError({ message: "Empty PKIOperation request body" });
+ }
+
+ const response = await server.services.pkiScep.handlePkiOperation({
+ profileId,
+ applicationId,
+ message: body,
+ clientIp
+ });
+
+ void res.header("Content-Type", "application/x-pki-message");
+ return res.send(response);
+ }
+ });
};
diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.ts
index 0b151a42fb..64ef6961cc 100644
--- a/backend/src/ee/routes/v1/index.ts
+++ b/backend/src/ee/routes/v1/index.ts
@@ -1,4 +1,6 @@
import { registerProjectTemplateRouter } from "@app/ee/routes/v1/project-template-router";
+import { blockCertManagerProjectAccess } from "@app/server/plugins/block-cert-manager-project-access";
+import { injectCertManagerProjectId } from "@app/server/plugins/inject-cert-manager-project-id";
import { registerAccessApprovalPolicyRouter } from "./access-approval-policy-router";
import { registerAccessApprovalRequestRouter } from "./access-approval-request-router";
@@ -90,6 +92,7 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
await server.register(
async (projectRouter) => {
+ await projectRouter.register(blockCertManagerProjectAccess);
await projectRouter.register(registerProjectRoleRouter);
await projectRouter.register(registerTrustedIpRouter);
await projectRouter.register(registerAssumePrivilegeRouter);
@@ -128,6 +131,8 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
await server.register(
async (pkiRouter) => {
+ await pkiRouter.register(injectCertManagerProjectId);
+
await pkiRouter.register(registerCaCrlRouter, { prefix: "/crl" });
await pkiRouter.register(registerPkiAcmeRouter, { prefix: "/acme" });
await pkiRouter.register(registerPkiDiscoveryRouter, { prefix: "/discovery-jobs" });
diff --git a/backend/src/ee/routes/v1/pki-acme-router.ts b/backend/src/ee/routes/v1/pki-acme-router.ts
index 3effecef1c..bb5eacb4f6 100644
--- a/backend/src/ee/routes/v1/pki-acme-router.ts
+++ b/backend/src/ee/routes/v1/pki-acme-router.ts
@@ -25,11 +25,6 @@ const SharedParamsSchema = z.object({
profileId: z.string().uuid()
});
-export interface MyRequestInterface {
- Params: { profileId: string; accountId?: string };
- Body: TRawJwsPayload;
-}
-
export const registerPkiAcmeRouter = async (server: FastifyZodProvider) => {
const validateExistingAccount = async <
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -484,4 +479,56 @@ export const registerPkiAcmeRouter = async (server: FastifyZodProvider) => {
);
}
});
+
+ const AppScopedParams = z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+ });
+
+ server.route({
+ method: "GET",
+ url: "/applications/:applicationId/profiles/:profileId/directory",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.PkiAcme],
+ description: "ACME Directory - provides URLs for the client to make API calls to",
+ params: AppScopedParams,
+ response: { 200: GetAcmeDirectoryResponseSchema }
+ },
+ handler: async (req) => server.services.pkiAcme.getAcmeDirectory(req.params.profileId, req.params.applicationId)
+ });
+
+ server.route({
+ method: "POST",
+ url: "/applications/:applicationId/profiles/:profileId/new-account",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.PkiAcme],
+ description: "ACME New Account - register a new account or find existing one",
+ params: AppScopedParams,
+ body: RawJwsPayloadSchema,
+ response: { 201: CreateAcmeAccountResponseSchema }
+ },
+ handler: async (req, res) => {
+ const { payload, protectedHeader } = await server.services.pkiAcme.validateNewAccountJwsPayload({
+ url: new URL(req.url, `${req.protocol}://${req.hostname}`),
+ rawJwsPayload: req.body
+ });
+ const { alg, jwk } = protectedHeader;
+ return sendAcmeResponse(
+ res,
+ req.params.profileId,
+ await server.services.pkiAcme.createAcmeAccount({
+ profileId: req.params.profileId,
+ applicationId: req.params.applicationId,
+ alg,
+ jwk: jwk!,
+ payload,
+ auditLogInfo: req.auditLogInfo
+ })
+ );
+ }
+ });
};
diff --git a/backend/src/ee/routes/v1/pki-discovery-router.ts b/backend/src/ee/routes/v1/pki-discovery-router.ts
index 3aed8c7536..7695e8070d 100644
--- a/backend/src/ee/routes/v1/pki-discovery-router.ts
+++ b/backend/src/ee/routes/v1/pki-discovery-router.ts
@@ -75,7 +75,6 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
operationId: "createPkiDiscovery",
description: "Create a new PKI discovery configuration",
body: z.object({
- projectId: z.string().describe("The ID of the project"),
name: slugSchema({ field: "Name", max: 100 }).describe("Name of the discovery configuration"),
description: z.string().max(500).optional().describe("Description of the discovery configuration"),
discoveryType: z
@@ -103,8 +102,9 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
throw new BadRequestError({ message: validation.error || "Invalid target configuration" });
}
+ const projectId = req.certManagerProjectId;
const discovery = await server.services.pkiDiscovery.createDiscovery({
- projectId: req.body.projectId,
+ projectId,
name: req.body.name,
description: req.body.description,
discoveryType: req.body.discoveryType,
@@ -120,7 +120,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.body.projectId,
+ projectId,
event: {
type: EventType.CREATE_PKI_DISCOVERY,
metadata: {
@@ -147,7 +147,6 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
operationId: "listPkiDiscoveries",
description: "List PKI discovery configurations for a project",
querystring: z.object({
- projectId: z.string().describe("The ID of the project"),
offset: z.coerce.number().min(0).optional().default(0).describe("Pagination offset"),
limit: z.coerce.number().min(1).max(100).optional().default(25).describe("Pagination limit"),
search: z.string().optional().describe("Search filter for name or description")
@@ -165,8 +164,9 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
}
},
handler: async (req) => {
+ const projectId = req.certManagerProjectId;
const { discoveries, totalCount } = await server.services.pkiDiscovery.listDiscoveries({
- projectId: req.query.projectId,
+ projectId,
offset: req.query.offset,
limit: req.query.limit,
search: req.query.search,
@@ -178,7 +178,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.query.projectId,
+ projectId,
event: {
type: EventType.GET_PKI_DISCOVERIES,
metadata: {
diff --git a/backend/src/ee/routes/v1/pki-installation-router.ts b/backend/src/ee/routes/v1/pki-installation-router.ts
index 8d645d11c3..fa6959778f 100644
--- a/backend/src/ee/routes/v1/pki-installation-router.ts
+++ b/backend/src/ee/routes/v1/pki-installation-router.ts
@@ -21,7 +21,6 @@ export const registerPkiInstallationRouter = async (server: FastifyZodProvider)
operationId: "listPkiInstallations",
description: "List PKI certificate installations for a project",
querystring: z.object({
- projectId: z.string().describe("The ID of the project"),
discoveryId: z.string().uuid().optional().describe("Filter by discovery configuration ID"),
certificateId: z.string().uuid().optional().describe("Filter by certificate ID"),
offset: z.coerce.number().min(0).optional().default(0).describe("Pagination offset"),
@@ -42,8 +41,9 @@ export const registerPkiInstallationRouter = async (server: FastifyZodProvider)
}
},
handler: async (req) => {
+ const projectId = req.certManagerProjectId;
const { installations, totalCount } = await server.services.pkiInstallation.listInstallations({
- projectId: req.query.projectId,
+ projectId,
discoveryId: req.query.discoveryId,
certificateId: req.query.certificateId,
offset: req.query.offset,
@@ -57,7 +57,7 @@ export const registerPkiInstallationRouter = async (server: FastifyZodProvider)
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.query.projectId,
+ projectId,
event: {
type: EventType.GET_PKI_INSTALLATIONS,
metadata: {
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 3d3b249565..51755bdaaa 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -435,6 +435,30 @@ export enum EventType {
DELETE_CERTIFICATE_PROFILE = "delete-certificate-profile",
GET_CERTIFICATE_PROFILE = "get-certificate-profile",
LIST_CERTIFICATE_PROFILES = "list-certificate-profiles",
+ CREATE_PKI_APPLICATION = "create-pki-application",
+ UPDATE_PKI_APPLICATION = "update-pki-application",
+ DELETE_PKI_APPLICATION = "delete-pki-application",
+ GET_PKI_APPLICATION = "get-pki-application",
+ LIST_PKI_APPLICATIONS = "list-pki-applications",
+ ATTACH_PKI_APPLICATION_PROFILES = "attach-pki-application-profiles",
+ DETACH_PKI_APPLICATION_PROFILE = "detach-pki-application-profile",
+ ADD_PKI_APPLICATION_MEMBER = "add-pki-application-member",
+ UPDATE_PKI_APPLICATION_MEMBER_ROLE = "update-pki-application-member-role",
+ REMOVE_PKI_APPLICATION_MEMBER = "remove-pki-application-member",
+ LIST_PKI_APPLICATION_MEMBERS = "list-pki-application-members",
+ GET_PKI_APPLICATION_ENROLLMENT = "get-pki-application-enrollment",
+ SET_PKI_APPLICATION_API_ENROLLMENT = "set-pki-application-api-enrollment",
+ CLEAR_PKI_APPLICATION_API_ENROLLMENT = "clear-pki-application-api-enrollment",
+ SET_PKI_APPLICATION_EST_ENROLLMENT = "set-pki-application-est-enrollment",
+ CLEAR_PKI_APPLICATION_EST_ENROLLMENT = "clear-pki-application-est-enrollment",
+ SET_PKI_APPLICATION_ACME_ENROLLMENT = "set-pki-application-acme-enrollment",
+ CLEAR_PKI_APPLICATION_ACME_ENROLLMENT = "clear-pki-application-acme-enrollment",
+ REVEAL_PKI_APPLICATION_ACME_EAB_SECRET = "reveal-pki-application-acme-eab-secret",
+ ROTATE_PKI_APPLICATION_ACME_EAB_SECRET = "rotate-pki-application-acme-eab-secret",
+ SET_PKI_APPLICATION_SCEP_ENROLLMENT = "set-pki-application-scep-enrollment",
+ CLEAR_PKI_APPLICATION_SCEP_ENROLLMENT = "clear-pki-application-scep-enrollment",
+ GET_CERT_MANAGER_INSTANCE_STATE = "get-cert-manager-instance-state",
+ SET_CERT_MANAGER_ACTIVE_PROJECT = "set-cert-manager-active-project",
ISSUE_CERTIFICATE_FROM_PROFILE = "issue-certificate-from-profile",
SIGN_CERTIFICATE_FROM_PROFILE = "sign-certificate-from-profile",
ORDER_CERTIFICATE_FROM_PROFILE = "order-certificate-from-profile",
@@ -2993,6 +3017,7 @@ interface CreatePkiAlert {
metadata: {
pkiAlertId: string;
pkiCollectionId?: string;
+ applicationId?: string;
name: string;
alertBefore?: string;
eventType: PkiAlertEventType;
@@ -3003,6 +3028,7 @@ interface GetPkiAlert {
type: EventType.GET_PKI_ALERT;
metadata: {
pkiAlertId: string;
+ applicationId?: string;
};
}
@@ -3011,6 +3037,7 @@ interface UpdatePkiAlert {
metadata: {
pkiAlertId: string;
pkiCollectionId?: string;
+ applicationId?: string;
name?: string;
alertBefore?: string;
eventType?: PkiAlertEventType;
@@ -3021,6 +3048,7 @@ interface DeletePkiAlert {
type: EventType.DELETE_PKI_ALERT;
metadata: {
pkiAlertId: string;
+ applicationId?: string;
};
}
@@ -3437,6 +3465,211 @@ interface DeleteCertificateProfile {
};
}
+interface CreatePkiApplication {
+ type: EventType.CREATE_PKI_APPLICATION;
+ metadata: {
+ applicationId: string;
+ slug: string;
+ name: string;
+ profileIds?: string[];
+ };
+}
+
+interface UpdatePkiApplication {
+ type: EventType.UPDATE_PKI_APPLICATION;
+ metadata: {
+ applicationId: string;
+ slug: string;
+ };
+}
+
+interface DeletePkiApplication {
+ type: EventType.DELETE_PKI_APPLICATION;
+ metadata: {
+ applicationId: string;
+ slug: string;
+ };
+}
+
+interface GetPkiApplication {
+ type: EventType.GET_PKI_APPLICATION;
+ metadata: {
+ applicationId: string;
+ slug: string;
+ };
+}
+
+interface ListPkiApplications {
+ type: EventType.LIST_PKI_APPLICATIONS;
+ metadata: {
+ projectId: string;
+ };
+}
+
+interface AttachPkiApplicationProfiles {
+ type: EventType.ATTACH_PKI_APPLICATION_PROFILES;
+ metadata: {
+ applicationId: string;
+ profileIds: string[];
+ };
+}
+
+interface DetachPkiApplicationProfile {
+ type: EventType.DETACH_PKI_APPLICATION_PROFILE;
+ metadata: {
+ applicationId: string;
+ profileId: string;
+ };
+}
+
+interface AddPkiApplicationMember {
+ type: EventType.ADD_PKI_APPLICATION_MEMBER;
+ metadata: {
+ applicationId: string;
+ membershipId: string;
+ userId?: string;
+ identityId?: string;
+ groupId?: string;
+ role: string;
+ };
+}
+
+interface UpdatePkiApplicationMemberRole {
+ type: EventType.UPDATE_PKI_APPLICATION_MEMBER_ROLE;
+ metadata: {
+ applicationId: string;
+ membershipId: string;
+ role: string;
+ };
+}
+
+interface RemovePkiApplicationMember {
+ type: EventType.REMOVE_PKI_APPLICATION_MEMBER;
+ metadata: {
+ applicationId: string;
+ membershipId: string;
+ };
+}
+
+interface ListPkiApplicationMembers {
+ type: EventType.LIST_PKI_APPLICATION_MEMBERS;
+ metadata: {
+ applicationId: string;
+ };
+}
+
+interface GetPkiApplicationEnrollment {
+ type: EventType.GET_PKI_APPLICATION_ENROLLMENT;
+ metadata: {
+ applicationId: string;
+ profileId: string;
+ };
+}
+
+interface SetPkiApplicationApiEnrollment {
+ type: EventType.SET_PKI_APPLICATION_API_ENROLLMENT;
+ metadata: {
+ applicationId: string;
+ profileId: string;
+ autoRenew: boolean;
+ renewBeforeDays: number | null;
+ };
+}
+
+interface ClearPkiApplicationApiEnrollment {
+ type: EventType.CLEAR_PKI_APPLICATION_API_ENROLLMENT;
+ metadata: {
+ applicationId: string;
+ profileId: string;
+ };
+}
+
+interface SetPkiApplicationEstEnrollment {
+ type: EventType.SET_PKI_APPLICATION_EST_ENROLLMENT;
+ metadata: {
+ applicationId: string;
+ profileId: string;
+ disableBootstrapCaValidation: boolean;
+ };
+}
+
+interface ClearPkiApplicationEstEnrollment {
+ type: EventType.CLEAR_PKI_APPLICATION_EST_ENROLLMENT;
+ metadata: {
+ applicationId: string;
+ profileId: string;
+ };
+}
+
+interface SetPkiApplicationAcmeEnrollment {
+ type: EventType.SET_PKI_APPLICATION_ACME_ENROLLMENT;
+ metadata: {
+ applicationId: string;
+ profileId: string;
+ skipDnsOwnershipVerification: boolean;
+ skipEabBinding: boolean;
+ };
+}
+
+interface ClearPkiApplicationAcmeEnrollment {
+ type: EventType.CLEAR_PKI_APPLICATION_ACME_ENROLLMENT;
+ metadata: {
+ applicationId: string;
+ profileId: string;
+ };
+}
+
+interface RevealPkiApplicationAcmeEabSecret {
+ type: EventType.REVEAL_PKI_APPLICATION_ACME_EAB_SECRET;
+ metadata: {
+ applicationId: string;
+ profileId: string;
+ };
+}
+
+interface RotatePkiApplicationAcmeEabSecret {
+ type: EventType.ROTATE_PKI_APPLICATION_ACME_EAB_SECRET;
+ metadata: {
+ applicationId: string;
+ profileId: string;
+ };
+}
+
+interface SetPkiApplicationScepEnrollment {
+ type: EventType.SET_PKI_APPLICATION_SCEP_ENROLLMENT;
+ metadata: {
+ applicationId: string;
+ profileId: string;
+ challengeType: string;
+ };
+}
+
+interface ClearPkiApplicationScepEnrollment {
+ type: EventType.CLEAR_PKI_APPLICATION_SCEP_ENROLLMENT;
+ metadata: {
+ applicationId: string;
+ profileId: string;
+ };
+}
+
+interface GetCertManagerInstanceState {
+ type: EventType.GET_CERT_MANAGER_INSTANCE_STATE;
+ metadata: {
+ activeProjectId: string | null;
+ projectCount: number;
+ isMultiInstance: boolean;
+ };
+}
+
+interface SetCertManagerActiveProject {
+ type: EventType.SET_CERT_MANAGER_ACTIVE_PROJECT;
+ metadata: {
+ activeProjectId: string;
+ previousActiveProjectId: string | null;
+ projectName: string;
+ };
+}
+
interface GetCertificateProfile {
type: EventType.GET_CERTIFICATE_PROFILE;
metadata: {
@@ -3927,6 +4160,7 @@ interface GetPkiSyncEvent {
metadata: {
destination: string;
syncId: string;
+ applicationId?: string;
};
}
@@ -3946,6 +4180,7 @@ interface CreatePkiSyncEvent {
pkiSyncId: string;
name: string;
destination: string;
+ applicationId?: string;
};
}
@@ -3954,6 +4189,7 @@ interface UpdatePkiSyncEvent {
metadata: {
pkiSyncId: string;
name: string;
+ applicationId?: string;
};
}
@@ -3963,6 +4199,7 @@ interface DeletePkiSyncEvent {
pkiSyncId: string;
name: string;
destination: string;
+ applicationId?: string;
};
}
@@ -6534,6 +6771,30 @@ export type Event =
| CreateCertificateProfile
| UpdateCertificateProfile
| DeleteCertificateProfile
+ | CreatePkiApplication
+ | UpdatePkiApplication
+ | DeletePkiApplication
+ | GetPkiApplication
+ | ListPkiApplications
+ | AttachPkiApplicationProfiles
+ | DetachPkiApplicationProfile
+ | AddPkiApplicationMember
+ | UpdatePkiApplicationMemberRole
+ | RemovePkiApplicationMember
+ | ListPkiApplicationMembers
+ | GetPkiApplicationEnrollment
+ | SetPkiApplicationApiEnrollment
+ | ClearPkiApplicationApiEnrollment
+ | SetPkiApplicationEstEnrollment
+ | ClearPkiApplicationEstEnrollment
+ | SetPkiApplicationAcmeEnrollment
+ | ClearPkiApplicationAcmeEnrollment
+ | RevealPkiApplicationAcmeEabSecret
+ | RotatePkiApplicationAcmeEabSecret
+ | SetPkiApplicationScepEnrollment
+ | ClearPkiApplicationScepEnrollment
+ | GetCertManagerInstanceState
+ | SetCertManagerActiveProject
| GetCertificateProfile
| ListCertificateProfiles
| GetCertificateProfileLatestActiveBundle
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index 35045cd7b2..f51c18b799 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -3,6 +3,7 @@ import { AbilityBuilder, createMongoAbility, MongoAbility } from "@casl/ability"
import {
ProjectPermissionActions,
ProjectPermissionAppConnectionActions,
+ ProjectPermissionApplicationActions,
ProjectPermissionApprovalRequestActions,
ProjectPermissionApprovalRequestGrantActions,
ProjectPermissionAuditLogsActions,
@@ -42,6 +43,15 @@ import {
ProjectPermissionSshHostActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
+import {
+ ResourcePermissionApplicationActions,
+ ResourcePermissionApplicationEnrollmentActions,
+ ResourcePermissionApprovalPolicyActions,
+ ResourcePermissionCertificateActions,
+ ResourcePermissionPkiSyncActions,
+ ResourcePermissionSet,
+ ResourcePermissionSub
+} from "@app/ee/services/permission/resource-permission";
const buildAdminPermissionRules = () => {
const { can, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);
@@ -153,6 +163,15 @@ const buildAdminPermissionRules = () => {
ProjectPermissionSub.CertificateProfiles
);
+ can(
+ [
+ ProjectPermissionApplicationActions.Read,
+ ProjectPermissionApplicationActions.List,
+ ProjectPermissionApplicationActions.Create
+ ],
+ ProjectPermissionSub.Application
+ );
+
can(
[ProjectPermissionCommitsActions.Read, ProjectPermissionCommitsActions.PerformRollback],
ProjectPermissionSub.Commits
@@ -616,6 +635,15 @@ const buildMemberPermissionRules = () => {
ProjectPermissionSub.CertificateProfiles
);
+ can(
+ [
+ ProjectPermissionApplicationActions.Read,
+ ProjectPermissionApplicationActions.List,
+ ProjectPermissionApplicationActions.Create
+ ],
+ ProjectPermissionSub.Application
+ );
+
can([ProjectPermissionActions.Read], ProjectPermissionSub.PkiAlerts);
can([ProjectPermissionActions.Read], ProjectPermissionSub.PkiCollections);
can(
@@ -772,6 +800,10 @@ const buildViewerPermissionRules = () => {
can(ProjectPermissionActions.Read, ProjectPermissionSub.SshCertificateTemplates);
can(ProjectPermissionSecretSyncActions.Read, ProjectPermissionSub.SecretSyncs);
can(ProjectPermissionPkiSyncActions.Read, ProjectPermissionSub.PkiSyncs);
+ can(
+ [ProjectPermissionApplicationActions.Read, ProjectPermissionApplicationActions.List],
+ ProjectPermissionSub.Application
+ );
can(ProjectPermissionPkiDiscoveryActions.Read, ProjectPermissionSub.PkiDiscovery);
can(ProjectPermissionPkiCertificateInstallationActions.Read, ProjectPermissionSub.PkiCertificateInstallations);
can(ProjectPermissionCodeSigningActions.Read, ProjectPermissionSub.CodeSigners);
@@ -864,3 +896,180 @@ export const sshHostBootstrapPermissions = buildSshHostBootstrapPermissionRules(
// KMS
export const cryptographicOperatorPermissions = buildCryptographicOperatorPermissionRules();
+
+const buildApplicationAdminPermissionRules = () => {
+ const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);
+
+ can(
+ [
+ ResourcePermissionApplicationActions.Read,
+ ResourcePermissionApplicationActions.Edit,
+ ResourcePermissionApplicationActions.Delete,
+ ResourcePermissionApplicationActions.AttachProfile,
+ ResourcePermissionApplicationActions.DetachProfile
+ ],
+ ResourcePermissionSub.Application
+ );
+
+ can(
+ [
+ ResourcePermissionApplicationEnrollmentActions.Read,
+ ResourcePermissionApplicationEnrollmentActions.Edit,
+ ResourcePermissionApplicationEnrollmentActions.RevealAcmeEabSecret,
+ ResourcePermissionApplicationEnrollmentActions.RotateAcmeEabSecret
+ ],
+ ResourcePermissionSub.ApplicationEnrollment
+ );
+
+ can(
+ [
+ ResourcePermissionApprovalPolicyActions.Read,
+ ResourcePermissionApprovalPolicyActions.Create,
+ ResourcePermissionApprovalPolicyActions.Edit,
+ ResourcePermissionApprovalPolicyActions.Delete
+ ],
+ ResourcePermissionSub.ApprovalPolicies
+ );
+
+ can(
+ [
+ ResourcePermissionCertificateActions.Read,
+ ResourcePermissionCertificateActions.List,
+ ResourcePermissionCertificateActions.Create,
+ ResourcePermissionCertificateActions.Edit,
+ ResourcePermissionCertificateActions.Delete,
+ ResourcePermissionCertificateActions.ReadPrivateKey,
+ ResourcePermissionCertificateActions.Import
+ ],
+ ResourcePermissionSub.Certificates
+ );
+
+ can(
+ [
+ ResourcePermissionPkiSyncActions.Read,
+ ResourcePermissionPkiSyncActions.List,
+ ResourcePermissionPkiSyncActions.Create,
+ ResourcePermissionPkiSyncActions.Edit,
+ ResourcePermissionPkiSyncActions.Delete,
+ ResourcePermissionPkiSyncActions.SyncCertificates,
+ ResourcePermissionPkiSyncActions.ImportCertificates,
+ ResourcePermissionPkiSyncActions.RemoveCertificates
+ ],
+ ResourcePermissionSub.PkiSyncs
+ );
+
+ can(
+ [
+ ProjectPermissionActions.Read,
+ ProjectPermissionActions.Create,
+ ProjectPermissionActions.Edit,
+ ProjectPermissionActions.Delete
+ ],
+ ResourcePermissionSub.PkiAlerts
+ );
+
+ can(
+ [ProjectPermissionApprovalRequestActions.Read, ProjectPermissionApprovalRequestActions.Create],
+ ResourcePermissionSub.ApprovalRequests
+ );
+
+ can(
+ [ProjectPermissionApprovalRequestGrantActions.Read, ProjectPermissionApprovalRequestGrantActions.Revoke],
+ ResourcePermissionSub.ApprovalRequestGrants
+ );
+
+ can(
+ [
+ ProjectPermissionMemberActions.Read,
+ ProjectPermissionMemberActions.Create,
+ ProjectPermissionMemberActions.Edit,
+ ProjectPermissionMemberActions.Delete,
+ ProjectPermissionMemberActions.GrantPrivileges,
+ ProjectPermissionMemberActions.AssignRole
+ ],
+ ResourcePermissionSub.Member
+ );
+
+ can(
+ [
+ ProjectPermissionActions.Read,
+ ProjectPermissionActions.Create,
+ ProjectPermissionActions.Edit,
+ ProjectPermissionActions.Delete
+ ],
+ ResourcePermissionSub.Role
+ );
+
+ can(
+ [ProjectPermissionCertificateProfileActions.Read, ProjectPermissionCertificateProfileActions.IssueCert],
+ ProjectPermissionSub.CertificateProfiles
+ );
+
+ can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);
+
+ return rules;
+};
+
+const buildApplicationOperatorPermissionRules = () => {
+ const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);
+
+ can([ResourcePermissionApplicationActions.Read], ResourcePermissionSub.Application);
+ can([ResourcePermissionApplicationEnrollmentActions.Read], ResourcePermissionSub.ApplicationEnrollment);
+ can([ResourcePermissionApprovalPolicyActions.Read], ResourcePermissionSub.ApprovalPolicies);
+
+ can(
+ [
+ ResourcePermissionCertificateActions.Read,
+ ResourcePermissionCertificateActions.List,
+ ResourcePermissionCertificateActions.Create,
+ ResourcePermissionCertificateActions.Edit
+ ],
+ ResourcePermissionSub.Certificates
+ );
+
+ can([ResourcePermissionPkiSyncActions.Read, ResourcePermissionPkiSyncActions.List], ResourcePermissionSub.PkiSyncs);
+ can([ProjectPermissionActions.Read], ResourcePermissionSub.PkiAlerts);
+
+ can(
+ [ProjectPermissionApprovalRequestActions.Read, ProjectPermissionApprovalRequestActions.Create],
+ ResourcePermissionSub.ApprovalRequests
+ );
+ can([ProjectPermissionApprovalRequestGrantActions.Read], ResourcePermissionSub.ApprovalRequestGrants);
+
+ can([ProjectPermissionMemberActions.Read], ResourcePermissionSub.Member);
+ can([ProjectPermissionActions.Read], ResourcePermissionSub.Role);
+
+ can(
+ [ProjectPermissionCertificateProfileActions.Read, ProjectPermissionCertificateProfileActions.IssueCert],
+ ProjectPermissionSub.CertificateProfiles
+ );
+ can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);
+
+ return rules;
+};
+
+const buildApplicationAuditorPermissionRules = () => {
+ const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);
+
+ can([ResourcePermissionApplicationActions.Read], ResourcePermissionSub.Application);
+ can([ResourcePermissionApplicationEnrollmentActions.Read], ResourcePermissionSub.ApplicationEnrollment);
+ can([ResourcePermissionApprovalPolicyActions.Read], ResourcePermissionSub.ApprovalPolicies);
+ can(
+ [ResourcePermissionCertificateActions.Read, ResourcePermissionCertificateActions.List],
+ ResourcePermissionSub.Certificates
+ );
+ can([ResourcePermissionPkiSyncActions.Read, ResourcePermissionPkiSyncActions.List], ResourcePermissionSub.PkiSyncs);
+ can([ProjectPermissionActions.Read], ResourcePermissionSub.PkiAlerts);
+ can([ProjectPermissionApprovalRequestActions.Read], ResourcePermissionSub.ApprovalRequests);
+ can([ProjectPermissionApprovalRequestGrantActions.Read], ResourcePermissionSub.ApprovalRequestGrants);
+ can([ProjectPermissionMemberActions.Read], ResourcePermissionSub.Member);
+ can([ProjectPermissionActions.Read], ResourcePermissionSub.Role);
+ can([ProjectPermissionCertificateProfileActions.Read], ProjectPermissionSub.CertificateProfiles);
+ can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);
+
+ return rules;
+};
+
+export const applicationAdminPermissions = buildApplicationAdminPermissionRules();
+export const applicationOperatorPermissions = buildApplicationOperatorPermissionRules();
+export const applicationAuditorPermissions = buildApplicationAuditorPermissionRules();
diff --git a/backend/src/ee/services/permission/org-permission.ts b/backend/src/ee/services/permission/org-permission.ts
index b28bc990c7..8e62bdca5e 100644
--- a/backend/src/ee/services/permission/org-permission.ts
+++ b/backend/src/ee/services/permission/org-permission.ts
@@ -125,6 +125,12 @@ export enum OrgPermissionEmailDomainActions {
Delete = "delete"
}
+export enum OrgPermissionCertManagerActions {
+ Read = "read",
+ ManageInstance = "manage-instance",
+ ManageSettings = "manage-settings"
+}
+
export enum OrgPermissionSubjects {
Workspace = "workspace",
Project = "project",
@@ -153,7 +159,8 @@ export enum OrgPermissionSubjects {
Relay = "relay",
SecretShare = "secret-share",
SubOrganization = "sub-organization",
- EmailDomains = "email-domains"
+ EmailDomains = "email-domains",
+ CertManager = "certificate-manager"
}
export type AppConnectionSubjectFields = {
@@ -194,7 +201,8 @@ export type OrgPermissionSet =
| [OrgPermissionMachineIdentityAuthTemplateActions, OrgPermissionSubjects.MachineIdentityAuthTemplate]
| [OrgPermissionKmipActions, OrgPermissionSubjects.Kmip]
| [OrgPermissionSecretShareAction, OrgPermissionSubjects.SecretShare]
- | [OrgPermissionEmailDomainActions, OrgPermissionSubjects.EmailDomains];
+ | [OrgPermissionEmailDomainActions, OrgPermissionSubjects.EmailDomains]
+ | [OrgPermissionCertManagerActions, OrgPermissionSubjects.CertManager];
const AppConnectionConditionSchema = z
.object({
@@ -357,6 +365,12 @@ export const OrgPermissionSchema = z.discriminatedUnion("subject", [
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(OrgPermissionEmailDomainActions).describe(
"Describe what action an entity can take."
)
+ }),
+ z.object({
+ subject: z.literal(OrgPermissionSubjects.CertManager).describe("The entity this permission pertains to."),
+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(OrgPermissionCertManagerActions).describe(
+ "Describe what action an entity can take."
+ )
})
]);
@@ -514,6 +528,10 @@ const buildAdminPermission = () => {
can(OrgPermissionEmailDomainActions.VerifyDomain, OrgPermissionSubjects.EmailDomains);
can(OrgPermissionEmailDomainActions.Delete, OrgPermissionSubjects.EmailDomains);
+ can(OrgPermissionCertManagerActions.Read, OrgPermissionSubjects.CertManager);
+ can(OrgPermissionCertManagerActions.ManageInstance, OrgPermissionSubjects.CertManager);
+ can(OrgPermissionCertManagerActions.ManageSettings, OrgPermissionSubjects.CertManager);
+
return rules;
};
@@ -566,6 +584,8 @@ const buildMemberPermission = () => {
OrgPermissionSubjects.MachineIdentityAuthTemplate
);
+ can(OrgPermissionCertManagerActions.Read, OrgPermissionSubjects.CertManager);
+
return rules;
};
@@ -577,3 +597,33 @@ const buildNoAccessPermission = () => {
};
export const orgNoAccessPermissions = buildNoAccessPermission();
+
+const buildCertManagerAdminPermission = () => {
+ const { can, rules } = new AbilityBuilder<MongoAbility<OrgPermissionSet>>(createMongoAbility);
+
+ can(OrgPermissionActions.Read, OrgPermissionSubjects.Member);
+ can(OrgPermissionGroupActions.Read, OrgPermissionSubjects.Groups);
+ can(OrgPermissionActions.Read, OrgPermissionSubjects.Role);
+ can(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);
+ can(OrgPermissionAuditLogsActions.Read, OrgPermissionSubjects.AuditLogs);
+ can(OrgPermissionIdentityActions.Read, OrgPermissionSubjects.Identity);
+ can(OrgPermissionAppConnectionActions.Read, OrgPermissionSubjects.AppConnections);
+ can(OrgPermissionAppConnectionActions.Connect, OrgPermissionSubjects.AppConnections);
+
+ can(OrgPermissionCertManagerActions.Read, OrgPermissionSubjects.CertManager);
+ can(OrgPermissionCertManagerActions.ManageInstance, OrgPermissionSubjects.CertManager);
+ can(OrgPermissionCertManagerActions.ManageSettings, OrgPermissionSubjects.CertManager);
+
+ return rules;
+};
+export const orgCertManagerAdminPermissions = buildCertManagerAdminPermission();
+
+const buildCertManagerGuestPermission = () => {
+ const { can, rules } = new AbilityBuilder<MongoAbility<OrgPermissionSet>>(createMongoAbility);
+ can(OrgPermissionActions.Read, OrgPermissionSubjects.Member);
+ can(OrgPermissionGroupActions.Read, OrgPermissionSubjects.Groups);
+ can(OrgPermissionAuditLogsActions.Read, OrgPermissionSubjects.AuditLogs);
+ can(OrgPermissionCertManagerActions.Read, OrgPermissionSubjects.CertManager);
+ return rules;
+};
+export const orgCertManagerGuestPermissions = buildCertManagerGuestPermission();
diff --git a/backend/src/ee/services/permission/permission-dal.ts b/backend/src/ee/services/permission/permission-dal.ts
index 09b0b71e36..e28ecf3190 100644
--- a/backend/src/ee/services/permission/permission-dal.ts
+++ b/backend/src/ee/services/permission/permission-dal.ts
@@ -7,6 +7,7 @@ import {
AccessScopeData,
MembershipRolesSchema,
MembershipsSchema,
+ RESOURCE_SCOPE,
TableName,
TMemberships,
TRoles
@@ -168,6 +169,14 @@ export interface TPermissionDALFactory {
actorType: ActorType.IDENTITY | ActorType.USER;
tx?: Knex;
}) => Promise<TPermissionDataReturn[]>;
+ getResourceMembership: (dto: {
+ projectId: string;
+ resourceType: string;
+ resourceId: string;
+ actorId: string;
+ actorType: ActorType.IDENTITY | ActorType.USER;
+ tx?: Knex;
+ }) => Promise<TResourceMembershipReturn[]>;
getPermissionFingerprint: (dto: {
projectId: string;
orgId: string;
@@ -176,6 +185,23 @@ export interface TPermissionDALFactory {
}) => Promise<string>;
}
+interface TResourceMembershipReturn extends TMemberships {
+ roles: {
+ id: string;
+ role: string;
+ permissions?: unknown;
+ customRoleId?: string | null;
+ customRoleSlug?: string | null;
+ isTemporary: boolean;
+ temporaryMode?: string | null;
+ temporaryRange?: string | null;
+ temporaryAccessStartTime?: Date | null;
+ temporaryAccessEndTime?: Date | null;
+ createdAt: Date;
+ updatedAt: Date;
+ }[];
+}
+
export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {
const getPermission: TPermissionDALFactory["getPermission"] = async ({ scopeData, tx, actorId, actorType }) => {
try {
@@ -372,6 +398,107 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {
}
};
+ const getResourceMembership: TPermissionDALFactory["getResourceMembership"] = async ({
+ projectId,
+ resourceType,
+ resourceId,
+ actorId,
+ actorType,
+ tx
+ }) => {
+ try {
+ const conn = tx || db.replicaNode();
+
+ const userGroupSubquery = conn(TableName.UserGroupMembership).where("userId", actorId).select("groupId");
+ const identityGroupSubquery = conn(TableName.IdentityGroupMembership)
+ .where("identityId", actorId)
+ .select("groupId");
+
+ const docs = await conn(TableName.Membership)
+ .join(TableName.MembershipRole, `${TableName.Membership}.id`, `${TableName.MembershipRole}.membershipId`)
+ .leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)
+ .where(`${TableName.Membership}.scope`, RESOURCE_SCOPE)
+ .where(`${TableName.Membership}.scopeProjectId`, projectId)
+ .where(`${TableName.Membership}.scopeResourceType`, resourceType)
+ .where(`${TableName.Membership}.scopeResourceId`, resourceId)
+ .where((qb) => {
+ if (actorType === ActorType.USER) {
+ void qb
+ .where(`${TableName.Membership}.actorUserId`, actorId)
+ .orWhereIn(`${TableName.Membership}.actorGroupId`, userGroupSubquery);
+ } else {
+ void qb
+ .where(`${TableName.Membership}.actorIdentityId`, actorId)
+ .orWhereIn(`${TableName.Membership}.actorGroupId`, identityGroupSubquery);
+ }
+ })
+ .select(selectAllTableCols(TableName.Membership))
+ .select(
+ db.ref("id").withSchema(TableName.MembershipRole).as("membershipRoleId"),
+ db.ref("role").withSchema(TableName.MembershipRole).as("membershipRole"),
+ db.ref("customRoleId").withSchema(TableName.MembershipRole).as("membershipCustomRoleId"),
+ db.ref("isTemporary").withSchema(TableName.MembershipRole).as("membershipRoleIsTemporary"),
+ db.ref("temporaryMode").withSchema(TableName.MembershipRole).as("membershipRoleTemporaryMode"),
+ db.ref("temporaryRange").withSchema(TableName.MembershipRole).as("membershipRoleTemporaryRange"),
+ db
+ .ref("temporaryAccessStartTime")
+ .withSchema(TableName.MembershipRole)
+ .as("membershipRoleTemporaryAccessStartTime"),
+ db
+ .ref("temporaryAccessEndTime")
+ .withSchema(TableName.MembershipRole)
+ .as("membershipRoleTemporaryAccessEndTime"),
+ db.ref("createdAt").withSchema(TableName.MembershipRole).as("membershipRoleCreatedAt"),
+ db.ref("updatedAt").withSchema(TableName.MembershipRole).as("membershipRoleUpdatedAt"),
+ db.ref("slug").withSchema(TableName.Role).as("customRoleSlug"),
+ db.ref("permissions").withSchema(TableName.Role).as("customRolePermissions")
+ );
+
+ const data = sqlNestRelationships({
+ data: docs,
+ key: "id",
+ parentMapper: (el) => MembershipsSchema.parse(el),
+ childrenMapper: [
+ {
+ key: "membershipRoleId",
+ label: "roles" as const,
+ mapper: ({
+ membershipRoleId,
+ membershipRole,
+ membershipCustomRoleId,
+ membershipRoleIsTemporary,
+ membershipRoleTemporaryMode,
+ membershipRoleTemporaryRange,
+ membershipRoleTemporaryAccessStartTime,
+ membershipRoleTemporaryAccessEndTime,
+ membershipRoleCreatedAt,
+ membershipRoleUpdatedAt,
+ customRoleSlug,
+ customRolePermissions
+ }) => ({
+ id: membershipRoleId,
+ role: membershipRole,
+ customRoleId: membershipCustomRoleId,
+ customRoleSlug: customRoleSlug as string | null | undefined,
+ permissions: customRolePermissions,
+ isTemporary: Boolean(membershipRoleIsTemporary),
+ temporaryMode: membershipRoleTemporaryMode,
+ temporaryRange: membershipRoleTemporaryRange,
+ temporaryAccessStartTime: membershipRoleTemporaryAccessStartTime,
+ temporaryAccessEndTime: membershipRoleTemporaryAccessEndTime,
+ createdAt: membershipRoleCreatedAt,
+ updatedAt: membershipRoleUpdatedAt
+ })
+ }
+ ]
+ });
+
+ return data as TResourceMembershipReturn[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Get Resource Membership" });
+ }
+ };
+
const getProjectGroupPermissions: TPermissionDALFactory["getProjectGroupPermissions"] = async (
projectId: string,
filterGroupId?: string
@@ -388,6 +515,7 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {
`${TableName.MembershipRole}.customRoleId`,
`groupCustomRoles.id`
)
+ .where(`${TableName.Membership}.scope`, AccessScope.Project)
.where(`${TableName.Membership}.scopeProjectId`, "=", projectId)
.where((bd) => {
if (filterGroupId) {
@@ -865,6 +993,11 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {
.where(`${TableName.Membership}.scope`, AccessScope.Project)
.where(`${TableName.Membership}.scopeProjectId`, projectId);
})
+ .orWhere((inner) => {
+ void inner
+ .where(`${TableName.Membership}.scope`, RESOURCE_SCOPE)
+ .where(`${TableName.Membership}.scopeProjectId`, projectId);
+ })
.orWhere(`${TableName.Membership}.scope`, AccessScope.Organization);
})
.where((qb) => {
@@ -903,6 +1036,7 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {
getProjectIdentityPermissions,
getProjectGroupPermissions,
getPermission,
+ getResourceMembership,
getPermissionFingerprint
};
};
diff --git a/backend/src/ee/services/permission/permission-service-types.ts b/backend/src/ee/services/permission/permission-service-types.ts
index 00f1118729..ce4f72d399 100644
--- a/backend/src/ee/services/permission/permission-service-types.ts
+++ b/backend/src/ee/services/permission/permission-service-types.ts
@@ -6,6 +6,7 @@ import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import { OrgPermissionSet } from "./org-permission";
import { ProjectPermissionSet } from "./project-permission";
+import { ResourcePermissionSet } from "./resource-permission";
export type TBuildProjectPermissionDTO = {
permissions?: unknown;
@@ -33,6 +34,16 @@ export type TGetProjectPermissionArg = {
actionProjectType: ActionProjectType;
};
+export type TGetResourcePermissionArg = {
+ actor: ActorType;
+ actorId: string;
+ projectId: string;
+ resourceType: string;
+ resourceId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId?: string;
+};
+
export type TGetOrgPermissionArg = {
actor: ActorType;
actorId: string;
@@ -59,6 +70,12 @@ export type TPermissionServiceFactory = {
hasRole: (role: string) => boolean;
hasProjectEnforcement: (check: "enforceEncryptedSecretManagerSecretMetadata") => boolean;
}>;
+ getResourcePermission: (arg: TGetResourcePermissionArg) => Promise<{
+ permission: MongoAbility<ResourcePermissionSet, MongoQuery>;
+ memberships: Array<TMemberships & { roles: { role: string; customRoleSlug?: string | null }[] }>;
+ hasRole: (role: string) => boolean;
+ isImplicitAdmin: boolean;
+ }>;
getProjectPermissions: (
projectId: string,
orgId: string
diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.ts
index daf9c5a945..83bd4aa941 100644
--- a/backend/src/ee/services/permission/permission-service.ts
+++ b/backend/src/ee/services/permission/permission-service.ts
@@ -6,6 +6,7 @@ import handlebars from "handlebars";
import {
AccessScope,
ActionProjectType,
+ ApplicationMembershipRole,
OrganizationActionScope,
OrgMembershipRole,
ProjectMembershipRole,
@@ -13,6 +14,9 @@ import {
TProjects
} from "@app/db/schemas";
import {
+ applicationAdminPermissions,
+ applicationAuditorPermissions,
+ applicationOperatorPermissions,
cryptographicOperatorPermissions,
projectAdminPermissions,
projectMemberPermissions,
@@ -20,6 +24,7 @@ import {
projectViewerPermission,
sshHostBootstrapPermissions
} from "@app/ee/services/permission/default-roles";
+import { ResourcePermissionSet } from "@app/ee/services/permission/resource-permission";
import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { withCacheFingerprint } from "@app/lib/cache/with-cache";
import { conditionsMatcher } from "@app/lib/casl";
@@ -37,6 +42,8 @@ import { TUserDALFactory } from "@app/services/user/user-dal";
import {
orgAdminPermissions,
+ orgCertManagerAdminPermissions,
+ orgCertManagerGuestPermissions,
orgMemberPermissions,
orgNoAccessPermissions,
OrgPermissionSet,
@@ -63,6 +70,10 @@ const buildOrgPermissionRules = (orgUserRoles: TBuildOrgPermissionDTO) => {
return orgMemberPermissions;
case OrgMembershipRole.NoAccess:
return orgNoAccessPermissions;
+ case OrgMembershipRole.CertManagerAdmin:
+ return orgCertManagerAdminPermissions;
+ case OrgMembershipRole.CertManagerGuest:
+ return orgCertManagerGuestPermissions;
case OrgMembershipRole.Custom:
return unpackRules<RawRuleOf<MongoAbility<OrgPermissionSet>>>(
permissions as PackRule<RawRuleOf<MongoAbility<OrgPermissionSet>>>[]
@@ -111,6 +122,33 @@ const buildProjectPermissionRules = (projectUserRoles: TBuildProjectPermissionDT
return rules;
};
+const buildResourcePermissionRules = (appUserRoles: TBuildProjectPermissionDTO) => {
+ const rules = appUserRoles
+ .map(({ role }) => {
+ switch (role) {
+ case ApplicationMembershipRole.Admin:
+ return applicationAdminPermissions;
+ case ApplicationMembershipRole.Operator:
+ return applicationOperatorPermissions;
+ case ApplicationMembershipRole.Auditor:
+ return applicationAuditorPermissions;
+ case ApplicationMembershipRole.Custom:
+ throw new BadRequestError({
+ message: "Custom resource-level roles are not supported yet"
+ });
+ default:
+ throw new NotFoundError({
+ name: "ApplicationRoleInvalid",
+ message: `Application role '${role}' not found`
+ });
+ }
+ })
+ .reduce((prev, curr) => prev.concat(curr), [] as RawRuleOf<MongoAbility<ResourcePermissionSet>>[])
+ .sort((a, b) => Number(Boolean(a.inverted)) - Number(Boolean(b.inverted)));
+
+ return rules;
+};
+
type MembershipWithRoles = {
roles?: Array<{
role: string;
@@ -574,6 +612,75 @@ export const permissionServiceFactory = ({
return payload.result;
};
+ const getResourcePermission: TPermissionServiceFactory["getResourcePermission"] = async ({
+ actor,
+ actorId,
+ projectId,
+ resourceType,
+ resourceId,
+ actorAuthMethod,
+ actorOrgId
+ }) => {
+ if (actor !== ActorType.USER && actor !== ActorType.IDENTITY) {
+ throw new BadRequestError({
+ message: "Invalid actor provided",
+ name: "Get resource permission"
+ });
+ }
+
+ const projectPerm = await getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+
+ if (projectPerm.hasRole(ProjectMembershipRole.Admin)) {
+ const permission = createMongoAbility<ResourcePermissionSet>(applicationAdminPermissions, {
+ conditionsMatcher
+ });
+ return {
+ permission,
+ memberships: [],
+ hasRole: (role: string) => role === ApplicationMembershipRole.Admin,
+ isImplicitAdmin: true
+ };
+ }
+
+ const resourceMemberships = await permissionDAL.getResourceMembership({
+ projectId,
+ resourceType,
+ resourceId,
+ actorId,
+ actorType: actor
+ });
+
+ if (!resourceMemberships?.length) {
+ throw new ForbiddenRequestError({
+ message: `You are not a member of ${resourceType} '${resourceId}'.`
+ });
+ }
+
+ const permissionFromRoles = flattenActiveRolesFromMemberships(
+ resourceMemberships,
+ ApplicationMembershipRole.Custom
+ );
+ const rules = buildResourcePermissionRules(permissionFromRoles);
+ const permission = createMongoAbility<ResourcePermissionSet>(rules, { conditionsMatcher });
+
+ const hasRole = (role: string) =>
+ resourceMemberships.some((m) => m.roles.some((r) => role === (r.customRoleSlug || r.role)));
+
+ return {
+ permission,
+ memberships: resourceMemberships,
+ hasRole,
+ isImplicitAdmin: false
+ };
+ };
+
const getProjectPermissions: TPermissionServiceFactory["getProjectPermissions"] = async (projectId, orgId) => {
// fetch user permissions
const rawUserProjectPermissions = await permissionDAL.getProjectUserPermissions(projectId, orgId);
@@ -821,6 +928,7 @@ export const permissionServiceFactory = ({
return {
getOrgPermission,
getProjectPermission,
+ getResourcePermission,
getProjectPermissions,
getOrgPermissionByRoles,
getProjectPermissionByRoles,
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index 38b0038748..ec3b4eaabb 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -149,6 +149,12 @@ export enum ProjectPermissionCertificateProfileActions {
RotateAcmeEabSecret = "rotate-acme-eab-secret"
}
+export enum ProjectPermissionApplicationActions {
+ Read = "read",
+ List = "list",
+ Create = "create"
+}
+
export enum ProjectPermissionSecretSyncActions {
Read = "read",
Create = "create",
@@ -369,6 +375,7 @@ export enum ProjectPermissionSub {
PamInsights = "pam-insights",
CertificateProfiles = "certificate-profiles",
CertificatePolicies = "certificate-policies",
+ Application = "certificate-application",
ApprovalRequests = "approval-requests",
ApprovalRequestGrants = "approval-request-grants",
McpEndpoints = "mcp-endpoints",
@@ -521,6 +528,10 @@ export type CertificateProfileSubjectFields = {
slug: string;
};
+export type ApplicationSubjectFields = {
+ slug: string;
+};
+
export type CertificatePolicySubjectFields = {
name: string;
};
@@ -711,6 +722,10 @@ export type ProjectPermissionSet =
| (ForcedSubject<ProjectPermissionSub.CertificateProfiles> & CertificateProfileSubjectFields)
)
]
+ | [
+ ProjectPermissionApplicationActions,
+ ProjectPermissionSub.Application | (ForcedSubject<ProjectPermissionSub.Application> & ApplicationSubjectFields)
+ ]
| [
ProjectPermissionCertificatePolicyActions,
(
diff --git a/backend/src/ee/services/permission/resource-permission.ts b/backend/src/ee/services/permission/resource-permission.ts
new file mode 100644
index 0000000000..fca3991df3
--- /dev/null
+++ b/backend/src/ee/services/permission/resource-permission.ts
@@ -0,0 +1,83 @@
+import { MongoAbility } from "@casl/ability";
+
+import {
+ ProjectPermissionActions,
+ ProjectPermissionApprovalRequestActions,
+ ProjectPermissionApprovalRequestGrantActions,
+ ProjectPermissionAuditLogsActions,
+ ProjectPermissionCertificateProfileActions,
+ ProjectPermissionMemberActions,
+ ProjectPermissionSub
+} from "./project-permission";
+
+export enum ResourcePermissionSub {
+ Application = "certificate-application",
+ ApplicationEnrollment = "certificate-application-enrollment",
+ ApprovalPolicies = "approval-policies",
+ Certificates = "certificates",
+ PkiSyncs = "pki-syncs",
+ PkiAlerts = "pki-alerts",
+ ApprovalRequests = "approval-requests",
+ ApprovalRequestGrants = "approval-request-grants",
+ Member = "member",
+ Role = "role"
+}
+
+export enum ResourcePermissionApplicationActions {
+ Read = "read",
+ Edit = "edit",
+ Delete = "delete",
+ AttachProfile = "attach-profile",
+ DetachProfile = "detach-profile"
+}
+
+export enum ResourcePermissionApplicationEnrollmentActions {
+ Read = "read",
+ Edit = "edit",
+ RevealAcmeEabSecret = "reveal-acme-eab-secret",
+ RotateAcmeEabSecret = "rotate-acme-eab-secret"
+}
+
+export enum ResourcePermissionApprovalPolicyActions {
+ Read = "read",
+ Create = "create",
+ Edit = "edit",
+ Delete = "delete"
+}
+
+export enum ResourcePermissionCertificateActions {
+ Read = "read",
+ List = "list",
+ Create = "create",
+ Edit = "edit",
+ Delete = "delete",
+ ReadPrivateKey = "read-private-key",
+ Import = "import"
+}
+
+export enum ResourcePermissionPkiSyncActions {
+ Read = "read",
+ List = "list",
+ Create = "create",
+ Edit = "edit",
+ Delete = "delete",
+ SyncCertificates = "sync-certificates",
+ ImportCertificates = "import-certificates",
+ RemoveCertificates = "remove-certificates"
+}
+
+export type ResourcePermissionSet =
+ | [ResourcePermissionApplicationActions, ResourcePermissionSub.Application]
+ | [ResourcePermissionApplicationEnrollmentActions, ResourcePermissionSub.ApplicationEnrollment]
+ | [ResourcePermissionApprovalPolicyActions, ResourcePermissionSub.ApprovalPolicies]
+ | [ResourcePermissionCertificateActions, ResourcePermissionSub.Certificates]
+ | [ResourcePermissionPkiSyncActions, ResourcePermissionSub.PkiSyncs]
+ | [ProjectPermissionActions, ResourcePermissionSub.PkiAlerts]
+ | [ProjectPermissionApprovalRequestActions, ResourcePermissionSub.ApprovalRequests]
+ | [ProjectPermissionApprovalRequestGrantActions, ResourcePermissionSub.ApprovalRequestGrants]
+ | [ProjectPermissionMemberActions, ResourcePermissionSub.Member]
+ | [ProjectPermissionActions, ResourcePermissionSub.Role]
+ | [ProjectPermissionCertificateProfileActions, ProjectPermissionSub.CertificateProfiles]
+ | [ProjectPermissionAuditLogsActions, ProjectPermissionSub.AuditLogs];
+
+export type TResourceAbility = MongoAbility<ResourcePermissionSet>;
diff --git a/backend/src/ee/services/pki-acme/pki-acme-account-dal.ts b/backend/src/ee/services/pki-acme/pki-acme-account-dal.ts
index 685d07f2bc..b2cdad9ac0 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-account-dal.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-account-dal.ts
@@ -34,9 +34,35 @@ export const pkiAcmeAccountDALFactory = (db: TDbClient) => {
}
};
+ const findApplicationProfileId = async (applicationId: string, profileId: string, tx?: Knex) => {
+ try {
+ const row = await (tx || db.replicaNode())(TableName.PkiApplicationProfile)
+ .where({ applicationId, profileId })
+ .select("id")
+ .first();
+ return row?.id ?? null;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find application profile junction id" });
+ }
+ };
+
+ const findApplicationIdByJunctionId = async (junctionId: string, tx?: Knex) => {
+ try {
+ const row = await (tx || db.replicaNode())(TableName.PkiApplicationProfile)
+ .where({ id: junctionId })
+ .select("applicationId")
+ .first();
+ return row?.applicationId ?? null;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find application id by junction id" });
+ }
+ };
+
return {
...pkiAcmeAccountOrm,
findByProjectIdAndAccountId,
- findByProfileIdAndPublicKeyThumbprintAndAlg
+ findByProfileIdAndPublicKeyThumbprintAndAlg,
+ findApplicationProfileId,
+ findApplicationIdByJunctionId
};
};
diff --git a/backend/src/ee/services/pki-acme/pki-acme-fns.ts b/backend/src/ee/services/pki-acme/pki-acme-fns.ts
index 3780c18af7..537149ffd6 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-fns.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-fns.ts
@@ -6,14 +6,17 @@ import { isValidIp } from "@app/lib/ip";
import { AcmeAccountDoesNotExistError } from "./pki-acme-errors";
-export const buildUrl = (profileId: string, path: string): string => {
+export const buildUrl = (profileId: string, path: string, applicationId?: string): string => {
const appCfg = getConfig();
const baseUrl = appCfg.SITE_URL ?? "";
+ if (applicationId) {
+ return `${baseUrl}/api/v1/cert-manager/acme/applications/${applicationId}/profiles/${profileId}${path}`;
+ }
return `${baseUrl}/api/v1/cert-manager/acme/profiles/${profileId}${path}`;
};
-export const extractAccountIdFromKid = (kid: string, profileId: string): string => {
- const kidPrefix = buildUrl(profileId, "/accounts/");
+export const extractAccountIdFromKid = (kid: string, profileId: string, applicationId?: string): string => {
+ const kidPrefix = buildUrl(profileId, "/accounts/", applicationId);
if (!kid.startsWith(kidPrefix)) {
throw new AcmeAccountDoesNotExistError({ message: "KID must start with the profile account URL" });
}
diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.ts
index 0712a8222f..b7da1f8348 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts
@@ -54,6 +54,7 @@ import { CertificateRequestStatus } from "@app/services/certificate-request/cert
import { resolveEffectiveTtl } from "@app/services/certificate-v3/certificate-v3-fns";
import { TCertificateV3ServiceFactory } from "@app/services/certificate-v3/certificate-v3-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TPkiApplicationProfileDALFactory } from "@app/services/pki-application/pki-application-profile-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
@@ -114,7 +115,11 @@ type TPkiAcmeServiceFactoryDep = {
certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "findById">;
acmeAccountDAL: Pick<
TPkiAcmeAccountDALFactory,
- "findByProjectIdAndAccountId" | "findByProfileIdAndPublicKeyThumbprintAndAlg" | "create"
+ | "findByProjectIdAndAccountId"
+ | "findByProfileIdAndPublicKeyThumbprintAndAlg"
+ | "findApplicationProfileId"
+ | "findApplicationIdByJunctionId"
+ | "create"
>;
acmeOrderDAL: Pick<
TPkiAcmeOrderDALFactory,
@@ -148,6 +153,7 @@ type TPkiAcmeServiceFactoryDep = {
approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findByProjectId" | "findStepsByPolicyId">;
approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "createRequestFromPolicy">;
certificateRequestDAL: Pick<TCertificateRequestDALFactory, "create" | "updateById">;
+ pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findOne">;
};
export const pkiAcmeServiceFactory = ({
@@ -172,7 +178,8 @@ export const pkiAcmeServiceFactory = ({
auditLogService,
approvalPolicyDAL,
approvalPolicyService,
- certificateRequestDAL
+ certificateRequestDAL,
+ pkiApplicationProfileDAL
}: TPkiAcmeServiceFactoryDep): TPkiAcmeServiceFactory => {
const validateAcmeProfile = async (profileId: string): Promise<TCertificateProfileWithConfigs> => {
const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
@@ -419,12 +426,12 @@ export const pkiAcmeServiceFactory = ({
});
};
- const getAcmeDirectory = async (profileId: string): Promise<TGetAcmeDirectoryResponse> => {
+ const getAcmeDirectory = async (profileId: string, applicationId?: string): Promise<TGetAcmeDirectoryResponse> => {
const profile = await validateAcmeProfile(profileId);
const skipEabBinding = profile.acmeConfig?.skipEabBinding ?? false;
return {
newNonce: buildUrl(profile.id, "/new-nonce"),
- newAccount: buildUrl(profile.id, "/new-account"),
+ newAccount: buildUrl(profile.id, "/new-account", applicationId),
newOrder: buildUrl(profile.id, "/new-order"),
meta: {
externalAccountRequired: !skipEabBinding
@@ -446,12 +453,14 @@ export const pkiAcmeServiceFactory = ({
* -------------------------------------------------------------- */
const createAcmeAccount = async ({
profileId,
+ applicationId,
alg,
jwk,
payload: { onlyReturnExisting, contact, externalAccountBinding },
auditLogInfo
}: {
profileId: string;
+ applicationId?: string;
alg: string;
jwk: JsonWebKey;
payload: TCreateAcmeAccountPayload;
@@ -586,9 +595,13 @@ export const pkiAcmeServiceFactory = ({
}
}
- // TODO: handle unique constraint violation error, should be very very rare
+ const applicationProfileId = applicationId
+ ? ((await pkiApplicationProfileDAL.findOne(applicationId, profile.id))?.id ?? null)
+ : null;
+
const newAccount = await acmeAccountDAL.create({
profileId: profile.id,
+ applicationProfileId,
alg,
publicKey: jwk,
publicKeyThumbprint,
@@ -843,7 +856,8 @@ export const pkiAcmeServiceFactory = ({
certificateRequest,
profile,
ca,
- tx
+ tx,
+ applicationId
}: {
caType: CaType;
accountId: string;
@@ -859,6 +873,7 @@ export const pkiAcmeServiceFactory = ({
profile: TCertificateProfileWithConfigs;
ca: Awaited<ReturnType<typeof certificateAuthorityDAL.findByIdWithAssociatedCa>>;
tx?: Knex;
+ applicationId?: string;
}): Promise<{ certificateId?: string; certIssuanceJobData?: TIssueCertificateFromProfileJobData }> => {
if (caType === CaType.INTERNAL) {
const internalPolicy = await certificatePolicyDAL.findById(profile.certificatePolicyId);
@@ -883,7 +898,8 @@ export const pkiAcmeServiceFactory = ({
}
: // ttl is not used if notAfter is provided
({ ttl: "0d" } as const),
- enrollmentType: EnrollmentType.ACME
+ enrollmentType: EnrollmentType.ACME,
+ applicationId
});
if ("certificateId" in result) {
return {
@@ -1070,6 +1086,13 @@ export const pkiAcmeServiceFactory = ({
throw new NotFoundError({ message: "Certificate Authority not found" });
}
+ const finalizeAccount = await acmeAccountDAL.findByProjectIdAndAccountId(profile.id, accountId);
+ const accountApplicationProfileId = (finalizeAccount as { applicationProfileId?: string | null } | null)
+ ?.applicationProfileId;
+ const accountApplicationId = accountApplicationProfileId
+ ? await acmeAccountDAL.findApplicationIdByJunctionId(accountApplicationProfileId)
+ : null;
+
const approvalFactory = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.CertRequest](
ApprovalPolicyType.CertRequest
);
@@ -1077,7 +1100,8 @@ export const pkiAcmeServiceFactory = ({
approvalPolicyDAL as TApprovalPolicyDALFactory,
profile.projectId,
{
- profileName: profile.slug
+ profileName: profile.slug,
+ applicationId: accountApplicationId ?? undefined
}
)) as TCertRequestPolicy | null;
@@ -1241,7 +1265,8 @@ export const pkiAcmeServiceFactory = ({
certificateRequest,
profile,
ca,
- tx
+ tx,
+ applicationId: accountApplicationId ?? undefined
});
await acmeOrderDAL.updateById(
orderId,
diff --git a/backend/src/ee/services/pki-acme/pki-acme-types.ts b/backend/src/ee/services/pki-acme/pki-acme-types.ts
index b00adfd4c4..0014e18fc8 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-types.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-types.ts
@@ -89,16 +89,18 @@ export type TPkiAcmeServiceFactory = {
schema?: TSchema;
expectedAccountId?: string;
}) => Promise<TAuthenciatedJwsPayload<T>>;
- getAcmeDirectory: (profileId: string) => Promise<TGetAcmeDirectoryResponse>;
+ getAcmeDirectory: (profileId: string, applicationId?: string) => Promise<TGetAcmeDirectoryResponse>;
getAcmeNewNonce: (profileId: string) => Promise<string>;
createAcmeAccount: ({
profileId,
+ applicationId,
alg,
jwk,
payload,
auditLogInfo
}: {
profileId: string;
+ applicationId?: string;
alg: string;
jwk: JsonWebKey;
payload: TCreateAcmeAccountPayload;
diff --git a/backend/src/ee/services/pki-scep/pki-scep-service.ts b/backend/src/ee/services/pki-scep/pki-scep-service.ts
index 3b5eb89084..1713570429 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-service.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-service.ts
@@ -34,6 +34,7 @@ import { resolveEffectiveTtl } from "@app/services/certificate-v3/certificate-v3
import { TCertificateV3ServiceFactory } from "@app/services/certificate-v3/certificate-v3-service";
import { TScepEnrollmentConfigDALFactory } from "@app/services/enrollment-config/scep-enrollment-config-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TPkiApplicationProfileDALFactory } from "@app/services/pki-application/pki-application-profile-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
@@ -76,6 +77,7 @@ type TPkiScepServiceFactoryDep = {
certificateIssuanceQueue: Pick<TCertificateIssuanceQueueFactory, "queueCertificateIssuance">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ pkiApplicationProfileDAL?: Pick<TPkiApplicationProfileDALFactory, "findOne">;
};
export type TPkiScepServiceFactory = ReturnType<typeof pkiScepServiceFactory>;
@@ -101,9 +103,10 @@ export const pkiScepServiceFactory = ({
certificateRequestService,
certificateIssuanceQueue,
auditLogService,
- permissionService
+ permissionService,
+ pkiApplicationProfileDAL
}: TPkiScepServiceFactoryDep) => {
- const loadScepContext = async (profileId: string) => {
+ const loadScepContext = async (profileId: string, applicationId?: string) => {
const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
if (!profile) {
throw new NotFoundError({ message: "Certificate profile not found" });
@@ -113,7 +116,20 @@ export const pkiScepServiceFactory = ({
throw new BadRequestError({ message: "Profile is not configured for SCEP enrollment" });
}
- if (!profile.scepConfigId) {
+ let resolvedScepConfigId: string | null = profile.scepConfigId ?? null;
+ if (applicationId && pkiApplicationProfileDAL) {
+ const junction = await pkiApplicationProfileDAL.findOne(applicationId, profileId);
+ if (!junction) {
+ throw new NotFoundError({
+ message: `Profile '${profileId}' is not attached to application '${applicationId}'.`
+ });
+ }
+ if (junction.scepConfigId) {
+ resolvedScepConfigId = junction.scepConfigId;
+ }
+ }
+
+ if (!resolvedScepConfigId) {
throw new BadRequestError({ message: "SCEP enrollment not configured for this profile" });
}
@@ -127,7 +143,7 @@ export const pkiScepServiceFactory = ({
}
const caType: CaType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;
- const scepConfig = await scepEnrollmentConfigDAL.findById(profile.scepConfigId);
+ const scepConfig = await scepEnrollmentConfigDAL.findById(resolvedScepConfigId);
if (!scepConfig) {
throw new NotFoundError({ message: "SCEP configuration not found" });
}
@@ -158,19 +174,28 @@ export const pkiScepServiceFactory = ({
return { profile, scepConfig, project, ca, caType, raPrivateKeyDer, raCertDer } as const;
};
- const getCaCaps = async ({ profileId }: TGetCaCapsDTO): Promise<string> => {
+ const getCaCaps = async ({ profileId, applicationId }: TGetCaCapsDTO): Promise<string> => {
const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
if (!profile || profile.enrollmentType !== EnrollmentType.SCEP) {
throw new NotFoundError({ message: "SCEP profile not found" });
}
+ if (applicationId && pkiApplicationProfileDAL) {
+ const junction = await pkiApplicationProfileDAL.findOne(applicationId, profileId);
+ if (!junction) {
+ throw new NotFoundError({
+ message: `Profile '${profileId}' is not attached to application '${applicationId}'.`
+ });
+ }
+ }
+
return getScepCapabilities({
allowCertBasedRenewal: profile.scepConfig?.allowCertBasedRenewal ?? false
});
};
- const getCaCert = async ({ profileId }: TGetCaCertDTO): Promise<Buffer> => {
- const { scepConfig, ca, caType } = await loadScepContext(profileId);
+ const getCaCert = async ({ profileId, applicationId }: TGetCaCertDTO): Promise<Buffer> => {
+ const { scepConfig, ca, caType } = await loadScepContext(profileId, applicationId);
const raCert = new x509.X509Certificate(scepConfig.raCertificate);
const rawCerts: ArrayBuffer[] = [raCert.rawData];
@@ -220,8 +245,16 @@ export const pkiScepServiceFactory = ({
return { ttl };
};
- const handlePkiOperation = async ({ profileId, message, clientIp }: THandlePkiOperationDTO): Promise<Buffer> => {
- const { profile, scepConfig, project, caType, raPrivateKeyDer, raCertDer } = await loadScepContext(profileId);
+ const handlePkiOperation = async ({
+ profileId,
+ message,
+ clientIp,
+ applicationId
+ }: THandlePkiOperationDTO): Promise<Buffer> => {
+ const { profile, scepConfig, project, caType, raPrivateKeyDer, raCertDer } = await loadScepContext(
+ profileId,
+ applicationId
+ );
const parsed = parseScepMessage(message, raPrivateKeyDer);
@@ -236,7 +269,8 @@ export const pkiScepServiceFactory = ({
raPrivateKeyDer,
raCertDer,
parsed,
- clientIp
+ clientIp,
+ applicationId
});
case ScepMessageType.RenewalReq:
@@ -249,7 +283,8 @@ export const pkiScepServiceFactory = ({
raPrivateKeyDer,
raCertDer,
parsed,
- clientIp
+ clientIp,
+ applicationId
});
case ScepMessageType.GetCertInitial:
@@ -274,7 +309,8 @@ export const pkiScepServiceFactory = ({
raPrivateKeyDer,
raCertDer,
parsed,
- clientIp
+ clientIp,
+ applicationId
}: {
profile: TScepContext["profile"];
scepConfig: TScepContext["scepConfig"];
@@ -284,6 +320,7 @@ export const pkiScepServiceFactory = ({
raCertDer: Buffer;
parsed: TParsedScepMessage;
clientIp: string;
+ applicationId?: string;
}): Promise<Buffer> => {
if (!parsed.csr) {
throw new BadRequestError({ message: "No CSR found in SCEP enrollment request" });
@@ -398,7 +435,8 @@ export const pkiScepServiceFactory = ({
caType,
parsed,
csrPem,
- ttl
+ ttl,
+ applicationId
});
const auditMetadata = {
@@ -461,7 +499,8 @@ export const pkiScepServiceFactory = ({
raPrivateKeyDer,
raCertDer,
parsed,
- clientIp
+ clientIp,
+ applicationId
}: {
profile: TScepContext["profile"];
scepConfig: TScepContext["scepConfig"];
@@ -471,6 +510,7 @@ export const pkiScepServiceFactory = ({
raCertDer: Buffer;
parsed: TParsedScepMessage;
clientIp: string;
+ applicationId?: string;
}): Promise<Buffer> => {
if (!scepConfig.allowCertBasedRenewal) {
return buildCertRepFailure({
@@ -537,7 +577,8 @@ export const pkiScepServiceFactory = ({
caType,
parsed,
csrPem,
- ttl
+ ttl,
+ applicationId
});
const auditMetadata = {
@@ -603,7 +644,8 @@ export const pkiScepServiceFactory = ({
caType,
parsed,
csrPem,
- ttl
+ ttl,
+ applicationId
}: {
profile: TScepContext["profile"];
project: TScepContext["project"];
@@ -611,6 +653,7 @@ export const pkiScepServiceFactory = ({
parsed: TParsedScepMessage;
csrPem: string;
ttl: string;
+ applicationId?: string;
}): Promise<TIssuanceResult> => {
// Internal CAs use direct signing
if (caType === CaType.INTERNAL) {
@@ -622,7 +665,8 @@ export const pkiScepServiceFactory = ({
profileId: profile.id,
csr: csrPem,
validity: { ttl },
- enrollmentType: EnrollmentType.SCEP
+ enrollmentType: EnrollmentType.SCEP,
+ applicationId
});
if (result.status === CertificateRequestStatus.PENDING_APPROVAL) {
@@ -638,7 +682,8 @@ export const pkiScepServiceFactory = ({
signerCertDer: parsed.signerCertDer,
certificateRequestId: result.certificateRequestId,
clientCipherOid: parsed.clientCipherOid || null,
- expiresAt
+ expiresAt,
+ applicationId: applicationId ?? null
});
}
@@ -735,7 +780,8 @@ export const pkiScepServiceFactory = ({
signerCertDer: parsed.signerCertDer,
certificateRequestId: newCertRequest.id,
clientCipherOid: parsed.clientCipherOid || null,
- expiresAt
+ expiresAt,
+ applicationId: applicationId ?? null
});
}
diff --git a/backend/src/ee/services/pki-scep/pki-scep-types.ts b/backend/src/ee/services/pki-scep/pki-scep-types.ts
index 321940dab6..6c49f943e7 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-types.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-types.ts
@@ -54,16 +54,19 @@ export interface TParsedScepMessage {
export type TGetCaCapsDTO = {
profileId: string;
+ applicationId?: string;
};
export type TGetCaCertDTO = {
profileId: string;
+ applicationId?: string;
};
export type THandlePkiOperationDTO = {
profileId: string;
message: Buffer;
clientIp: string;
+ applicationId?: string;
};
export type TGenerateDynamicChallengeDTO = {
diff --git a/backend/src/ee/services/sub-org/sub-org-service.ts b/backend/src/ee/services/sub-org/sub-org-service.ts
index 3818ba2108..e203e1072e 100644
--- a/backend/src/ee/services/sub-org/sub-org-service.ts
+++ b/backend/src/ee/services/sub-org/sub-org-service.ts
@@ -7,6 +7,8 @@ import { ActorType } from "@app/services/auth/auth-type";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
import { TOrgDALFactory } from "@app/services/org/org-dal";
+import { bootstrapCertManagerProject } from "@app/services/pki-application/cert-manager-project-bootstrap";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TLicenseServiceFactory } from "../license/license-service";
import { OrgPermissionSubjects, OrgPermissionSubOrgActions } from "../permission/org-permission";
@@ -22,6 +24,7 @@ type TSubOrgServiceFactoryDep = {
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
membershipDAL: Pick<TMembershipDALFactory, "create" | "findOne">;
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create">;
+ projectDAL: Pick<TProjectDALFactory, "create" | "findOne">;
};
export type TSubOrgServiceFactory = ReturnType<typeof subOrgServiceFactory>;
@@ -31,7 +34,8 @@ export const subOrgServiceFactory = ({
permissionService,
licenseService,
membershipDAL,
- membershipRoleDAL
+ membershipRoleDAL,
+ projectDAL
}: TSubOrgServiceFactoryDep) => {
const createSubOrg = async ({ name, slug, permission }: TCreateSubOrgDTO) => {
const { permission: orgPermission } = await permissionService.getOrgPermission({
@@ -88,6 +92,17 @@ export const subOrgServiceFactory = ({
},
tx
);
+
+ await bootstrapCertManagerProject(
+ {
+ orgId: org.id,
+ adminUserIds: permission.type === ActorType.USER ? [permission.id] : [],
+ adminIdentityIds: permission.type === ActorType.IDENTITY ? [permission.id] : []
+ },
+ { projectDAL, membershipDAL, membershipRoleDAL },
+ tx
+ );
+
return org;
});
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 2874a7ee86..58f71d7322 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -67,6 +67,8 @@ export enum ApiDocsTags {
PkiCertificatePolicies = "PKI Certificate Policies",
PkiCertificateTemplates = "PKI Certificate Templates",
PkiCertificateProfiles = "PKI Certificate Profiles",
+ PkiApplications = "PKI Applications",
+ CertManagerInstance = "Certificate Manager Instance",
PkiCertificateCollections = "PKI Certificate Collections",
PkiAlerting = "PKI Alerting",
PkiDiscovery = "PKI Discovery",
diff --git a/backend/src/server/plugins/block-cert-manager-project-access.ts b/backend/src/server/plugins/block-cert-manager-project-access.ts
new file mode 100644
index 0000000000..05b30dfd24
--- /dev/null
+++ b/backend/src/server/plugins/block-cert-manager-project-access.ts
@@ -0,0 +1,26 @@
+import { FastifyPluginAsync } from "fastify";
+import fp from "fastify-plugin";
+import RE2 from "re2";
+
+import { ForbiddenRequestError } from "@app/lib/errors";
+
+const ACCESS_PATH_RE = new RE2("/(memberships|identities|groups|roles)(/|$|\\?)");
+
+export const blockCertManagerProjectAccess: FastifyPluginAsync = fp(async (server) => {
+ server.addHook("preValidation", async (req) => {
+ const projectId = (req.params as { projectId?: string } | null)?.projectId;
+ if (!projectId) return;
+
+ const routePath = req.routerPath ?? "";
+ if (!routePath.startsWith("/api/v1/projects/")) return;
+ if (!ACCESS_PATH_RE.test(routePath)) return;
+
+ const isCertManager = await server.services.certManagerProjectResolver.isCertManagerProject(projectId);
+ if (isCertManager) {
+ throw new ForbiddenRequestError({
+ message:
+ "This Cert Manager project does not support project-level memberships. Use /api/v1/cert-manager/access/* instead."
+ });
+ }
+ });
+});
diff --git a/backend/src/server/plugins/inject-cert-manager-project-id.ts b/backend/src/server/plugins/inject-cert-manager-project-id.ts
new file mode 100644
index 0000000000..e7f4d5d20b
--- /dev/null
+++ b/backend/src/server/plugins/inject-cert-manager-project-id.ts
@@ -0,0 +1,17 @@
+import { FastifyPluginAsync } from "fastify";
+import fp from "fastify-plugin";
+
+export const injectCertManagerProjectId: FastifyPluginAsync = fp(async (server) => {
+ server.decorateRequest("certManagerProjectId", "");
+
+ server.addHook("preValidation", async (req) => {
+ if (!req.permission?.orgId) return;
+
+ const routePath = req.routerPath ?? "";
+ if (routePath === "/api/v1/cert-manager/instance" || routePath.startsWith("/api/v1/cert-manager/instance/")) {
+ return;
+ }
+
+ req.certManagerProjectId = await server.services.certManagerProjectResolver.resolve(req.permission.orgId);
+ });
+});
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 4386a91d74..cda7aeac88 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -384,6 +384,13 @@ import { pkiAlertHistoryDALFactory } from "@app/services/pki-alert-v2/pki-alert-
import { pkiAlertV2DALFactory } from "@app/services/pki-alert-v2/pki-alert-v2-dal";
import { pkiAlertV2QueueServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-queue";
import { pkiAlertV2ServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-service";
+import { certManagerInstanceServiceFactory } from "@app/services/pki-application/cert-manager-instance-service";
+import { certManagerProjectResolverFactory } from "@app/services/pki-application/cert-manager-project-resolver";
+import { pkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";
+import { pkiApplicationEnrollmentServiceFactory } from "@app/services/pki-application/pki-application-enrollment-service";
+import { pkiApplicationMembershipServiceFactory } from "@app/services/pki-application/pki-application-membership-service";
+import { pkiApplicationProfileDALFactory } from "@app/services/pki-application/pki-application-profile-dal";
+import { pkiApplicationServiceFactory } from "@app/services/pki-application/pki-application-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";
@@ -1109,6 +1116,7 @@ export const registerRoutes = async (
reminderService,
membershipRoleDAL,
membershipUserDAL,
+ membershipDAL,
roleDAL,
userGroupMembershipDAL,
additionalPrivilegeDAL
@@ -1119,6 +1127,7 @@ export const registerRoutes = async (
membershipDAL,
membershipRoleDAL,
orgDAL,
+ projectDAL,
permissionService
});
@@ -1257,6 +1266,8 @@ export const registerRoutes = async (
const certificateTemplateEstConfigDAL = certificateTemplateEstConfigDALFactory(db);
const certificatePolicyDAL = certificatePolicyDALFactory(db);
const certificateProfileDAL = certificateProfileDALFactory(db);
+ const pkiApplicationDAL = pkiApplicationDALFactory(db);
+ const pkiApplicationProfileDAL = pkiApplicationProfileDALFactory(db);
const apiEnrollmentConfigDAL = apiEnrollmentConfigDALFactory(db);
const estEnrollmentConfigDAL = estEnrollmentConfigDALFactory(db);
const acmeEnrollmentConfigDAL = acmeEnrollmentConfigDALFactory(db);
@@ -1393,7 +1404,50 @@ export const registerRoutes = async (
permissionService,
kmsService,
projectDAL,
- resourceMetadataDAL
+ resourceMetadataDAL,
+ pkiApplicationProfileDAL
+ });
+
+ const pkiApplicationService = pkiApplicationServiceFactory({
+ pkiApplicationDAL,
+ pkiApplicationProfileDAL,
+ membershipDAL,
+ membershipRoleDAL,
+ permissionService
+ });
+
+ const pkiApplicationMembershipService = pkiApplicationMembershipServiceFactory({
+ pkiApplicationDAL,
+ membershipDAL,
+ membershipRoleDAL,
+ permissionService,
+ userDAL,
+ identityDAL,
+ groupDAL
+ });
+
+ const certManagerProjectResolver = certManagerProjectResolverFactory({
+ orgDAL,
+ projectDAL
+ });
+
+ const certManagerInstanceService = certManagerInstanceServiceFactory({
+ db,
+ orgDAL,
+ projectDAL,
+ permissionService
+ });
+
+ const pkiApplicationEnrollmentService = pkiApplicationEnrollmentServiceFactory({
+ pkiApplicationDAL,
+ pkiApplicationProfileDAL,
+ apiEnrollmentConfigDAL,
+ estEnrollmentConfigDAL,
+ acmeEnrollmentConfigDAL,
+ scepEnrollmentConfigDAL,
+ kmsService,
+ projectDAL,
+ permissionService
});
const pkiAlertService = pkiAlertServiceFactory({
@@ -2638,7 +2692,8 @@ export const registerRoutes = async (
identityDAL,
approvalPolicyService,
resourceMetadataDAL,
- pkiAlertV2Queue
+ pkiAlertV2Queue,
+ pkiApplicationProfileDAL
});
const certificateV3Queue = certificateV3QueueServiceFactory({
@@ -2669,7 +2724,8 @@ export const registerRoutes = async (
licenseService,
certificateProfileDAL,
estEnrollmentConfigDAL,
- certificatePolicyDAL
+ certificatePolicyDAL,
+ pkiApplicationProfileDAL
});
const pkiScepService = pkiScepServiceFactory({
@@ -2691,7 +2747,8 @@ export const registerRoutes = async (
certificateRequestService,
certificateIssuanceQueue,
auditLogService,
- permissionService
+ permissionService,
+ pkiApplicationProfileDAL
});
const acmeChallengeService = pkiAcmeChallengeServiceFactory({
@@ -2726,7 +2783,8 @@ export const registerRoutes = async (
auditLogService,
approvalPolicyDAL,
approvalPolicyService,
- certificateRequestDAL
+ certificateRequestDAL,
+ pkiApplicationProfileDAL
});
const pkiSubscriberService = pkiSubscriberServiceFactory({
@@ -3240,6 +3298,11 @@ export const registerRoutes = async (
certificateTemplate: certificateTemplateService,
certificatePolicy: certificatePolicyService,
certificateProfile: certificateProfileService,
+ pkiApplication: pkiApplicationService,
+ pkiApplicationMembership: pkiApplicationMembershipService,
+ pkiApplicationEnrollment: pkiApplicationEnrollmentService,
+ certManagerProjectResolver,
+ certManagerInstance: certManagerInstanceService,
certificateAuthorityCrl: certificateAuthorityCrlService,
certificateEst: certificateEstService,
pkiAcme: pkiAcmeService,
diff --git a/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts b/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts
index 147b9f5b53..a48271b62c 100644
--- a/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts
+++ b/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts
@@ -109,7 +109,8 @@ export const registerApprovalPolicyEndpoints = ({
operationId: "listApprovalPolicies",
description: "List approval policies",
querystring: z.object({
- projectId: z.string().uuid()
+ projectId: z.string().uuid(),
+ applicationId: z.string().uuid().optional()
}),
response: {
200: z.object({
@@ -119,7 +120,9 @@ export const registerApprovalPolicyEndpoints = ({
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
- const { policies } = await server.services.approvalPolicy.list(policyType, req.query.projectId, req.permission);
+ const { policies } = await server.services.approvalPolicy.list(policyType, req.query.projectId, req.permission, {
+ applicationId: req.query.applicationId
+ });
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
@@ -276,7 +279,8 @@ export const registerApprovalPolicyEndpoints = ({
operationId: "listApprovalRequests",
description: "List approval requests",
querystring: z.object({
- projectId: z.string().uuid()
+ projectId: z.string().uuid(),
+ applicationId: z.string().uuid().optional()
}),
response: {
200: z.object({
@@ -289,7 +293,8 @@ export const registerApprovalPolicyEndpoints = ({
const { requests } = await server.services.approvalPolicy.listRequests(
policyType,
req.query.projectId,
- req.permission
+ req.permission,
+ { applicationId: req.query.applicationId }
);
await server.services.auditLog.createAuditLog({
diff --git a/backend/src/server/routes/v1/cert-manager-access-router.ts b/backend/src/server/routes/v1/cert-manager-access-router.ts
new file mode 100644
index 0000000000..0cac65e5d3
--- /dev/null
+++ b/backend/src/server/routes/v1/cert-manager-access-router.ts
@@ -0,0 +1,847 @@
+import { z } from "zod";
+
+import {
+ AccessScope,
+ GroupsSchema,
+ IdentitiesSchema,
+ IdentityProjectMembershipsSchema,
+ ProjectMembershipRole,
+ ProjectMembershipsSchema,
+ ProjectRolesSchema,
+ ProjectUserMembershipRolesSchema,
+ TemporaryPermissionMode
+} from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } from "@app/lib/api-docs";
+import { BadRequestError } from "@app/lib/errors";
+import { ms } from "@app/lib/ms";
+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 { SanitizedRoleSchema, SanitizedUserSchema } from "../sanitizedSchemas";
+
+const MembershipRoleSchema = z.object({
+ id: z.string(),
+ role: z.string(),
+ customRoleId: z.string().optional().nullable(),
+ customRoleName: z.string().optional().nullable(),
+ customRoleSlug: z.string().optional().nullable(),
+ isTemporary: z.boolean(),
+ temporaryMode: z.string().optional().nullable(),
+ temporaryRange: z.string().nullable().optional(),
+ temporaryAccessStartTime: z.date().nullable().optional(),
+ temporaryAccessEndTime: z.date().nullable().optional()
+});
+
+const RolesUpdateBodySchema = z.object({
+ roles: z
+ .array(
+ z.union([
+ z.object({
+ role: z.string(),
+ isTemporary: z.literal(false).default(false)
+ }),
+ z.object({
+ role: z.string(),
+ isTemporary: z.literal(true),
+ temporaryMode: z.nativeEnum(TemporaryPermissionMode),
+ temporaryRange: z.string().refine((val) => ms(val) > 0, "Temporary range must be a positive number"),
+ temporaryAccessStartTime: z.string().datetime()
+ })
+ ])
+ )
+ .min(1)
+ .refine((data) => data.some(({ isTemporary }) => !isTemporary), "At least one long lived role is required")
+});
+
+export const registerCertManagerAccessRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/users",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listCertManagerUsers",
+ tags: [ApiDocsTags.PkiCertificates],
+ description: "List Cert Manager users.",
+ response: {
+ 200: z.object({
+ memberships: ProjectMembershipsSchema.extend({
+ user: SanitizedUserSchema,
+ roles: z.array(MembershipRoleSchema)
+ })
+ .omit({ updatedAt: true, projectId: true })
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { data: memberships } = await server.services.membershipUser.listMemberships({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ data: {}
+ });
+ return {
+ memberships: memberships.map((el) => ({
+ ...el,
+ userId: el.actorUserId as string
+ }))
+ };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/users/:membershipId",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "getCertManagerUser",
+ params: z.object({ membershipId: z.string().trim().min(1) }),
+ response: {
+ 200: z.object({
+ membership: ProjectMembershipsSchema.extend({
+ user: SanitizedUserSchema,
+ roles: z.array(MembershipRoleSchema)
+ }).omit({ updatedAt: true, projectId: true })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { userId } = await server.services.convertor.userMembershipIdToUserId(
+ req.params.membershipId,
+ AccessScope.Project,
+ req.permission.orgId
+ );
+ const membership = await server.services.membershipUser.getMembershipByUserId({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ selector: { userId }
+ });
+ return { membership: { ...membership, userId } };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/users",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "inviteCertManagerUsers",
+ tags: [ApiDocsTags.PkiCertificates],
+ description: "Invite users to Cert Manager.",
+ body: z.object({
+ emails: z
+ .string()
+ .email()
+ .array()
+ .default([])
+ .refine((val) => val.every((el) => el === el.toLowerCase()), "Email must be lowercase"),
+ usernames: z
+ .string()
+ .array()
+ .default([])
+ .refine((val) => val.every((el) => el === el.toLowerCase()), "Username must be lowercase"),
+ roleSlugs: z.string().array().min(1).optional()
+ }),
+ response: {
+ 200: z.object({ memberships: ProjectMembershipsSchema.omit({ projectId: true }).array() })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const usernamesAndEmails = [...req.body.emails, ...req.body.usernames];
+
+ await server.services.membershipUser.createMembership({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Organization, orgId: req.permission.orgId },
+ data: { roles: [], usernames: usernamesAndEmails }
+ });
+
+ const { memberships } = await server.services.membershipUser.createMembership({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ data: {
+ roles: (req.body.roleSlugs || [ProjectMembershipRole.Member]).map((role) => ({
+ isTemporary: false,
+ role
+ })),
+ usernames: usernamesAndEmails
+ }
+ });
+
+ await server.services.auditLog.createAuditLog({
+ projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.ADD_BATCH_PROJECT_MEMBER,
+ metadata: {
+ members: memberships.map(({ actorUserId, id }) => ({
+ userId: actorUserId || "",
+ membershipId: id,
+ email: ""
+ }))
+ }
+ }
+ });
+
+ return {
+ memberships: memberships.map((el) => ({ ...el, userId: el.actorUserId as string }))
+ };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/users/:membershipId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "updateCertManagerUser",
+ params: z.object({ membershipId: z.string().trim().min(1) }),
+ body: RolesUpdateBodySchema,
+ response: { 200: z.object({ roles: ProjectUserMembershipRolesSchema.array() }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { userId } = await server.services.convertor.userMembershipIdToUserId(
+ req.params.membershipId,
+ AccessScope.Project,
+ req.permission.orgId
+ );
+ const { membership } = await server.services.membershipUser.updateMembership({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ selector: { userId },
+ data: { roles: req.body.roles }
+ });
+ return {
+ roles: membership.roles.map((el) => ({ ...el, projectMembershipId: req.params.membershipId }))
+ };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/users",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "removeCertManagerUsers",
+ body: z.object({
+ emails: z
+ .string()
+ .email()
+ .array()
+ .default([])
+ .refine((val) => val.every((el) => el === el.toLowerCase()), "Email must be lowercase"),
+ usernames: z
+ .string()
+ .array()
+ .default([])
+ .refine((val) => val.every((el) => el === el.toLowerCase()), "Username must be lowercase")
+ }),
+ response: { 200: z.object({ memberships: ProjectMembershipsSchema.omit({ projectId: true }).array() }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const memberships = await server.services.projectMembership.deleteProjectMemberships({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId,
+ emails: req.body.emails,
+ usernames: req.body.usernames
+ });
+ await Promise.all(
+ memberships.map((membership) =>
+ server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId,
+ event: {
+ type: EventType.REMOVE_PROJECT_MEMBER,
+ metadata: { userId: membership.actorUserId as string, email: "" }
+ }
+ })
+ )
+ );
+ return {
+ memberships: memberships.map((el) => ({ ...el, userId: el.actorUserId as string }))
+ };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/users/:membershipId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "removeCertManagerUser",
+ params: z.object({ membershipId: z.string().trim().min(1) }),
+ response: { 200: z.object({ membership: ProjectMembershipsSchema.omit({ projectId: true }) }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { userId } = await server.services.convertor.userMembershipIdToUserId(
+ req.params.membershipId,
+ AccessScope.Project,
+ req.permission.orgId
+ );
+ const { membership } = await server.services.membershipUser.deleteMembership({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ selector: { userId }
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId,
+ event: {
+ type: EventType.REMOVE_PROJECT_MEMBER,
+ metadata: { userId: membership.actorUserId as string, email: "" }
+ }
+ });
+ return { membership: { ...membership, userId } };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/identities",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "listCertManagerIdentities",
+ querystring: z.object({
+ offset: z.coerce.number().min(0).default(0).optional(),
+ limit: z.coerce.number().min(1).max(1000).default(20).optional(),
+ identityName: z.string().trim().optional(),
+ roles: z
+ .string()
+ .transform((val) => val.split(",").map((role) => role.trim()))
+ .optional()
+ }),
+ response: {
+ 200: z.object({
+ identityMemberships: z
+ .object({
+ id: z.string(),
+ identityId: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ roles: z.array(MembershipRoleSchema),
+ identity: IdentitiesSchema.pick({ name: true, id: true, orgId: true })
+ })
+ .array(),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { data: identityMemberships, totalCount } = await server.services.membershipIdentity.listMemberships({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ data: {
+ offset: req.query.offset,
+ limit: req.query.limit,
+ identityName: req.query.identityName,
+ roles: req.query.roles
+ }
+ });
+ return { identityMemberships, totalCount };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/identities/available",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "listAvailableCertManagerIdentities",
+ querystring: z.object({
+ offset: z.coerce.number().min(0).default(0).optional(),
+ limit: z.coerce.number().min(1).max(1000).default(20).optional(),
+ identityName: z.string().trim().optional()
+ }),
+ response: {
+ 200: z.object({
+ identities: IdentitiesSchema.pick({ id: true, name: true }).array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { identities } = await server.services.membershipIdentity.listAvailableIdentities({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ data: {
+ offset: req.query.offset,
+ limit: req.query.limit,
+ identityName: req.query.identityName
+ }
+ });
+ return { identities };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/identities/:identityId",
+ config: { rateLimit: readLimit },
+ schema: {
+ operationId: "getCertManagerIdentity",
+ params: z.object({ identityId: z.string().trim().min(1) }),
+ response: {
+ 200: z.object({
+ identityMembership: z.object({
+ id: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ roles: z.array(MembershipRoleSchema),
+ lastLoginAuthMethod: z.string().nullable().optional(),
+ lastLoginTime: z.date().nullable().optional(),
+ identity: IdentitiesSchema.pick({ name: true, id: true, orgId: true }).extend({
+ authMethods: z.array(z.string()),
+ metadata: z
+ .object({
+ id: z.string().trim().min(1),
+ key: z.string().trim().min(1),
+ value: z.string().trim().min(1)
+ })
+ .array()
+ .optional()
+ })
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const identityMembership = await server.services.membershipIdentity.getMembershipByIdentityId({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ selector: { identityId: req.params.identityId }
+ });
+ return { identityMembership };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/identities/:identityId",
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "addCertManagerIdentity",
+ params: z.object({ identityId: z.string().trim().min(1) }),
+ body: z.object({
+ role: z.string().trim().optional().default(ProjectMembershipRole.NoAccess),
+ roles: z
+ .array(
+ z.union([
+ z.object({
+ role: z.string(),
+ isTemporary: z.literal(false).default(false)
+ }),
+ z.object({
+ role: z.string(),
+ isTemporary: z.literal(true),
+ temporaryMode: z.nativeEnum(TemporaryPermissionMode),
+ temporaryRange: z.string().refine((val) => ms(val) > 0, "Temporary range must be a positive number"),
+ temporaryAccessStartTime: z.string().datetime()
+ })
+ ])
+ )
+ .optional()
+ }),
+ response: { 200: z.object({ identityMembership: IdentityProjectMembershipsSchema.omit({ projectId: true }) }) }
+ },
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { role, roles } = req.body;
+ if (!role && !roles) {
+ throw new BadRequestError({ message: "You must provide either role or roles field" });
+ }
+ const { membership } = await server.services.membershipIdentity.createMembership({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ data: {
+ identityId: req.params.identityId,
+ roles: roles || [{ role, isTemporary: false }]
+ }
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId,
+ event: {
+ type: EventType.CREATE_IDENTITY_PROJECT_MEMBERSHIP,
+ metadata: { identityId: req.params.identityId, roles: req.body.roles }
+ }
+ });
+ return { identityMembership: { ...membership, identityId: req.params.identityId } };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/identities/:identityId",
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "updateCertManagerIdentity",
+ params: z.object({ identityId: z.string().trim().min(1) }),
+ body: RolesUpdateBodySchema,
+ response: { 200: z.object({ identityMembership: IdentityProjectMembershipsSchema.omit({ projectId: true }) }) }
+ },
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { membership } = await server.services.membershipIdentity.updateMembership({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ selector: { identityId: req.params.identityId },
+ data: { roles: req.body.roles }
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId,
+ event: {
+ type: EventType.UPDATE_IDENTITY_PROJECT_MEMBERSHIP,
+ metadata: { identityId: req.params.identityId, roles: req.body.roles }
+ }
+ });
+ return { identityMembership: { ...membership, identityId: req.params.identityId } };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/identities/:identityId",
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "removeCertManagerIdentity",
+ params: z.object({ identityId: z.string().trim().min(1) }),
+ response: { 200: z.object({ identityMembership: IdentityProjectMembershipsSchema.omit({ projectId: true }) }) }
+ },
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { membership } = await server.services.membershipIdentity.deleteMembership({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ selector: { identityId: req.params.identityId }
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId,
+ event: {
+ type: EventType.DELETE_IDENTITY_PROJECT_MEMBERSHIP,
+ metadata: { identityId: req.params.identityId }
+ }
+ });
+ return { identityMembership: { ...membership, identityId: req.params.identityId } };
+ }
+ });
+
+ const certManagerGroupMembershipRoleSchema = z.object({
+ id: z.string(),
+ role: z.string(),
+ customRoleId: z.string().optional().nullable(),
+ customRoleName: z.string().optional().nullable(),
+ customRoleSlug: z.string().optional().nullable(),
+ isTemporary: z.boolean(),
+ temporaryMode: z.string().optional().nullable(),
+ temporaryRange: z.string().nullable().optional(),
+ temporaryAccessStartTime: z.date().nullable().optional(),
+ temporaryAccessEndTime: z.date().nullable().optional(),
+ createdAt: z.date().optional(),
+ updatedAt: z.date().optional()
+ });
+
+ const certManagerGroupMembershipSchema = z.object({
+ id: z.string().uuid(),
+ groupId: z.string().uuid(),
+ group: GroupsSchema.pick({ id: true, name: true, slug: true }).extend({
+ orgId: z.string().uuid().optional()
+ }),
+ roles: z.array(certManagerGroupMembershipRoleSchema),
+ createdAt: z.date(),
+ updatedAt: z.date()
+ });
+
+ server.route({
+ method: "GET",
+ url: "/groups",
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "listCertManagerGroups",
+ response: { 200: z.object({ groupMemberships: z.array(certManagerGroupMembershipSchema) }) }
+ },
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { memberships: groupMemberships } = await server.services.membershipGroup.listMemberships({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ data: {}
+ });
+ return {
+ groupMemberships: groupMemberships.map((el) => ({
+ ...el,
+ groupId: el.actorGroupId as string,
+ group: el.group
+ }))
+ };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/groups/:groupId",
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "getCertManagerGroup",
+ params: z.object({ groupId: z.string().uuid() }),
+ response: { 200: z.object({ groupMembership: certManagerGroupMembershipSchema }) }
+ },
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { membership } = await server.services.membershipGroup.getMembershipByGroupId({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ selector: { groupId: req.params.groupId }
+ });
+ return {
+ groupMembership: {
+ ...membership,
+ groupId: membership.actorGroupId as string,
+ group: membership.group
+ }
+ };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/groups/:groupId",
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "addCertManagerGroup",
+ params: z.object({ groupId: z.string().uuid() }),
+ body: z.object({
+ role: z.string().trim().min(1).default(ProjectMembershipRole.NoAccess).optional(),
+ roles: z
+ .array(
+ z.union([
+ z.object({
+ role: z.string(),
+ isTemporary: z.literal(false).default(false)
+ }),
+ z.object({
+ role: z.string(),
+ isTemporary: z.literal(true),
+ temporaryMode: z.nativeEnum(TemporaryPermissionMode),
+ temporaryRange: z.string().refine((val) => ms(val) > 0, "Temporary range must be a positive number"),
+ temporaryAccessStartTime: z.string().datetime()
+ })
+ ])
+ )
+ .optional()
+ }),
+ response: { 200: z.object({ groupMembership: certManagerGroupMembershipSchema }) }
+ },
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const roles =
+ req.body.roles ??
+ (req.body.role
+ ? [{ role: req.body.role, isTemporary: false }]
+ : [{ role: ProjectMembershipRole.NoAccess, isTemporary: false }]);
+ await server.services.membershipGroup.createMembership({
+ permission: req.permission,
+ data: { groupId: req.params.groupId, roles },
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId }
+ });
+ const { membership: full } = await server.services.membershipGroup.getMembershipByGroupId({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ selector: { groupId: req.params.groupId }
+ });
+ return {
+ groupMembership: {
+ ...full,
+ groupId: full.actorGroupId as string,
+ group: full.group
+ }
+ };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/groups/:groupId",
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "updateCertManagerGroup",
+ params: z.object({ groupId: z.string().uuid() }),
+ body: RolesUpdateBodySchema,
+ response: { 200: z.object({ roles: ProjectUserMembershipRolesSchema.array() }) }
+ },
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { membership: groupMembership } = await server.services.membershipGroup.updateMembership({
+ permission: req.permission,
+ selector: { groupId: req.params.groupId },
+ data: { roles: req.body.roles },
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId }
+ });
+ return {
+ roles: groupMembership.roles.map((el) => ({ ...el, projectMembershipId: groupMembership.id }))
+ };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/groups/:groupId",
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "removeCertManagerGroup",
+ params: z.object({ groupId: z.string().uuid() }),
+ response: {
+ 200: z.object({
+ groupMembership: certManagerGroupMembershipSchema
+ .pick({ id: true, groupId: true })
+ .extend({ createdAt: z.date(), updatedAt: z.date() })
+ })
+ }
+ },
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { membership: groupMembership } = await server.services.membershipGroup.deleteMembership({
+ permission: req.permission,
+ selector: { groupId: req.params.groupId },
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId }
+ });
+ return {
+ groupMembership: {
+ id: groupMembership.id,
+ groupId: groupMembership.actorGroupId as string,
+ createdAt: groupMembership.createdAt,
+ updatedAt: groupMembership.updatedAt
+ }
+ };
+ }
+ });
+
+ const CERT_MANAGER_ROLE_SLUGS = new Set([ProjectMembershipRole.Admin, ProjectMembershipRole.Member]);
+ const CERT_MANAGER_CUSTOM_ROLE_ERROR =
+ "Cert Manager does not support custom roles. Use the built-in Admin or Guest role.";
+
+ server.route({
+ method: "GET",
+ url: "/roles",
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "listCertManagerRoles",
+ response: {
+ 200: z.object({
+ roles: ProjectRolesSchema.omit({ permissions: true, version: true, projectId: true }).array()
+ })
+ }
+ },
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const { roles } = await server.services.role.listRoles({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ data: {}
+ });
+ return {
+ roles: roles
+ .filter((el) => CERT_MANAGER_ROLE_SLUGS.has(el.slug as ProjectMembershipRole))
+ .map((el) => ({
+ ...el,
+ name: el.slug === ProjectMembershipRole.Member ? "Guest" : el.name
+ }))
+ };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/roles/slug/:roleSlug",
+ config: { rateLimit: readLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "getCertManagerRoleBySlug",
+ params: z.object({ roleSlug: z.string().trim().min(1) }),
+ response: { 200: z.object({ role: SanitizedRoleSchema.omit({ projectId: true }) }) }
+ },
+ handler: async (req) => {
+ const projectId = req.certManagerProjectId;
+ const role = await server.services.role.getRoleBySlug({
+ permission: req.permission,
+ scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },
+ selector: { slug: req.params.roleSlug }
+ });
+ return { role };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/roles",
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: { operationId: "createCertManagerRole" },
+ handler: async () => {
+ throw new BadRequestError({ message: CERT_MANAGER_CUSTOM_ROLE_ERROR });
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/roles/:roleId",
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "updateCertManagerRole",
+ params: z.object({ roleId: z.string().trim().min(1) })
+ },
+ handler: async () => {
+ throw new BadRequestError({ message: CERT_MANAGER_CUSTOM_ROLE_ERROR });
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/roles/:roleId",
+ config: { rateLimit: writeLimit },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ operationId: "deleteCertManagerRole",
+ params: z.object({ roleId: z.string().trim().min(1) })
+ },
+ handler: async () => {
+ throw new BadRequestError({ message: CERT_MANAGER_CUSTOM_ROLE_ERROR });
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/cert-manager-instance-router.ts b/backend/src/server/routes/v1/cert-manager-instance-router.ts
new file mode 100644
index 0000000000..80dbe3fd98
--- /dev/null
+++ b/backend/src/server/routes/v1/cert-manager-instance-router.ts
@@ -0,0 +1,142 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } 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";
+
+const ProjectSummarySchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ slug: z.string(),
+ createdAt: z.date()
+});
+
+const InstanceStateSchema = z.object({
+ activeProjectId: z.string().nullable(),
+ projects: z.array(ProjectSummarySchema),
+ isMultiInstance: z.boolean()
+});
+
+const LegacyInstanceSchema = ProjectSummarySchema.extend({
+ certificateCount: z.number().int().nonnegative(),
+ syncCount: z.number().int().nonnegative(),
+ alertCount: z.number().int().nonnegative(),
+ isActive: z.boolean()
+});
+
+export const registerCertManagerInstanceRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/instance",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "getCertManagerInstanceState",
+ description:
+ "Get the active Cert Manager project and the list of legacy Cert Manager projects in this organization.",
+ tags: [ApiDocsTags.CertManagerInstance],
+ response: { 200: InstanceStateSchema }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const state = await server.services.certManagerInstance.getInstanceState({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.GET_CERT_MANAGER_INSTANCE_STATE,
+ metadata: {
+ activeProjectId: state.activeProjectId,
+ projectCount: state.projects.length,
+ isMultiInstance: state.isMultiInstance
+ }
+ }
+ });
+
+ return state;
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/instance/legacy",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listCertManagerLegacyInstances",
+ description: "List all Cert Manager projects in the organization with their certificate, sync, and alert counts.",
+ tags: [ApiDocsTags.CertManagerInstance],
+ response: {
+ 200: z.object({
+ activeProjectId: z.string().nullable(),
+ instances: z.array(LegacyInstanceSchema)
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.certManagerInstance.listLegacyInstances({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/instance/active-project",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "setCertManagerActiveProject",
+ description:
+ "Set the active Cert Manager project for this organization. New API requests resolve to this project when no projectId is supplied.",
+ tags: [ApiDocsTags.CertManagerInstance],
+ body: z.object({ projectId: z.string().uuid() }),
+ response: {
+ 200: z.object({
+ activeProjectId: z.string(),
+ previousActiveProjectId: z.string().nullable(),
+ projectName: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.certManagerInstance.setActiveProject(
+ {
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ },
+ req.body.projectId
+ );
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.SET_CERT_MANAGER_ACTIVE_PROJECT,
+ metadata: {
+ activeProjectId: result.activeProjectId,
+ previousActiveProjectId: result.previousActiveProjectId,
+ projectName: result.projectName
+ }
+ }
+ });
+
+ return result;
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/certificate-authority-router.ts b/backend/src/server/routes/v1/certificate-authority-router.ts
index a5d69782ca..317a4a2554 100644
--- a/backend/src/server/routes/v1/certificate-authority-router.ts
+++ b/backend/src/server/routes/v1/certificate-authority-router.ts
@@ -38,7 +38,6 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {
description: "Create CA",
body: z
.object({
- projectSlug: z.string().trim().describe(CERTIFICATE_AUTHORITIES.CREATE.projectSlug),
type: z.nativeEnum(InternalCaType).describe(CERTIFICATE_AUTHORITIES.CREATE.type),
friendlyName: z.string().optional().describe(CERTIFICATE_AUTHORITIES.CREATE.friendlyName),
commonName: z.string().trim().describe(CERTIFICATE_AUTHORITIES.CREATE.commonName),
@@ -98,6 +97,7 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {
actorAuthMethod: req.permission.authMethod,
isInternal: false,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.body
});
diff --git a/backend/src/server/routes/v1/certificate-authority-routers/azure-ad-cs-certificate-authority-router.ts b/backend/src/server/routes/v1/certificate-authority-routers/azure-ad-cs-certificate-authority-router.ts
index d1c250c673..6e1b4a612a 100644
--- a/backend/src/server/routes/v1/certificate-authority-routers/azure-ad-cs-certificate-authority-router.ts
+++ b/backend/src/server/routes/v1/certificate-authority-routers/azure-ad-cs-certificate-authority-router.ts
@@ -35,9 +35,6 @@ export const registerAzureAdCsCertificateAuthorityRouter = async (server: Fastif
params: z.object({
caId: z.string().describe("Azure AD CS CA ID")
}),
- querystring: z.object({
- projectId: z.string().describe("Project ID")
- }),
response: {
200: z.object({
templates: z.array(
@@ -52,9 +49,10 @@ export const registerAzureAdCsCertificateAuthorityRouter = async (server: Fastif
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
+ const projectId = req.certManagerProjectId;
const templates = await server.services.certificateAuthority.getAzureAdcsTemplates({
caId: req.params.caId,
- projectId: req.query.projectId,
+ projectId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -63,7 +61,7 @@ export const registerAzureAdCsCertificateAuthorityRouter = async (server: Fastif
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.query.projectId,
+ projectId,
event: {
type: EventType.GET_AZURE_AD_TEMPLATES,
metadata: {
diff --git a/backend/src/server/routes/v1/certificate-authority-routers/certificate-authority-endpoints.ts b/backend/src/server/routes/v1/certificate-authority-routers/certificate-authority-endpoints.ts
index bc74f1abc9..0c34ef739f 100644
--- a/backend/src/server/routes/v1/certificate-authority-routers/certificate-authority-endpoints.ts
+++ b/backend/src/server/routes/v1/certificate-authority-routers/certificate-authority-endpoints.ts
@@ -25,7 +25,7 @@ export const registerCertificateAuthorityEndpoints = <
server: FastifyZodProvider;
createSchema: z.ZodType<{
name: string;
- projectId: string;
+ projectId?: string;
status: CaStatus;
configuration: I["configuration"];
}>;
@@ -49,18 +49,13 @@ export const registerCertificateAuthorityEndpoints = <
hide: false,
operationId: `list${caTypeNameForOpId}CertificateAuthoritiesV1`,
tags: [ApiDocsTags.PkiCertificateAuthorities],
- querystring: z.object({
- projectId: z.string().trim().min(1, "Project ID required")
- }),
response: {
200: responseSchema.array()
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const {
- query: { projectId }
- } = req;
+ const projectId = req.certManagerProjectId;
const certificateAuthorities = (await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{ projectId, type: caType },
@@ -141,8 +136,9 @@ export const registerCertificateAuthorityEndpoints = <
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
+ const body = req.body as { projectId?: string };
const certificateAuthority = (await server.services.certificateAuthority.createCertificateAuthority(
- { ...req.body, type: caType },
+ { ...req.body, projectId: body.projectId ?? req.certManagerProjectId, type: caType },
req.permission
)) as T;
diff --git a/backend/src/server/routes/v1/certificate-authority-routers/general-certificate-authority-router.ts b/backend/src/server/routes/v1/certificate-authority-routers/general-certificate-authority-router.ts
index d417ce835e..dbea4994ee 100644
--- a/backend/src/server/routes/v1/certificate-authority-routers/general-certificate-authority-router.ts
+++ b/backend/src/server/routes/v1/certificate-authority-routers/general-certificate-authority-router.ts
@@ -37,9 +37,6 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ
operationId: "listCertificateAuthoritiesV1General",
tags: [ApiDocsTags.PkiCertificateAuthorities],
description: "Get Certificate Authorities",
- querystring: z.object({
- projectId: z.string()
- }),
response: {
200: z.object({
certificateAuthorities: CertificateAuthoritySchema.array()
@@ -47,9 +44,10 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ
}
},
handler: async (req) => {
+ const projectId = req.certManagerProjectId;
const internalCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.INTERNAL
},
req.permission
@@ -57,7 +55,7 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ
const acmeCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.ACME
},
req.permission
@@ -65,7 +63,7 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ
const azureAdCsCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.AZURE_AD_CS
},
req.permission
@@ -73,7 +71,7 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ
const awsPcaCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.AWS_PCA
},
req.permission
@@ -81,7 +79,7 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ
const digicertCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.DIGICERT
},
req.permission
@@ -89,7 +87,7 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ
const awsAcmPublicCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.AWS_ACM_PUBLIC_CA
},
req.permission
@@ -97,7 +95,7 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ
const venafiTppCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.VENAFI_TPP
},
req.permission
@@ -105,7 +103,7 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.query.projectId,
+ projectId,
event: {
type: EventType.GET_CAS,
metadata: {
diff --git a/backend/src/server/routes/v1/certificate-cleanup-router.ts b/backend/src/server/routes/v1/certificate-cleanup-router.ts
index 513c0198d0..d9dcb1572b 100644
--- a/backend/src/server/routes/v1/certificate-cleanup-router.ts
+++ b/backend/src/server/routes/v1/certificate-cleanup-router.ts
@@ -20,9 +20,6 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvide
operationId: "getCertificateCleanupConfig",
description: "Get certificate cleanup configuration for a project",
tags: [ApiDocsTags.PkiCertificates],
- querystring: z.object({
- projectId: z.string().trim().describe("Project ID")
- }),
response: {
200: z.object({
config: CertificateCleanupConfigsSchema.omit({ id: true }).nullable()
@@ -31,7 +28,7 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvide
},
handler: async (req) => {
const config = await server.services.certificateCleanup.getConfig({
- projectId: req.query.projectId,
+ projectId: req.certManagerProjectId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -54,7 +51,6 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvide
description: "Create or update certificate cleanup configuration for a project",
tags: [ApiDocsTags.PkiCertificates],
body: z.object({
- projectId: z.string().trim().describe("Project ID"),
isEnabled: z.boolean().optional().describe("Enable cleanup"),
postExpiryRetentionDays: z
.number()
@@ -73,7 +69,7 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvide
},
handler: async (req) => {
const config = await server.services.certificateCleanup.updateConfig({
- projectId: req.body.projectId,
+ projectId: req.certManagerProjectId,
isEnabled: req.body.isEnabled,
postExpiryRetentionDays: req.body.postExpiryRetentionDays,
skipCertsWithActiveSyncs: req.body.skipCertsWithActiveSyncs,
@@ -85,11 +81,11 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvide
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.body.projectId,
+ projectId: req.certManagerProjectId,
event: {
type: EventType.UPDATE_CERTIFICATE_CLEANUP_CONFIG,
metadata: {
- projectId: req.body.projectId,
+ projectId: req.certManagerProjectId,
isEnabled: config.isEnabled,
postExpiryRetentionDays: config.postExpiryRetentionDays,
skipCertsWithActiveSyncs: config.skipCertsWithActiveSyncs
diff --git a/backend/src/server/routes/v1/certificate-inventory-view-router.ts b/backend/src/server/routes/v1/certificate-inventory-view-router.ts
index 80909783ff..80b4896e39 100644
--- a/backend/src/server/routes/v1/certificate-inventory-view-router.ts
+++ b/backend/src/server/routes/v1/certificate-inventory-view-router.ts
@@ -42,7 +42,7 @@ const ColumnsSchema = z.array(z.enum(ValidColumns)).max(20);
export const registerCertificateInventoryViewRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:projectId/certificate-inventory-views",
+ url: "/",
config: {
rateLimit: readLimit
},
@@ -51,9 +51,6 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
operationId: "listCertificateInventoryViews",
tags: [ApiDocsTags.PkiCertificates],
description: "List system and custom certificate inventory views for a project.",
- params: z.object({
- projectId: z.string().trim()
- }),
response: {
200: z.object({
systemViews: z.array(
@@ -87,7 +84,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
return server.services.certificateInventoryView.listViews({
- projectId: req.params.projectId,
+ projectId: req.certManagerProjectId,
actorId: req.permission.id,
actorOrgId: req.permission.orgId,
actorAuthMethod: req.permission.authMethod,
@@ -98,7 +95,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
server.route({
method: "POST",
- url: "/:projectId/certificate-inventory-views",
+ url: "/",
config: {
rateLimit: writeLimit
},
@@ -107,9 +104,6 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
operationId: "createCertificateInventoryView",
tags: [ApiDocsTags.PkiCertificates],
description: "Create a custom certificate inventory view.",
- params: z.object({
- projectId: z.string().trim()
- }),
body: z.object({
name: z.string().trim().min(1).max(255),
filters: InventoryViewFiltersSchema.default({}),
@@ -125,7 +119,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
const view = await server.services.certificateInventoryView.createView({
- projectId: req.params.projectId,
+ projectId: req.certManagerProjectId,
name: req.body.name,
filters: req.body.filters,
columns: req.body.columns,
@@ -137,7 +131,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.params.projectId,
+ projectId: req.certManagerProjectId,
event: {
type: EventType.CREATE_CERTIFICATE_INVENTORY_VIEW,
metadata: {
@@ -155,7 +149,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
server.route({
method: "PATCH",
- url: "/:projectId/certificate-inventory-views/:viewId",
+ url: "/:viewId",
config: {
rateLimit: writeLimit
},
@@ -165,7 +159,6 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
tags: [ApiDocsTags.PkiCertificates],
description: "Update a custom certificate inventory view.",
params: z.object({
- projectId: z.string().trim(),
viewId: z.string().uuid()
}),
body: z.object({
@@ -184,7 +177,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
handler: async (req) => {
const view = await server.services.certificateInventoryView.updateView({
viewId: req.params.viewId,
- projectId: req.params.projectId,
+ projectId: req.certManagerProjectId,
name: req.body.name,
filters: req.body.filters,
columns: req.body.columns,
@@ -196,7 +189,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.params.projectId,
+ projectId: req.certManagerProjectId,
event: {
type: EventType.UPDATE_CERTIFICATE_INVENTORY_VIEW,
metadata: {
@@ -214,7 +207,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
server.route({
method: "DELETE",
- url: "/:projectId/certificate-inventory-views/:viewId",
+ url: "/:viewId",
config: {
rateLimit: writeLimit
},
@@ -224,7 +217,6 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
tags: [ApiDocsTags.PkiCertificates],
description: "Delete a custom certificate inventory view.",
params: z.object({
- projectId: z.string().trim(),
viewId: z.string().uuid()
}),
response: {
@@ -237,7 +229,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
handler: async (req) => {
const view = await server.services.certificateInventoryView.deleteView({
viewId: req.params.viewId,
- projectId: req.params.projectId,
+ projectId: req.certManagerProjectId,
actorId: req.permission.id,
actorOrgId: req.permission.orgId,
actorAuthMethod: req.permission.authMethod,
@@ -245,7 +237,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.params.projectId,
+ projectId: req.certManagerProjectId,
event: {
type: EventType.DELETE_CERTIFICATE_INVENTORY_VIEW,
metadata: {
diff --git a/backend/src/server/routes/v1/certificate-policy-router.ts b/backend/src/server/routes/v1/certificate-policy-router.ts
index d872288774..73d6dda222 100644
--- a/backend/src/server/routes/v1/certificate-policy-router.ts
+++ b/backend/src/server/routes/v1/certificate-policy-router.ts
@@ -175,7 +175,6 @@ const policyBasicConstraintsSchema = z
.nullable();
const createCertificatePolicySchema = z.object({
- projectId: z.string().min(1),
name: slugSchema({ min: 1, max: 255, field: "Name" }),
description: z.string().max(1000).optional(),
subject: z.array(policySubjectSchema).optional(),
@@ -219,19 +218,18 @@ export const registerCertificatePolicyRouter = async (server: FastifyZodProvider
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const { projectId, ...data } = req.body;
const certificatePolicy = await server.services.certificatePolicy.createPolicy({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod!,
actorOrgId: req.permission.orgId,
- projectId,
- data
+ projectId: req.certManagerProjectId,
+ data: req.body
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId,
+ projectId: req.certManagerProjectId,
event: {
type: EventType.CREATE_CERTIFICATE_POLICY,
metadata: {
@@ -257,7 +255,6 @@ export const registerCertificatePolicyRouter = async (server: FastifyZodProvider
operationId: "listCertificatePolicies",
tags: [ApiDocsTags.PkiCertificatePolicies],
querystring: z.object({
- projectId: z.string().min(1),
offset: z.coerce.number().min(0).default(0),
limit: z.coerce.number().min(1).max(100).default(20),
search: z.string().optional()
@@ -276,16 +273,17 @@ export const registerCertificatePolicyRouter = async (server: FastifyZodProvider
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod!,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.query
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.query.projectId,
+ projectId: req.certManagerProjectId,
event: {
type: EventType.LIST_CERTIFICATE_POLICIES,
metadata: {
- projectId: req.query.projectId
+ projectId: req.certManagerProjectId
}
}
});
diff --git a/backend/src/server/routes/v1/certificate-profiles-router.ts b/backend/src/server/routes/v1/certificate-profiles-router.ts
index 2e3f354ebf..586c3eeb69 100644
--- a/backend/src/server/routes/v1/certificate-profiles-router.ts
+++ b/backend/src/server/routes/v1/certificate-profiles-router.ts
@@ -56,7 +56,6 @@ export const registerCertificateProfilesRouter = async (
tags: [ApiDocsTags.PkiCertificateProfiles],
body: z
.object({
- projectId: z.string().min(1),
caId: z.string().uuid().optional(),
certificatePolicyId: z.string().uuid(),
slug: z
@@ -119,39 +118,6 @@ export const registerCertificateProfilesRouter = async (
})
.nullish()
})
- .refine(
- (data) => {
- if (data.enrollmentType === EnrollmentType.EST) {
- return !!data.estConfig;
- }
- return true;
- },
- {
- message: "EST enrollment type requires EST configuration"
- }
- )
- .refine(
- (data) => {
- if (data.enrollmentType === EnrollmentType.API) {
- return !!data.apiConfig;
- }
- return true;
- },
- {
- message: "API enrollment type requires API configuration"
- }
- )
- .refine(
- (data) => {
- if (data.enrollmentType === EnrollmentType.ACME) {
- return !!data.acmeConfig;
- }
- return true;
- },
- {
- message: "ACME enrollment type requires ACME configuration"
- }
- )
.refine(
(data) => {
if (data.enrollmentType === EnrollmentType.ACME && data.acmeConfig) {
@@ -198,8 +164,7 @@ export const registerCertificateProfilesRouter = async (
)
.refine(
(data) => {
- if (data.enrollmentType === EnrollmentType.SCEP) {
- if (!data.scepConfig) return false;
+ if (data.enrollmentType === EnrollmentType.SCEP && data.scepConfig) {
// Static mode requires a challenge password with min 8 chars; dynamic mode does not
if (data.scepConfig.challengeType === ScepChallengeType.DYNAMIC) return true;
return !!data.scepConfig.challengePassword && data.scepConfig.challengePassword.length >= 8;
@@ -270,13 +235,13 @@ export const registerCertificateProfilesRouter = async (
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.body.projectId,
+ projectId: req.certManagerProjectId,
data: req.body
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.body.projectId,
+ projectId: req.certManagerProjectId,
event: {
type: EventType.CREATE_CERTIFICATE_PROFILE,
metadata: {
@@ -304,7 +269,6 @@ export const registerCertificateProfilesRouter = async (
...(enableOperationId ? { operationId: "listCertificateProfiles" } : {}),
tags: [ApiDocsTags.PkiCertificateProfiles],
querystring: z.object({
- projectId: z.string().min(1),
offset: z.coerce.number().min(0).default(0),
limit: z.coerce.number().min(1).max(100).default(20),
search: z.string().optional(),
@@ -385,16 +349,17 @@ export const registerCertificateProfilesRouter = async (
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.query
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.query.projectId,
+ projectId: req.certManagerProjectId,
event: {
type: EventType.LIST_CERTIFICATE_PROFILES,
metadata: {
- projectId: req.query.projectId
+ projectId: req.certManagerProjectId
}
}
});
@@ -521,9 +486,6 @@ export const registerCertificateProfilesRouter = async (
params: z.object({
slug: z.string().min(1)
}),
- querystring: z.object({
- projectId: z.string().min(1)
- }),
response: {
200: z.object({
certificateProfile: PkiCertificateProfilesSchema.extend({
@@ -540,7 +502,7 @@ export const registerCertificateProfilesRouter = async (
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.query.projectId,
+ projectId: req.certManagerProjectId,
slug: req.params.slug
});
diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.ts
index 2bacc31be0..4dedb1983d 100644
--- a/backend/src/server/routes/v1/certificate-router.ts
+++ b/backend/src/server/routes/v1/certificate-router.ts
@@ -25,7 +25,6 @@ import { EnrollmentType } from "@app/services/certificate-profile/certificate-pr
import { CertificateRequestStatus } from "@app/services/certificate-request/certificate-request-types";
import { validateTemplateRegexField } from "@app/services/certificate-template/certificate-template-validators";
import { TCertificateIssuanceResponse } from "@app/services/certificate-v3/certificate-v3-types";
-import { ProjectFilterType } from "@app/services/project/project-types";
import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
import { booleanSchema } from "../sanitizedSchemas";
@@ -506,7 +505,6 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
operationId: "listCertificateRequests",
tags: [ApiDocsTags.PkiCertificates],
querystring: z.object({
- projectSlug: z.string().min(1).trim(),
offset: z.coerce.number().min(0).default(0),
limit: z.coerce.number().min(1).max(100).default(20),
search: z.string().trim().optional(),
@@ -553,24 +551,14 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const project = await server.services.project.getAProject({
- actor: req.permission.type,
- actorId: req.permission.id,
- actorOrgId: req.permission.orgId,
- actorAuthMethod: req.permission.authMethod,
- filter: {
- type: ProjectFilterType.SLUG,
- slug: req.query.projectSlug,
- orgId: req.permission.orgId
- }
- });
+ const projectId = req.certManagerProjectId;
const { certificateRequests, totalCount } = await server.services.certificateRequest.listCertificateRequests({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: project.id,
+ projectId,
offset: req.query.offset,
limit: req.query.limit,
search: req.query.search,
@@ -584,7 +572,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: project.id,
+ projectId,
event: {
type: EventType.LIST_CERTIFICATE_REQUESTS,
metadata: {
@@ -629,7 +617,6 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
tags: [ApiDocsTags.PkiCertificates],
description: "Search and filter certificate requests.",
body: z.object({
- projectSlug: z.string().min(1).trim(),
offset: z.number().min(0).default(0),
limit: z.number().min(1).max(100).default(20),
search: z.string().trim().optional(),
@@ -680,25 +667,14 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
const { metadata, ...filters } = req.body;
-
- const project = await server.services.project.getAProject({
- actor: req.permission.type,
- actorId: req.permission.id,
- actorOrgId: req.permission.orgId,
- actorAuthMethod: req.permission.authMethod,
- filter: {
- type: ProjectFilterType.SLUG,
- slug: filters.projectSlug,
- orgId: req.permission.orgId
- }
- });
+ const projectId = req.certManagerProjectId;
const { certificateRequests, totalCount } = await server.services.certificateRequest.listCertificateRequests({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: project.id,
+ projectId,
offset: filters.offset,
limit: filters.limit,
search: filters.search,
@@ -713,7 +689,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: project.id,
+ projectId,
event: {
type: EventType.LIST_CERTIFICATE_REQUESTS,
metadata: {
@@ -1472,8 +1448,6 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
tags: [ApiDocsTags.PkiCertificates],
description: "Import certificate",
body: z.object({
- projectSlug: z.string().trim().min(1).describe(CERTIFICATES.IMPORT.projectSlug),
-
certificatePem: z.string().trim().min(1).describe(CERTIFICATES.IMPORT.certificatePem),
privateKeyPem: z.string().trim().min(1).describe(CERTIFICATES.IMPORT.privateKeyPem),
chainPem: z.string().trim().min(1).describe(CERTIFICATES.IMPORT.chainPem),
@@ -1497,6 +1471,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.body
});
diff --git a/backend/src/server/routes/v1/deprecated-certificate-authority-routers/azure-ad-cs-certificate-authority-router.ts b/backend/src/server/routes/v1/deprecated-certificate-authority-routers/azure-ad-cs-certificate-authority-router.ts
index 9407ee6811..48861a892f 100644
--- a/backend/src/server/routes/v1/deprecated-certificate-authority-routers/azure-ad-cs-certificate-authority-router.ts
+++ b/backend/src/server/routes/v1/deprecated-certificate-authority-routers/azure-ad-cs-certificate-authority-router.ts
@@ -34,9 +34,6 @@ export const registerAzureAdCsCertificateAuthorityRouter = async (server: Fastif
params: z.object({
caId: z.string().describe("Azure AD CS CA ID")
}),
- querystring: z.object({
- projectId: z.string().describe("Project ID")
- }),
response: {
200: z.object({
templates: z.array(
@@ -51,9 +48,10 @@ export const registerAzureAdCsCertificateAuthorityRouter = async (server: Fastif
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
+ const projectId = req.certManagerProjectId;
const templates = await server.services.certificateAuthority.getAzureAdcsTemplates({
caId: req.params.caId,
- projectId: req.query.projectId,
+ projectId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -62,7 +60,7 @@ export const registerAzureAdCsCertificateAuthorityRouter = async (server: Fastif
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.query.projectId,
+ projectId,
event: {
type: EventType.GET_AZURE_AD_TEMPLATES,
metadata: {
diff --git a/backend/src/server/routes/v1/deprecated-certificate-authority-routers/certificate-authority-endpoints.ts b/backend/src/server/routes/v1/deprecated-certificate-authority-routers/certificate-authority-endpoints.ts
index dd0f8b2156..76300d0689 100644
--- a/backend/src/server/routes/v1/deprecated-certificate-authority-routers/certificate-authority-endpoints.ts
+++ b/backend/src/server/routes/v1/deprecated-certificate-authority-routers/certificate-authority-endpoints.ts
@@ -25,13 +25,13 @@ export const registerCertificateAuthorityEndpoints = <
server: FastifyZodProvider;
createSchema: z.ZodType<{
name: string;
- projectId: string;
+ projectId?: string;
status: CaStatus;
configuration: I["configuration"];
enableDirectIssuance: boolean;
}>;
updateSchema: z.ZodType<{
- projectId: string;
+ projectId?: string;
name?: string;
status?: CaStatus;
configuration?: I["configuration"];
@@ -48,18 +48,13 @@ export const registerCertificateAuthorityEndpoints = <
schema: {
hide: false,
tags: [ApiDocsTags.PkiCertificateAuthorities],
- querystring: z.object({
- projectId: z.string().trim().min(1, "Project ID required")
- }),
response: {
200: responseSchema.array()
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const {
- query: { projectId }
- } = req;
+ const projectId = req.certManagerProjectId;
const certificateAuthorities = (await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{ projectId, type: caType },
@@ -93,9 +88,6 @@ export const registerCertificateAuthorityEndpoints = <
params: z.object({
caName: z.string()
}),
- querystring: z.object({
- projectId: z.string().uuid()
- }),
response: {
200: responseSchema
}
@@ -103,7 +95,7 @@ export const registerCertificateAuthorityEndpoints = <
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
const { caName } = req.params;
- const { projectId } = req.query;
+ const projectId = req.certManagerProjectId;
const certificateAuthority =
(await server.services.certificateAuthority.findCertificateAuthorityByNameAndProjectId(
@@ -143,8 +135,9 @@ export const registerCertificateAuthorityEndpoints = <
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
+ const body = req.body as { projectId?: string };
const certificateAuthority = (await server.services.certificateAuthority.createCertificateAuthority(
- { ...req.body, type: caType },
+ { ...req.body, projectId: body.projectId ?? req.certManagerProjectId, type: caType },
req.permission
)) as T;
@@ -184,10 +177,11 @@ export const registerCertificateAuthorityEndpoints = <
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
const { caName } = req.params;
-
+ const body = req.body as { projectId?: string };
const certificateAuthority = (await server.services.certificateAuthority.deprecatedUpdateCertificateAuthority(
{
...req.body,
+ projectId: body.projectId ?? req.certManagerProjectId,
type: caType,
caName
},
@@ -223,9 +217,6 @@ export const registerCertificateAuthorityEndpoints = <
params: z.object({
caName: z.string()
}),
- body: z.object({
- projectId: z.string().uuid()
- }),
response: {
200: responseSchema
}
@@ -233,7 +224,7 @@ export const registerCertificateAuthorityEndpoints = <
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
const { caName } = req.params;
- const { projectId } = req.body;
+ const projectId = req.certManagerProjectId;
const certificateAuthority = (await server.services.certificateAuthority.deprecatedDeleteCertificateAuthority(
{ caName, type: caType, projectId },
diff --git a/backend/src/server/routes/v1/deprecated-certificate-router.ts b/backend/src/server/routes/v1/deprecated-certificate-router.ts
index 955407e4cc..0e0d83ec0a 100644
--- a/backend/src/server/routes/v1/deprecated-certificate-router.ts
+++ b/backend/src/server/routes/v1/deprecated-certificate-router.ts
@@ -298,8 +298,6 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =
tags: [ApiDocsTags.PkiCertificates],
description: "Import certificate",
body: z.object({
- projectSlug: z.string().trim().min(1).describe(CERTIFICATES.IMPORT.projectSlug),
-
certificatePem: z.string().trim().min(1).describe(CERTIFICATES.IMPORT.certificatePem),
privateKeyPem: z.string().trim().min(1).describe(CERTIFICATES.IMPORT.privateKeyPem),
chainPem: z.string().trim().min(1).describe(CERTIFICATES.IMPORT.chainPem),
@@ -323,6 +321,7 @@ export const registerDeprecatedCertRouter = async (server: FastifyZodProvider) =
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.body
});
diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.ts
index 1eafb60492..c1234042c8 100644
--- a/backend/src/server/routes/v1/index.ts
+++ b/backend/src/server/routes/v1/index.ts
@@ -1,3 +1,5 @@
+import { blockCertManagerProjectAccess } from "@app/server/plugins/block-cert-manager-project-access";
+import { injectCertManagerProjectId } from "@app/server/plugins/inject-cert-manager-project-id";
import {
APP_CONNECTION_REGISTER_ROUTER_MAP,
registerAppConnectionRouter
@@ -11,6 +13,8 @@ import { registerAdminRouter } from "./admin-router";
import { APPROVAL_POLICY_REGISTER_ROUTER_MAP } from "./approval-policy-routers";
import { registerAuthRoutes } from "./auth-router";
import { registerProjectBotRouter } from "./bot-router";
+import { registerCertManagerAccessRouter } from "./cert-manager-access-router";
+import { registerCertManagerInstanceRouter } from "./cert-manager-instance-router";
import { registerCaRouter } from "./certificate-authority-router";
import { CERTIFICATE_AUTHORITY_REGISTER_ROUTER_MAP } from "./certificate-authority-routers";
import { registerGeneralCertificateAuthorityRouter } from "./certificate-authority-routers/general-certificate-authority-router";
@@ -62,6 +66,7 @@ import { registerOrganizationMembershipsRouter } from "./organization-membership
import { registerOrgRouter } from "./organization-router";
import { registerPasswordRouter } from "./password-router";
import { registerPkiAlertRouter } from "./pki-alert-router";
+import { registerPkiApplicationRouter } from "./pki-application-router";
import { registerPkiCollectionRouter } from "./pki-collection-router";
import { registerPkiSubscriberRouter } from "./pki-subscriber-router";
import { PKI_SYNC_REGISTER_ROUTER_MAP, registerPkiSyncRouter } from "./pki-sync-routers";
@@ -151,8 +156,8 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
await server.register(
async (projectRouter) => {
+ await projectRouter.register(blockCertManagerProjectAccess);
await projectRouter.register(registerProjectRouter);
- await projectRouter.register(registerCertificateInventoryViewRouter);
await projectRouter.register(registerProjectMembershipRouter);
await projectRouter.register(registerProjectIdentityRouter);
await projectRouter.register(registerProjectEnvRouter);
@@ -166,6 +171,7 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
await server.register(
async (membershipsRouter) => {
+ await membershipsRouter.register(blockCertManagerProjectAccess);
await membershipsRouter.register(registerIdentityProjectMembershipRouter);
await membershipsRouter.register(registerProjectGroupMembershipsRouter);
},
@@ -174,6 +180,8 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
await server.register(
async (pkiRouter) => {
+ await pkiRouter.register(injectCertManagerProjectId);
+
await pkiRouter.register(
async (caRouter) => {
for await (const [caType, router] of Object.entries(CERTIFICATE_AUTHORITY_REGISTER_ROUTER_MAP)) {
@@ -195,8 +203,12 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
{ prefix: "/certificate-profiles" }
);
await pkiRouter.register(registerPkiAlertRouter, { prefix: "/alerts" });
+ await pkiRouter.register(registerPkiApplicationRouter, { prefix: "/applications" });
+ await pkiRouter.register(registerCertManagerInstanceRouter);
await pkiRouter.register(registerSignerRouter, { prefix: "/signers" });
await pkiRouter.register(registerCertificateCleanupRouter, { prefix: "/certificate-cleanup" });
+ await pkiRouter.register(registerCertificateInventoryViewRouter, { prefix: "/certificate-inventory-views" });
+ await pkiRouter.register(registerCertManagerAccessRouter, { prefix: "/access" });
await pkiRouter.register(
async (pkiSyncRouter) => {
await registerPkiSyncRouter(pkiSyncRouter as unknown as FastifyZodProvider);
@@ -219,6 +231,7 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
// DO NOT EXTEND THEM ANYMORE!!!
await server.register(
async (pkiRouter) => {
+ await pkiRouter.register(injectCertManagerProjectId);
await pkiRouter.register(registerCaRouter, { prefix: "/ca" });
await pkiRouter.register(
async (caRouter) => {
diff --git a/backend/src/server/routes/v1/pki-alert-router.ts b/backend/src/server/routes/v1/pki-alert-router.ts
index 0a81c90ff1..be8ba1b2c1 100644
--- a/backend/src/server/routes/v1/pki-alert-router.ts
+++ b/backend/src/server/routes/v1/pki-alert-router.ts
@@ -30,7 +30,11 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
description: "Create a new PKI alert",
tags: [ApiDocsTags.PkiAlerting],
body: BasePkiAlertV2Schema.extend({
- projectId: z.string().uuid().describe("Project ID")
+ applicationId: z
+ .string()
+ .uuid()
+ .optional()
+ .describe("Optional Cert Manager Application this alert is scoped to")
}),
response: {
200: z.object({
@@ -66,12 +70,13 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.body
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.body.projectId,
+ projectId: req.certManagerProjectId,
event: {
type: EventType.CREATE_PKI_ALERT,
metadata: {
@@ -100,7 +105,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
description: "List PKI alerts for a project",
tags: [ApiDocsTags.PkiAlerting],
querystring: z.object({
- projectId: z.string().uuid(),
+ applicationId: z.string().uuid().optional(),
search: z.string().optional(),
eventType: z.nativeEnum(PkiAlertEventType).optional(),
enabled: z.coerce.boolean().optional(),
@@ -150,6 +155,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.query
});
@@ -427,7 +433,6 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
description: "Preview certificates that would match the given filter rules",
tags: [ApiDocsTags.PkiAlerting],
body: z.object({
- projectId: z.string().uuid().describe("Project ID"),
filters: z.array(PkiFilterRuleSchema),
alertBefore: z
.string()
@@ -462,6 +467,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.body
});
diff --git a/backend/src/server/routes/v1/pki-application-alert-router.ts b/backend/src/server/routes/v1/pki-application-alert-router.ts
new file mode 100644
index 0000000000..48ba10a02f
--- /dev/null
+++ b/backend/src/server/routes/v1/pki-application-alert-router.ts
@@ -0,0 +1,194 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } 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 {
+ BasePkiAlertV2Schema,
+ PkiAlertEventType,
+ PkiAlertV2ResponseSchema,
+ UpdatePkiAlertV2Schema
+} from "@app/services/pki-alert-v2/pki-alert-v2-types";
+
+import { ApplicationIdParamsSchema } from "./pki-application-schemas";
+
+export const registerPkiApplicationAlertRoutes = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/:applicationId/alerts",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listPkiApplicationAlerts",
+ description: "List alerts for a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: ApplicationIdParamsSchema,
+ querystring: z.object({
+ search: z.string().optional(),
+ eventType: z.nativeEnum(PkiAlertEventType).optional(),
+ enabled: z.coerce.boolean().optional(),
+ limit: z.coerce.number().int().min(1).max(100).default(20),
+ offset: z.coerce.number().int().min(0).default(0)
+ }),
+ response: {
+ 200: z.object({
+ alerts: z.array(PkiAlertV2ResponseSchema),
+ total: z.number().int().nonnegative()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiAlertV2.listAlerts({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ search: req.query.search,
+ eventType: req.query.eventType,
+ enabled: req.query.enabled,
+ limit: req.query.limit,
+ offset: req.query.offset
+ });
+
+ return result;
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:applicationId/alerts",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "createPkiApplicationAlert",
+ description: "Create an alert on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: ApplicationIdParamsSchema,
+ body: BasePkiAlertV2Schema,
+ response: { 200: z.object({ alert: PkiAlertV2ResponseSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const alert = await server.services.pkiAlertV2.createAlert({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ applicationId: req.params.applicationId,
+ projectId: req.certManagerProjectId,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.CREATE_PKI_ALERT,
+ metadata: {
+ pkiAlertId: alert.id,
+ applicationId: req.params.applicationId,
+ name: alert.name,
+ alertBefore: alert.alertBefore ?? undefined,
+ eventType: alert.eventType
+ }
+ }
+ });
+
+ return { alert };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:applicationId/alerts/:alertId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "updatePkiApplicationAlert",
+ description: "Update an alert on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({
+ applicationId: z.string().uuid(),
+ alertId: z.string().uuid()
+ }),
+ body: UpdatePkiAlertV2Schema,
+ response: { 200: z.object({ alert: PkiAlertV2ResponseSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const alert = await server.services.pkiAlertV2.updateAlert({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ applicationId: req.params.applicationId,
+ alertId: req.params.alertId,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.UPDATE_PKI_ALERT,
+ metadata: {
+ pkiAlertId: alert.id,
+ applicationId: req.params.applicationId,
+ name: alert.name,
+ alertBefore: alert.alertBefore ?? undefined,
+ eventType: alert.eventType
+ }
+ }
+ });
+
+ return { alert };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:applicationId/alerts/:alertId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "deletePkiApplicationAlert",
+ description: "Delete an alert from a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({
+ applicationId: z.string().uuid(),
+ alertId: z.string().uuid()
+ }),
+ response: { 200: z.object({ alert: PkiAlertV2ResponseSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const alert = await server.services.pkiAlertV2.deleteAlert({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ applicationId: req.params.applicationId,
+ alertId: req.params.alertId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.DELETE_PKI_ALERT,
+ metadata: {
+ pkiAlertId: alert.id,
+ applicationId: req.params.applicationId
+ }
+ }
+ });
+
+ return { alert };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/pki-application-enrollment-router.ts b/backend/src/server/routes/v1/pki-application-enrollment-router.ts
new file mode 100644
index 0000000000..a7dacb4cfc
--- /dev/null
+++ b/backend/src/server/routes/v1/pki-application-enrollment-router.ts
@@ -0,0 +1,554 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ScepChallengeType } from "@app/ee/services/pki-scep/challenge";
+import { ApiDocsTags } 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";
+
+const ApiEnrollmentSchema = z.object({
+ id: z.string().uuid(),
+ autoRenew: z.boolean(),
+ renewBeforeDays: z.number().int().nullable()
+});
+
+const EstEnrollmentStateSchema = z.object({
+ id: z.string().uuid(),
+ disableBootstrapCaValidation: z.boolean()
+});
+
+const AcmeEnrollmentStateSchema = z.object({
+ id: z.string().uuid(),
+ skipDnsOwnershipVerification: z.boolean(),
+ skipEabBinding: z.boolean()
+});
+
+const ScepEnrollmentStateSchema = z.object({
+ id: z.string().uuid(),
+ challengeType: z.nativeEnum(ScepChallengeType),
+ includeCaCertInResponse: z.boolean(),
+ allowCertBasedRenewal: z.boolean(),
+ dynamicChallengeExpiryMinutes: z.number().int().nullable(),
+ dynamicChallengeMaxPending: z.number().int().nullable()
+});
+
+const EnrollmentStateSchema = z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid(),
+ api: ApiEnrollmentSchema.nullable(),
+ est: EstEnrollmentStateSchema.nullable(),
+ acme: AcmeEnrollmentStateSchema.nullable(),
+ scep: ScepEnrollmentStateSchema.nullable(),
+ estConfigured: z.boolean(),
+ acmeConfigured: z.boolean(),
+ scepConfigured: z.boolean()
+});
+
+export const registerPkiApplicationEnrollmentRoutes = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/:applicationId/profiles/:profileId/enrollment",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "getPkiApplicationEnrollment",
+ description: "Get the enrollment state for a profile on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+ }),
+ response: { 200: EnrollmentStateSchema }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplicationEnrollment.getEnrollment({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.GET_PKI_APPLICATION_ENROLLMENT,
+ metadata: {
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId
+ }
+ }
+ });
+
+ return result;
+ }
+ });
+
+ server.route({
+ method: "PUT",
+ url: "/:applicationId/profiles/:profileId/enrollment/api",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "setPkiApplicationApiEnrollment",
+ description: "Enable or update the API enrollment method for a profile on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+ }),
+ body: z.object({
+ autoRenew: z.boolean().default(false),
+ renewBeforeDays: z.number().int().min(1).max(365).optional()
+ }),
+ response: {
+ 200: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid(),
+ api: ApiEnrollmentSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplicationEnrollment.setApiEnrollment({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId,
+ config: {
+ autoRenew: req.body.autoRenew,
+ renewBeforeDays: req.body.renewBeforeDays
+ }
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.SET_PKI_APPLICATION_API_ENROLLMENT,
+ metadata: {
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId,
+ autoRenew: result.api.autoRenew,
+ renewBeforeDays: result.api.renewBeforeDays
+ }
+ }
+ });
+
+ return result;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:applicationId/profiles/:profileId/enrollment/api",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "clearPkiApplicationApiEnrollment",
+ description: "Disable the API enrollment method for a profile on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplicationEnrollment.clearApiEnrollment({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.CLEAR_PKI_APPLICATION_API_ENROLLMENT,
+ metadata: {
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId
+ }
+ }
+ });
+
+ return result;
+ }
+ });
+
+ server.route({
+ method: "PUT",
+ url: "/:applicationId/profiles/:profileId/enrollment/est",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "setPkiApplicationEstEnrollment",
+ description: "Enable or update the EST enrollment method for a profile on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({ applicationId: z.string().uuid(), profileId: z.string().uuid() }),
+ body: z.object({
+ passphrase: z.string().min(8),
+ disableBootstrapCaValidation: z.boolean().optional().default(false),
+ caChain: z.string().optional()
+ }),
+ response: {
+ 200: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid(),
+ est: z.object({ id: z.string().uuid(), disableBootstrapCaValidation: z.boolean() })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplicationEnrollment.setEstEnrollment({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId,
+ config: {
+ passphrase: req.body.passphrase,
+ disableBootstrapCaValidation: req.body.disableBootstrapCaValidation,
+ caChain: req.body.caChain
+ }
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.SET_PKI_APPLICATION_EST_ENROLLMENT,
+ metadata: {
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId,
+ disableBootstrapCaValidation: result.est.disableBootstrapCaValidation
+ }
+ }
+ });
+ return result;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:applicationId/profiles/:profileId/enrollment/est",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "clearPkiApplicationEstEnrollment",
+ description: "Disable the EST enrollment method for a profile on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({ applicationId: z.string().uuid(), profileId: z.string().uuid() }),
+ response: {
+ 200: z.object({ applicationId: z.string().uuid(), profileId: z.string().uuid() })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplicationEnrollment.clearEstEnrollment({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.CLEAR_PKI_APPLICATION_EST_ENROLLMENT,
+ metadata: { applicationId: req.params.applicationId, profileId: req.params.profileId }
+ }
+ });
+ return result;
+ }
+ });
+
+ server.route({
+ method: "PUT",
+ url: "/:applicationId/profiles/:profileId/enrollment/acme",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "setPkiApplicationAcmeEnrollment",
+ description: "Enable or update the ACME enrollment method for a profile on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({ applicationId: z.string().uuid(), profileId: z.string().uuid() }),
+ body: z
+ .object({
+ skipDnsOwnershipVerification: z.boolean().optional().default(false),
+ skipEabBinding: z.boolean().optional().default(false)
+ })
+ .refine((v) => !(v.skipDnsOwnershipVerification && v.skipEabBinding), {
+ message: "skipDnsOwnershipVerification and skipEabBinding cannot both be enabled — pick at most one.",
+ path: ["skipEabBinding"]
+ }),
+ response: {
+ 200: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid(),
+ acme: z.object({
+ id: z.string().uuid(),
+ skipDnsOwnershipVerification: z.boolean(),
+ skipEabBinding: z.boolean()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplicationEnrollment.setAcmeEnrollment({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId,
+ config: {
+ skipDnsOwnershipVerification: req.body.skipDnsOwnershipVerification,
+ skipEabBinding: req.body.skipEabBinding
+ }
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.SET_PKI_APPLICATION_ACME_ENROLLMENT,
+ metadata: {
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId,
+ skipDnsOwnershipVerification: result.acme.skipDnsOwnershipVerification,
+ skipEabBinding: result.acme.skipEabBinding
+ }
+ }
+ });
+ return result;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:applicationId/profiles/:profileId/enrollment/acme",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "clearPkiApplicationAcmeEnrollment",
+ description: "Disable the ACME enrollment method for a profile on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({ applicationId: z.string().uuid(), profileId: z.string().uuid() }),
+ response: { 200: z.object({ applicationId: z.string().uuid(), profileId: z.string().uuid() }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplicationEnrollment.clearAcmeEnrollment({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.CLEAR_PKI_APPLICATION_ACME_ENROLLMENT,
+ metadata: { applicationId: req.params.applicationId, profileId: req.params.profileId }
+ }
+ });
+ return result;
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:applicationId/profiles/:profileId/enrollment/acme/eab/reveal",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "revealPkiApplicationAcmeEabSecret",
+ description: "Reveal the ACME EAB secret for a profile on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({ applicationId: z.string().uuid(), profileId: z.string().uuid() }),
+ response: {
+ 200: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid(),
+ eabKid: z.string(),
+ eabSecret: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplicationEnrollment.revealAcmeEabSecret({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.REVEAL_PKI_APPLICATION_ACME_EAB_SECRET,
+ metadata: { applicationId: req.params.applicationId, profileId: req.params.profileId }
+ }
+ });
+ return result;
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:applicationId/profiles/:profileId/enrollment/acme/eab/rotate",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "rotatePkiApplicationAcmeEabSecret",
+ description: "Rotate the ACME EAB secret for a profile on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({ applicationId: z.string().uuid(), profileId: z.string().uuid() }),
+ response: { 200: z.object({ applicationId: z.string().uuid(), profileId: z.string().uuid() }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplicationEnrollment.rotateAcmeEabSecret({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.ROTATE_PKI_APPLICATION_ACME_EAB_SECRET,
+ metadata: { applicationId: req.params.applicationId, profileId: req.params.profileId }
+ }
+ });
+ return result;
+ }
+ });
+
+ server.route({
+ method: "PUT",
+ url: "/:applicationId/profiles/:profileId/enrollment/scep",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "setPkiApplicationScepEnrollment",
+ description: "Enable or update the SCEP enrollment method for a profile on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({ applicationId: z.string().uuid(), profileId: z.string().uuid() }),
+ body: z.object({
+ challengeType: z.nativeEnum(ScepChallengeType).optional(),
+ challengePassword: z.string().optional(),
+ includeCaCertInResponse: z.boolean().optional().default(true),
+ allowCertBasedRenewal: z.boolean().optional().default(true),
+ dynamicChallengeExpiryMinutes: z.number().int().min(5).max(1440).optional(),
+ dynamicChallengeMaxPending: z.number().int().min(1).max(1000).optional()
+ }),
+ response: {
+ 200: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid(),
+ scep: z.object({ id: z.string().uuid(), challengeType: z.nativeEnum(ScepChallengeType) })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplicationEnrollment.setScepEnrollment({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId,
+ config: req.body
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.SET_PKI_APPLICATION_SCEP_ENROLLMENT,
+ metadata: {
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId,
+ challengeType: result.scep.challengeType
+ }
+ }
+ });
+ return result;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:applicationId/profiles/:profileId/enrollment/scep",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "clearPkiApplicationScepEnrollment",
+ description: "Disable the SCEP enrollment method for a profile on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({ applicationId: z.string().uuid(), profileId: z.string().uuid() }),
+ response: { 200: z.object({ applicationId: z.string().uuid(), profileId: z.string().uuid() }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplicationEnrollment.clearScepEnrollment({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.CLEAR_PKI_APPLICATION_SCEP_ENROLLMENT,
+ metadata: { applicationId: req.params.applicationId, profileId: req.params.profileId }
+ }
+ });
+ return result;
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/pki-application-membership-router.ts b/backend/src/server/routes/v1/pki-application-membership-router.ts
new file mode 100644
index 0000000000..704a3e2907
--- /dev/null
+++ b/backend/src/server/routes/v1/pki-application-membership-router.ts
@@ -0,0 +1,223 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } 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 { ApplicationIdParamsSchema } from "./pki-application-schemas";
+
+const ApplicationMemberSchema = z.object({
+ membershipId: z.string().uuid(),
+ applicationId: z.string().uuid(),
+ actorUserId: z.string().uuid().nullable().optional(),
+ actorIdentityId: z.string().uuid().nullable().optional(),
+ actorGroupId: z.string().uuid().nullable().optional(),
+ role: z.string(),
+ customRoleId: z.string().uuid().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ details: z
+ .object({
+ name: z.string().nullable(),
+ email: z.string().nullable().optional(),
+ username: z.string().nullable().optional(),
+ authMethod: z.string().nullable().optional(),
+ slug: z.string().nullable().optional()
+ })
+ .nullable()
+ .optional()
+});
+
+export const registerPkiApplicationMembershipRoutes = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/:applicationId/memberships",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listPkiApplicationMembers",
+ description: "List members of a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: ApplicationIdParamsSchema,
+ response: { 200: z.object({ memberships: z.array(ApplicationMemberSchema) }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const memberships = await server.services.pkiApplicationMembership.listMembers({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.LIST_PKI_APPLICATION_MEMBERS,
+ metadata: { applicationId: req.params.applicationId }
+ }
+ });
+
+ return { memberships };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:applicationId/memberships",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "addPkiApplicationMember",
+ description: "Add a user, identity, or group as a member of a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: ApplicationIdParamsSchema,
+ body: z
+ .object({
+ userId: z.string().uuid().optional(),
+ identityId: z.string().uuid().optional(),
+ groupId: z.string().uuid().optional(),
+ role: z.string().min(1)
+ })
+ .refine(
+ (data) => [data.userId, data.identityId, data.groupId].filter(Boolean).length === 1,
+ "Exactly one of userId, identityId, or groupId must be provided."
+ ),
+ response: { 200: z.object({ membership: ApplicationMemberSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const membership = await server.services.pkiApplicationMembership.addMember({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ userId: req.body.userId,
+ identityId: req.body.identityId,
+ groupId: req.body.groupId,
+ role: req.body.role
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.ADD_PKI_APPLICATION_MEMBER,
+ metadata: {
+ applicationId: membership.applicationId,
+ membershipId: membership.membershipId,
+ userId: membership.actorUserId ?? undefined,
+ identityId: membership.actorIdentityId ?? undefined,
+ groupId: membership.actorGroupId ?? undefined,
+ role: membership.role
+ }
+ }
+ });
+
+ return { membership };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:applicationId/memberships/:membershipId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "updatePkiApplicationMemberRole",
+ description: "Update the role of a member on a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({
+ applicationId: z.string().uuid(),
+ membershipId: z.string().uuid()
+ }),
+ body: z.object({
+ role: z.string().min(1)
+ }),
+ response: { 200: z.object({ membership: ApplicationMemberSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const membership = await server.services.pkiApplicationMembership.updateMemberRole({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ membershipId: req.params.membershipId,
+ role: req.body.role
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.UPDATE_PKI_APPLICATION_MEMBER_ROLE,
+ metadata: {
+ applicationId: membership.applicationId,
+ membershipId: membership.membershipId,
+ role: membership.role
+ }
+ }
+ });
+
+ return { membership };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:applicationId/memberships/:membershipId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "removePkiApplicationMember",
+ description: "Remove a member from a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({
+ applicationId: z.string().uuid(),
+ membershipId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ membershipId: z.string().uuid(),
+ applicationId: z.string().uuid()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplicationMembership.removeMember({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ membershipId: req.params.membershipId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.REMOVE_PKI_APPLICATION_MEMBER,
+ metadata: {
+ applicationId: result.applicationId,
+ membershipId: result.membershipId
+ }
+ }
+ });
+
+ return result;
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/pki-application-profile-router.ts b/backend/src/server/routes/v1/pki-application-profile-router.ts
new file mode 100644
index 0000000000..943585f689
--- /dev/null
+++ b/backend/src/server/routes/v1/pki-application-profile-router.ts
@@ -0,0 +1,133 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } 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 { ApplicationIdParamsSchema, ApplicationProfileSchema } from "./pki-application-schemas";
+
+export const registerPkiApplicationProfileRoutes = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/:applicationId/profiles",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listPkiApplicationProfiles",
+ description: "List profiles attached to a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: ApplicationIdParamsSchema,
+ response: {
+ 200: z.object({ profiles: z.array(ApplicationProfileSchema) })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const profiles = await server.services.pkiApplication.listApplicationProfiles({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId
+ });
+
+ return { profiles };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:applicationId/profiles",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "attachPkiApplicationProfiles",
+ description: "Attach one or more profiles to a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: ApplicationIdParamsSchema,
+ body: z.object({
+ profileIds: z.array(z.string().uuid()).min(1)
+ }),
+ response: {
+ 200: z.object({ profiles: z.array(ApplicationProfileSchema) })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const profiles = await server.services.pkiApplication.attachProfiles({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileIds: req.body.profileIds
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.ATTACH_PKI_APPLICATION_PROFILES,
+ metadata: {
+ applicationId: req.params.applicationId,
+ profileIds: req.body.profileIds
+ }
+ }
+ });
+
+ return { profiles };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:applicationId/profiles/:profileId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "detachPkiApplicationProfile",
+ description: "Detach a profile from a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplication.detachProfile({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ profileId: req.params.profileId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.DETACH_PKI_APPLICATION_PROFILE,
+ metadata: {
+ applicationId: result.applicationId,
+ profileId: result.profileId
+ }
+ }
+ });
+
+ return result;
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/pki-application-router.ts b/backend/src/server/routes/v1/pki-application-router.ts
new file mode 100644
index 0000000000..c5055a599d
--- /dev/null
+++ b/backend/src/server/routes/v1/pki-application-router.ts
@@ -0,0 +1,289 @@
+import RE2 from "re2";
+import { z } from "zod";
+
+import { PkiApplicationsSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } 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 { registerPkiApplicationAlertRoutes } from "./pki-application-alert-router";
+import { registerPkiApplicationEnrollmentRoutes } from "./pki-application-enrollment-router";
+import { registerPkiApplicationMembershipRoutes } from "./pki-application-membership-router";
+import { registerPkiApplicationProfileRoutes } from "./pki-application-profile-router";
+import { ApplicationIdParamsSchema, ApplicationProfileSchema } from "./pki-application-schemas";
+import { registerPkiApplicationSyncRoutes } from "./pki-application-sync-router";
+
+export { ApplicationProfileSchema };
+
+const APPLICATION_SLUG_REGEX = new RE2("^[a-z0-9-]+$");
+const APPLICATION_SLUG_MESSAGE = "Slug must contain only lowercase letters, numbers, and hyphens";
+
+const ApplicationListItemSchema = PkiApplicationsSchema.extend({
+ profileCount: z.number().int().nonnegative(),
+ memberCount: z.number().int().nonnegative(),
+ certificateCount: z.number().int().nonnegative()
+});
+
+export const registerPkiApplicationRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "createPkiApplication",
+ description: "Create a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ body: z.object({
+ name: z.string().trim().min(1).max(64),
+ slug: z.string().trim().min(1).max(64).regex(APPLICATION_SLUG_REGEX, APPLICATION_SLUG_MESSAGE),
+ description: z.string().max(256).optional(),
+ profileIds: z.array(z.string().uuid()).optional()
+ }),
+ response: {
+ 200: z.object({ application: PkiApplicationsSchema })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const application = await server.services.pkiApplication.createApplication({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ name: req.body.name,
+ slug: req.body.slug,
+ description: req.body.description,
+ profileIds: req.body.profileIds
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.CREATE_PKI_APPLICATION,
+ metadata: {
+ applicationId: application.id,
+ slug: application.slug,
+ name: application.name,
+ profileIds: req.body.profileIds
+ }
+ }
+ });
+
+ return { application };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listPkiApplications",
+ description: "List Cert Manager applications.",
+ tags: [ApiDocsTags.PkiApplications],
+ querystring: z.object({
+ search: z.string().optional(),
+ limit: z.coerce.number().int().min(1).max(100).default(20),
+ offset: z.coerce.number().int().min(0).default(0)
+ }),
+ response: {
+ 200: z.object({
+ applications: z.array(ApplicationListItemSchema),
+ total: z.number().int().nonnegative()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.pkiApplication.listApplications({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ search: req.query.search,
+ limit: req.query.limit,
+ offset: req.query.offset
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.LIST_PKI_APPLICATIONS,
+ metadata: { projectId: req.certManagerProjectId }
+ }
+ });
+
+ return result;
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:applicationId",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "getPkiApplication",
+ description: "Get a Cert Manager application by id.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: ApplicationIdParamsSchema,
+ response: { 200: z.object({ application: PkiApplicationsSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const application = await server.services.pkiApplication.getApplicationById({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.GET_PKI_APPLICATION,
+ metadata: { applicationId: application.id, slug: application.slug }
+ }
+ });
+
+ return { application };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/slug/:slug",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "getPkiApplicationBySlug",
+ description: "Get a Cert Manager application by slug.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({ slug: z.string().regex(APPLICATION_SLUG_REGEX, APPLICATION_SLUG_MESSAGE) }),
+ response: { 200: z.object({ application: PkiApplicationsSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const application = await server.services.pkiApplication.getApplicationBySlug({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ slug: req.params.slug
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.GET_PKI_APPLICATION,
+ metadata: { applicationId: application.id, slug: application.slug }
+ }
+ });
+
+ return { application };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:applicationId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "updatePkiApplication",
+ description: "Update a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: ApplicationIdParamsSchema,
+ body: z
+ .object({
+ name: z.string().trim().min(1).max(64).optional(),
+ slug: z.string().trim().min(1).max(64).regex(APPLICATION_SLUG_REGEX, APPLICATION_SLUG_MESSAGE).optional(),
+ description: z.string().max(256).nullable().optional()
+ })
+ .refine((d) => d.name !== undefined || d.slug !== undefined || d.description !== undefined, {
+ message: "At least one of name, slug, or description must be provided."
+ }),
+ response: { 200: z.object({ application: PkiApplicationsSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const application = await server.services.pkiApplication.updateApplication({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId,
+ name: req.body.name,
+ slug: req.body.slug,
+ description: req.body.description
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.UPDATE_PKI_APPLICATION,
+ metadata: { applicationId: application.id, slug: application.slug }
+ }
+ });
+
+ return { application };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:applicationId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "deletePkiApplication",
+ description: "Delete a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: ApplicationIdParamsSchema,
+ response: { 200: z.object({ application: PkiApplicationsSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const application = await server.services.pkiApplication.deleteApplication({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.DELETE_PKI_APPLICATION,
+ metadata: { applicationId: application.id, slug: application.slug }
+ }
+ });
+
+ return { application };
+ }
+ });
+
+ await registerPkiApplicationProfileRoutes(server);
+ await registerPkiApplicationMembershipRoutes(server);
+ await registerPkiApplicationEnrollmentRoutes(server);
+ await registerPkiApplicationAlertRoutes(server);
+ await registerPkiApplicationSyncRoutes(server);
+};
diff --git a/backend/src/server/routes/v1/pki-application-schemas.ts b/backend/src/server/routes/v1/pki-application-schemas.ts
new file mode 100644
index 0000000000..c26fdc3636
--- /dev/null
+++ b/backend/src/server/routes/v1/pki-application-schemas.ts
@@ -0,0 +1,21 @@
+import { z } from "zod";
+
+export const ApplicationIdParamsSchema = z.object({ applicationId: z.string().uuid() });
+
+export const ApplicationProfileParamsSchema = z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid()
+});
+
+export const ApplicationProfileSchema = z.object({
+ applicationId: z.string().uuid(),
+ profileId: z.string().uuid(),
+ profileSlug: z.string(),
+ profileDescription: z.string().nullable().optional(),
+ estConfigId: z.string().uuid().nullable().optional(),
+ apiConfigId: z.string().uuid().nullable().optional(),
+ acmeConfigId: z.string().uuid().nullable().optional(),
+ scepConfigId: z.string().uuid().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
diff --git a/backend/src/server/routes/v1/pki-application-sync-router.ts b/backend/src/server/routes/v1/pki-application-sync-router.ts
new file mode 100644
index 0000000000..ab211d19b8
--- /dev/null
+++ b/backend/src/server/routes/v1/pki-application-sync-router.ts
@@ -0,0 +1,146 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags } 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 { ApplicationIdParamsSchema } from "./pki-application-schemas";
+import { PkiSyncSchema } from "./pki-sync-routers/pki-sync-router";
+
+export const registerPkiApplicationSyncRoutes = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/:applicationId/pki-syncs",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listPkiApplicationSyncs",
+ description: "List PKI syncs for a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: ApplicationIdParamsSchema,
+ querystring: z.object({
+ certificateId: z.string().uuid().optional()
+ }),
+ response: {
+ 200: z.object({ syncs: z.array(PkiSyncSchema) })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const syncs = await server.services.pkiSync.listPkiSyncsByProjectId(
+ {
+ projectId: req.certManagerProjectId,
+ certificateId: req.query.certificateId,
+ applicationId: req.params.applicationId
+ },
+ req.permission
+ );
+
+ return { syncs };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:applicationId/pki-syncs/:syncId",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "getPkiApplicationSync",
+ description: "Get a PKI sync by id for a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({
+ applicationId: z.string().uuid(),
+ syncId: z.string().uuid()
+ }),
+ response: { 200: z.object({ sync: PkiSyncSchema }) }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const sync = await server.services.pkiSync.findPkiSyncById(
+ {
+ id: req.params.syncId,
+ projectId: req.certManagerProjectId,
+ applicationId: req.params.applicationId
+ },
+ req.permission
+ );
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.certManagerProjectId,
+ event: {
+ type: EventType.GET_PKI_SYNC,
+ metadata: {
+ syncId: sync.id,
+ destination: sync.destination,
+ applicationId: req.params.applicationId
+ }
+ }
+ });
+
+ return { sync };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:applicationId/pki-syncs/:syncId",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "deletePkiApplicationSync",
+ description: "Delete a PKI sync from a Cert Manager application.",
+ tags: [ApiDocsTags.PkiApplications],
+ params: z.object({
+ applicationId: z.string().uuid(),
+ syncId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ sync: z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ projectId: z.string().uuid(),
+ destination: z.string()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const sync = await server.services.pkiSync.deletePkiSync(
+ {
+ id: req.params.syncId,
+ applicationId: req.params.applicationId
+ },
+ req.permission
+ );
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: sync.projectId,
+ event: {
+ type: EventType.DELETE_PKI_SYNC,
+ metadata: {
+ pkiSyncId: sync.id,
+ name: sync.name,
+ destination: sync.destination,
+ applicationId: req.params.applicationId
+ }
+ }
+ });
+
+ return {
+ sync: {
+ id: sync.id,
+ name: sync.name,
+ projectId: sync.projectId,
+ destination: sync.destination
+ }
+ };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/pki-collection-router.ts b/backend/src/server/routes/v1/pki-collection-router.ts
index f78350d186..4e0773d27b 100644
--- a/backend/src/server/routes/v1/pki-collection-router.ts
+++ b/backend/src/server/routes/v1/pki-collection-router.ts
@@ -18,10 +18,10 @@ export const registerPkiCollectionRouter = async (server: FastifyZodProvider) =>
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
schema: {
hide: false,
+ operationId: "createPkiCollection",
tags: [ApiDocsTags.PkiCertificateCollections],
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)
}),
@@ -35,6 +35,7 @@ export const registerPkiCollectionRouter = async (server: FastifyZodProvider) =>
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.body
});
diff --git a/backend/src/server/routes/v1/pki-subscriber-router.ts b/backend/src/server/routes/v1/pki-subscriber-router.ts
index 68b32672aa..966be49cc4 100644
--- a/backend/src/server/routes/v1/pki-subscriber-router.ts
+++ b/backend/src/server/routes/v1/pki-subscriber-router.ts
@@ -32,9 +32,6 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
params: z.object({
subscriberName: z.string().describe(PKI_SUBSCRIBERS.GET.subscriberName)
}),
- querystring: z.object({
- projectId: z.string().describe(PKI_SUBSCRIBERS.GET.projectId)
- }),
response: {
200: sanitizedPkiSubscriber
}
@@ -43,7 +40,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
handler: async (req) => {
const subscriber = await server.services.pkiSubscriber.getSubscriber({
subscriberName: req.params.subscriberName,
- projectId: req.query.projectId,
+ projectId: req.certManagerProjectId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -78,7 +75,6 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
tags: [ApiDocsTags.PkiSubscribers],
description: "Create PKI Subscriber",
body: z.object({
- projectId: z.string().trim().describe(PKI_SUBSCRIBERS.CREATE.projectId),
caId: z
.string()
.trim()
@@ -206,6 +202,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
handler: async (req) => {
const subscriber = await server.services.pkiSubscriber.createSubscriber({
...req.body,
+ projectId: req.certManagerProjectId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -250,7 +247,6 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
subscriberName: z.string().trim().describe(PKI_SUBSCRIBERS.UPDATE.subscriberName)
}),
body: z.object({
- projectId: z.string().trim().describe(PKI_SUBSCRIBERS.UPDATE.projectId),
caId: z
.string()
.trim()
@@ -374,6 +370,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
handler: async (req) => {
const subscriber = await server.services.pkiSubscriber.updateSubscriber({
subscriberName: req.params.subscriberName,
+ projectId: req.certManagerProjectId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -416,9 +413,6 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
params: z.object({
subscriberName: z.string().describe(PKI_SUBSCRIBERS.DELETE.subscriberName)
}),
- body: z.object({
- projectId: z.string().trim().describe(PKI_SUBSCRIBERS.DELETE.projectId)
- }),
response: {
200: sanitizedPkiSubscriber
}
@@ -427,7 +421,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
handler: async (req) => {
const subscriber = await server.services.pkiSubscriber.deleteSubscriber({
subscriberName: req.params.subscriberName,
- projectId: req.body.projectId,
+ projectId: req.certManagerProjectId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -465,9 +459,6 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
params: z.object({
subscriberName: z.string().describe(PKI_SUBSCRIBERS.ISSUE_CERT.subscriberName)
}),
- body: z.object({
- projectId: z.string().trim().describe(PKI_SUBSCRIBERS.ISSUE_CERT.projectId)
- }),
response: {
200: z.object({
message: z.string().trim()
@@ -477,7 +468,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
handler: async (req) => {
const subscriber = await server.services.pkiSubscriber.orderSubscriberCert({
subscriberName: req.params.subscriberName,
- projectId: req.body.projectId,
+ projectId: req.certManagerProjectId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -528,9 +519,6 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
params: z.object({
subscriberName: z.string().describe(PKI_SUBSCRIBERS.ISSUE_CERT.subscriberName)
}),
- body: z.object({
- projectId: z.string().trim().describe(PKI_SUBSCRIBERS.ISSUE_CERT.projectId)
- }),
response: {
200: z.object({
certificate: z.string().trim().describe(PKI_SUBSCRIBERS.ISSUE_CERT.certificate),
@@ -545,7 +533,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
const { certificate, certificateChain, issuingCaCertificate, privateKey, serialNumber, subscriber } =
await server.services.pkiSubscriber.issueSubscriberCert({
subscriberName: req.params.subscriberName,
- projectId: req.body.projectId,
+ projectId: req.certManagerProjectId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -602,7 +590,6 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
subscriberName: z.string().describe(PKI_SUBSCRIBERS.SIGN_CERT.subscriberName)
}),
body: z.object({
- projectId: z.string().trim().describe(PKI_SUBSCRIBERS.SIGN_CERT.projectId),
csr: z.string().trim().min(1).max(3000).describe(PKI_SUBSCRIBERS.SIGN_CERT.csr)
}),
response: {
@@ -618,7 +605,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
const { certificate, certificateChain, issuingCaCertificate, serialNumber, subscriber } =
await server.services.pkiSubscriber.signSubscriberCert({
subscriberName: req.params.subscriberName,
- projectId: req.body.projectId,
+ projectId: req.certManagerProjectId,
csr: req.body.csr,
actor: req.permission.type,
actorId: req.permission.id,
@@ -673,9 +660,6 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
params: z.object({
subscriberName: z.string().describe(PKI_SUBSCRIBERS.GET_LATEST_CERT_BUNDLE.subscriberName)
}),
- querystring: z.object({
- projectId: z.string().trim().describe(PKI_SUBSCRIBERS.GET_LATEST_CERT_BUNDLE.projectId)
- }),
response: {
200: z.object({
certificate: z.string().trim().describe(PKI_SUBSCRIBERS.GET_LATEST_CERT_BUNDLE.certificate),
@@ -698,7 +682,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- ...req.query
+ projectId: req.certManagerProjectId
});
await server.services.auditLog.createAuditLog({
@@ -741,7 +725,6 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
subscriberName: z.string().describe(PKI_SUBSCRIBERS.GET.subscriberName)
}),
querystring: z.object({
- projectId: z.string().trim().describe(PKI_SUBSCRIBERS.LIST_CERTS.projectId),
offset: z.coerce.number().min(0).max(100).default(0).describe(PKI_SUBSCRIBERS.LIST_CERTS.offset),
limit: z.coerce.number().min(1).max(100).default(25).describe(PKI_SUBSCRIBERS.LIST_CERTS.limit)
}),
@@ -760,18 +743,19 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.query
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.query.projectId,
+ projectId: req.certManagerProjectId,
event: {
type: EventType.LIST_PKI_SUBSCRIBER_CERTS,
metadata: {
subscriberId: req.params.subscriberName,
name: req.params.subscriberName,
- projectId: req.query.projectId
+ projectId: req.certManagerProjectId
}
}
});
diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts
index 3d4de46b85..bc62b673ab 100644
--- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts
+++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts
@@ -21,7 +21,8 @@ export const registerSyncPkiEndpoints = ({
server: FastifyZodProvider;
createSchema: z.ZodType<{
name: string;
- projectId: string;
+ projectId?: string;
+ applicationId?: string;
connectionId: string;
destinationConfig: Record<string, unknown>;
syncOptions?: Record<string, unknown>;
@@ -62,18 +63,13 @@ export const registerSyncPkiEndpoints = ({
...(enableOperationId ? { operationId: `list${destinationNameForOpId}PkiSyncs` } : {}),
tags: [ApiDocsTags.PkiSyncs],
description: `List the ${destinationName} PKI Syncs for the specified project.`,
- querystring: z.object({
- projectId: z.string().trim().min(1, "Project ID required")
- }),
response: {
200: z.object({ pkiSyncs: responseSchema.array() })
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const {
- query: { projectId }
- } = req;
+ const projectId = req.certManagerProjectId;
const pkiSyncs = await server.services.pkiSync.listPkiSyncsByProjectId({ projectId }, req.permission);
@@ -150,7 +146,10 @@ export const registerSyncPkiEndpoints = ({
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const pkiSync = await server.services.pkiSync.createPkiSync({ ...req.body, destination }, req.permission);
+ const pkiSync = await server.services.pkiSync.createPkiSync(
+ { ...req.body, projectId: req.body.projectId ?? req.certManagerProjectId, destination },
+ req.permission
+ );
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts
index 95d6329cb0..0e22b5b167 100644
--- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts
+++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts
@@ -10,7 +10,7 @@ import { CertificateSyncStatus } from "@app/services/certificate-sync/certificat
import { SyncMetadataSchema } from "@app/services/certificate-sync/certificate-sync-schemas";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
-const PkiSyncSchema = z.object({
+export const PkiSyncSchema = z.object({
id: z.string().uuid(),
name: z.string(),
description: z.string().nullable().optional(),
@@ -19,6 +19,7 @@ const PkiSyncSchema = z.object({
destinationConfig: z.record(z.unknown()),
syncOptions: z.record(z.unknown()),
projectId: z.string().uuid(),
+ applicationId: z.string().uuid().nullable().optional(),
subscriberId: z.string().uuid().nullable().optional(),
connectionId: z.string().uuid(),
createdAt: z.date(),
@@ -138,7 +139,6 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider, enableOp
tags: [ApiDocsTags.PkiSyncs],
description: "List all the PKI Syncs for the specified project.",
querystring: z.object({
- projectId: z.string().trim().min(1),
certificateId: z.string().uuid().optional()
}),
response: {
@@ -148,9 +148,10 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider, enableOp
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
const {
- query: { projectId, certificateId },
+ query: { certificateId },
permission
} = req;
+ const projectId = req.certManagerProjectId;
const pkiSyncs = await server.services.pkiSync.listPkiSyncsByProjectId({ projectId, certificateId }, permission);
diff --git a/backend/src/server/routes/v1/project-router.ts b/backend/src/server/routes/v1/project-router.ts
index 26f505579d..8e89d59ea6 100644
--- a/backend/src/server/routes/v1/project-router.ts
+++ b/backend/src/server/routes/v1/project-router.ts
@@ -25,6 +25,7 @@ import { loginMappingSchema, sanitizedSshHost } from "@app/ee/services/ssh-host/
import { LoginMappingSource } from "@app/ee/services/ssh-host/ssh-host-types";
import { sanitizedSshHostGroup } from "@app/ee/services/ssh-host-group/ssh-host-group-schema";
import { ApiDocsTags, PROJECTS } from "@app/lib/api-docs";
+import { BadRequestError } from "@app/lib/errors";
import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";
import { re2Validator } from "@app/lib/zod";
import { projectCreationLimit, readLimit, requestAccessLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -173,6 +174,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
+ if (req.body.type === ProjectType.CertificateManager) {
+ throw new BadRequestError({
+ message:
+ "Cert Manager is a single-instance product per organization and cannot be created via this endpoint. The Cert Manager project is auto-provisioned at organization creation."
+ });
+ }
+
const project = await server.services.project.createProject({
actorId: req.permission.id,
actor: req.permission.type,
@@ -1323,6 +1331,11 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
notAfterTo: z.coerce.date().optional().describe(PROJECTS.SEARCH_CERTIFICATES.notAfterTo),
notBeforeFrom: z.coerce.date().optional().describe(PROJECTS.SEARCH_CERTIFICATES.notBeforeFrom),
notBeforeTo: z.coerce.date().optional().describe(PROJECTS.SEARCH_CERTIFICATES.notBeforeTo),
+ applicationId: z
+ .string()
+ .uuid()
+ .optional()
+ .describe("Filter to certificates issued through a specific Cert Manager Application."),
sortBy: z
.enum(["notAfter", "notBefore", "createdAt", "commonName", "keyAlgorithm", "status"])
.optional()
diff --git a/backend/src/server/routes/v2/certificate-authority-router.ts b/backend/src/server/routes/v2/certificate-authority-router.ts
index 51fe7a2095..e2e605ffe4 100644
--- a/backend/src/server/routes/v2/certificate-authority-router.ts
+++ b/backend/src/server/routes/v2/certificate-authority-router.ts
@@ -37,9 +37,6 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {
operationId: "listCertificateAuthoritiesV2",
tags: [ApiDocsTags.PkiCertificateAuthorities],
description: "Get Certificate Authorities",
- querystring: z.object({
- projectId: z.string()
- }),
response: {
200: z.object({
certificateAuthorities: CertificateAuthoritySchema.array()
@@ -47,9 +44,10 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req) => {
+ const projectId = req.certManagerProjectId;
const internalCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.INTERNAL
},
req.permission
@@ -57,7 +55,7 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {
const acmeCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.ACME
},
req.permission
@@ -65,7 +63,7 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {
const azureAdCsCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.AZURE_AD_CS
},
req.permission
@@ -73,7 +71,7 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {
const awsPcaCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.AWS_PCA
},
req.permission
@@ -81,7 +79,7 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {
const digicertCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.DIGICERT
},
req.permission
@@ -89,7 +87,7 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {
const awsAcmPublicCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.AWS_ACM_PUBLIC_CA
},
req.permission
@@ -97,7 +95,7 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {
const venafiTppCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId(
{
- projectId: req.query.projectId,
+ projectId,
type: CaType.VENAFI_TPP
},
req.permission
@@ -105,7 +103,7 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.query.projectId,
+ projectId,
event: {
type: EventType.GET_CAS,
metadata: {
diff --git a/backend/src/server/routes/v2/index.ts b/backend/src/server/routes/v2/index.ts
index 45e7632aa7..24ca8c2b50 100644
--- a/backend/src/server/routes/v2/index.ts
+++ b/backend/src/server/routes/v2/index.ts
@@ -1,3 +1,5 @@
+import { injectCertManagerProjectId } from "@app/server/plugins/inject-cert-manager-project-id";
+
import { registerCaRouter } from "./certificate-authority-router";
import { registerDeprecatedGroupProjectRouter } from "./deprecated-group-project-router";
import { registerDeprecatedIdentityProjectRouter } from "./deprecated-identity-project-router";
@@ -24,6 +26,7 @@ export const registerV2Routes = async (server: FastifyZodProvider) => {
await server.register(
async (pkiRouter) => {
+ await pkiRouter.register(injectCertManagerProjectId);
await pkiRouter.register(registerCaRouter, { prefix: "/ca" });
await pkiRouter.register(registerPkiTemplatesRouter, { prefix: "/certificate-templates" });
await pkiRouter.register(registerPkiAlertRouter, { prefix: "/alerts" });
diff --git a/backend/src/server/routes/v2/pki-alert-router.ts b/backend/src/server/routes/v2/pki-alert-router.ts
index 1b10ad695d..6c839dd7d8 100644
--- a/backend/src/server/routes/v2/pki-alert-router.ts
+++ b/backend/src/server/routes/v2/pki-alert-router.ts
@@ -29,7 +29,11 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
description: "Create a new PKI alert",
tags: [ApiDocsTags.PkiAlerting],
body: BasePkiAlertV2Schema.extend({
- projectId: z.string().uuid().describe("Project ID")
+ applicationId: z
+ .string()
+ .uuid()
+ .optional()
+ .describe("Optional Cert Manager Application this alert is scoped to")
}),
response: {
200: z.object({
@@ -65,12 +69,13 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.body
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.body.projectId,
+ projectId: req.certManagerProjectId,
event: {
type: EventType.CREATE_PKI_ALERT,
metadata: {
@@ -98,7 +103,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
description: "List PKI alerts for a project",
tags: [ApiDocsTags.PkiAlerting],
querystring: z.object({
- projectId: z.string().uuid(),
+ applicationId: z.string().uuid().optional(),
search: z.string().optional(),
eventType: z.nativeEnum(PkiAlertEventType).optional(),
enabled: z.coerce.boolean().optional(),
@@ -148,6 +153,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.query
});
@@ -421,7 +427,6 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
description: "Preview certificates that would match the given filter rules",
tags: [ApiDocsTags.PkiAlerting],
body: z.object({
- projectId: z.string().uuid().describe("Project ID"),
filters: z.array(PkiFilterRuleSchema),
alertBefore: z
.string()
@@ -456,6 +461,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.body
});
@@ -475,7 +481,6 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
description: "Test a webhook configuration by sending a test payload",
tags: [ApiDocsTags.PkiAlerting],
body: z.object({
- projectId: z.string().uuid().describe("Project ID for permission check"),
url: z
.string()
.url()
@@ -492,7 +497,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {
},
handler: async (req) => {
const result = await server.services.pkiAlertV2.testWebhookConfig({
- projectId: req.body.projectId,
+ projectId: req.certManagerProjectId,
url: req.body.url,
signingSecret: req.body.signingSecret,
actor: req.permission.type,
diff --git a/backend/src/server/routes/v2/pki-templates-router.ts b/backend/src/server/routes/v2/pki-templates-router.ts
index c3e672f3a2..e1e0eb4654 100644
--- a/backend/src/server/routes/v2/pki-templates-router.ts
+++ b/backend/src/server/routes/v2/pki-templates-router.ts
@@ -28,7 +28,6 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
body: z.object({
name: slugSchema(),
caName: slugSchema({ field: "caName" }),
- projectId: z.string(),
commonName: validateTemplateRegexField,
subjectAlternativeName: validateTemplateRegexField,
ttl: z.string().refine((val) => ms(val) > 0, "TTL must be a positive number"),
@@ -52,6 +51,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.body
});
@@ -75,7 +75,6 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
body: z.object({
name: slugSchema().optional(),
caName: slugSchema(),
- projectId: z.string(),
commonName: validateTemplateRegexField.optional(),
subjectAlternativeName: validateTemplateRegexField.optional(),
ttl: z
@@ -103,6 +102,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
templateName: req.params.templateName,
+ projectId: req.certManagerProjectId,
...req.body
});
@@ -123,9 +123,6 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
params: z.object({
templateName: z.string().min(1)
}),
- body: z.object({
- projectId: z.string()
- }),
response: {
200: z.object({
certificateTemplate: CertificateTemplatesSchema
@@ -140,7 +137,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
templateName: req.params.templateName,
- projectId: req.body.projectId
+ projectId: req.certManagerProjectId
});
return { certificateTemplate };
@@ -160,9 +157,6 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
params: z.object({
templateName: slugSchema()
}),
- querystring: z.object({
- projectId: z.string()
- }),
response: {
200: z.object({
certificateTemplate: CertificateTemplatesSchema.extend({
@@ -179,7 +173,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
templateName: req.params.templateName,
- projectId: req.query.projectId
+ projectId: req.certManagerProjectId
});
return { certificateTemplate };
@@ -197,7 +191,6 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
operationId: "listPkiTemplates",
tags: [ApiDocsTags.PkiCertificateTemplates],
querystring: z.object({
- projectId: z.string(),
limit: z.coerce.number().default(100),
offset: z.coerce.number().default(0)
}),
@@ -217,6 +210,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
+ projectId: req.certManagerProjectId,
...req.query
});
@@ -238,7 +232,6 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
templateName: slugSchema()
}),
body: z.object({
- projectId: z.string(),
commonName: validateTemplateRegexField,
ttl: z.string().refine((val) => ms(val) > 0, "TTL must be a positive number"),
keyUsages: z.nativeEnum(CertKeyUsage).array().optional(),
@@ -265,6 +258,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
templateName: req.params.templateName,
+ projectId: req.certManagerProjectId,
...req.body
});
@@ -286,7 +280,6 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
templateName: slugSchema()
}),
body: z.object({
- projectId: z.string(),
ttl: z.string().refine((val) => ms(val) > 0, "TTL must be a positive number"),
csr: z.string().trim().min(1).max(4096)
}),
@@ -307,6 +300,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
templateName: req.params.templateName,
+ projectId: req.certManagerProjectId,
...req.body
});
diff --git a/backend/src/services/approval-policy/approval-policy-dal.ts b/backend/src/services/approval-policy/approval-policy-dal.ts
index 2087c15590..d85331c029 100644
--- a/backend/src/services/approval-policy/approval-policy-dal.ts
+++ b/backend/src/services/approval-policy/approval-policy-dal.ts
@@ -61,13 +61,25 @@ export const approvalPolicyDALFactory = (db: TDbClient) => {
}
};
- const findByProjectId = async (policyType: ApprovalPolicyType, projectId: string) => {
+ const findByProjectId = async (
+ policyType: ApprovalPolicyType,
+ projectId: string,
+ options?: { applicationId?: string | null }
+ ) => {
try {
const dbInstance = db.replicaNode();
- const policies = await dbInstance(TableName.ApprovalPolicies)
+ const baseQuery = dbInstance(TableName.ApprovalPolicies)
.where({ type: policyType, projectId })
.orderBy("id", "asc");
+ if (options?.applicationId === null) {
+ void baseQuery.whereNull("applicationId");
+ } else if (typeof options?.applicationId === "string") {
+ void baseQuery.where({ applicationId: options.applicationId });
+ }
+
+ const policies = await baseQuery;
+
if (!policies.length) {
return [];
}
diff --git a/backend/src/services/approval-policy/approval-policy-service.ts b/backend/src/services/approval-policy/approval-policy-service.ts
index 6758ddaee7..9a9e436aad 100644
--- a/backend/src/services/approval-policy/approval-policy-service.ts
+++ b/backend/src/services/approval-policy/approval-policy-service.ts
@@ -1,6 +1,12 @@
import { ForbiddenError } from "@casl/ability";
-import { ActionProjectType, ProjectMembershipRole, TApprovalPolicies, TApprovalRequests } from "@app/db/schemas";
+import {
+ ActionProjectType,
+ ProjectMembershipRole,
+ ResourceType,
+ TApprovalPolicies,
+ TApprovalRequests
+} from "@app/db/schemas";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
@@ -9,6 +15,10 @@ import {
ProjectPermissionCodeSigningActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
+import {
+ ResourcePermissionApprovalPolicyActions,
+ ResourcePermissionSub
+} from "@app/ee/services/permission/resource-permission";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
import { OrgServiceActor } from "@app/lib/types";
@@ -62,7 +72,10 @@ type TApprovalPolicyServiceFactoryDep = {
approvalRequestGrantsDAL: TApprovalRequestGrantsDALFactory;
userGroupMembershipDAL: TUserGroupMembershipDALFactory;
notificationService: TNotificationServiceFactory;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
+ permissionService: Pick<
+ TPermissionServiceFactory,
+ "getProjectPermission" | "getOrgPermission" | "getResourcePermission"
+ >;
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findProjectMembershipsByUserIds">;
certificateApprovalService: TCertificateApprovalService;
certificateRequestDAL: Pick<TCertificateRequestDALFactory, "updateById" | "findById">;
@@ -88,6 +101,39 @@ export const approvalPolicyServiceFactory = ({
const $notifyApprovers = (step: ApprovalPolicyStep, request: TApprovalRequests) =>
notifyApproversForStep(step, request, { userGroupMembershipDAL, notificationService });
+ const $assertCanManagePolicy = async (
+ projectId: string,
+ applicationId: string | null | undefined,
+ actor: OrgServiceActor,
+ resourceAction: ResourcePermissionApprovalPolicyActions
+ ) => {
+ const { hasRole } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorAuthMethod: actor.authMethod,
+ actorId: actor.id,
+ actorOrgId: actor.orgId,
+ projectId,
+ actionProjectType: ActionProjectType.Any
+ });
+
+ if (hasRole(ProjectMembershipRole.Admin)) return;
+
+ if (!applicationId) {
+ throw new ForbiddenRequestError({ message: "User has insufficient privileges" });
+ }
+
+ const { permission } = await permissionService.getResourcePermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId,
+ resourceType: ResourceType.CertificateApplication,
+ resourceId: applicationId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(resourceAction, ResourcePermissionSub.ApprovalPolicies);
+ };
+
const $verifyProjectUserMembership = async (userIds: string[], orgId: string, projectId: string) => {
const uniqueUserIds = [...new Set(userIds)];
if (uniqueUserIds.length === 0) return;
@@ -106,23 +152,20 @@ export const approvalPolicyServiceFactory = ({
const create = async (
policyType: ApprovalPolicyType,
- { projectId, name, maxRequestTtl, conditions, constraints, steps, bypassForMachineIdentities }: TCreatePolicyDTO,
+ {
+ projectId,
+ name,
+ maxRequestTtl,
+ conditions,
+ constraints,
+ steps,
+ bypassForMachineIdentities,
+ applicationId
+ }: TCreatePolicyDTO,
actor: OrgServiceActor
) => {
- const { hasRole } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId,
- actionProjectType: ActionProjectType.Any
- });
+ await $assertCanManagePolicy(projectId, applicationId, actor, ResourcePermissionApprovalPolicyActions.Create);
- if (!hasRole(ProjectMembershipRole.Admin)) {
- throw new ForbiddenRequestError({ message: "User has insufficient privileges" });
- }
-
- // Verify all users are part of project
const approverUserIds = steps
.flatMap((step) => step.approvers ?? [])
.filter((approver) => approver.type === ApproverType.User)
@@ -139,7 +182,8 @@ export const approvalPolicyServiceFactory = ({
conditions: { version: 1, conditions },
constraints: { version: 1, constraints },
type: policyType,
- bypassForMachineIdentities: bypassForMachineIdentities ?? false
+ bypassForMachineIdentities: bypassForMachineIdentities ?? false,
+ applicationId: applicationId ?? null
},
tx
);
@@ -183,7 +227,12 @@ export const approvalPolicyServiceFactory = ({
};
};
- const list = async (policyType: ApprovalPolicyType, projectId: string, actor: OrgServiceActor) => {
+ const list = async (
+ policyType: ApprovalPolicyType,
+ projectId: string,
+ actor: OrgServiceActor,
+ options?: { applicationId?: string | null }
+ ) => {
const { hasRole } = await permissionService.getProjectPermission({
actor: actor.type,
actorAuthMethod: actor.authMethod,
@@ -197,7 +246,9 @@ export const approvalPolicyServiceFactory = ({
throw new ForbiddenRequestError({ message: "User has insufficient privileges" });
}
- const policies = await approvalPolicyDAL.findByProjectId(policyType, projectId);
+ const policies = await approvalPolicyDAL.findByProjectId(policyType, projectId, {
+ applicationId: options?.applicationId
+ });
return { policies };
};
@@ -208,18 +259,12 @@ export const approvalPolicyServiceFactory = ({
throw new ForbiddenRequestError({ message: "Policy not found" });
}
- const { hasRole } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: policy.projectId,
- actionProjectType: ActionProjectType.Any
- });
-
- if (!hasRole(ProjectMembershipRole.Admin)) {
- throw new ForbiddenRequestError({ message: "User has insufficient privileges" });
- }
+ await $assertCanManagePolicy(
+ policy.projectId,
+ policy.applicationId,
+ actor,
+ ResourcePermissionApprovalPolicyActions.Read
+ );
const steps = await approvalPolicyDAL.findStepsByPolicyId(policyId);
@@ -228,7 +273,15 @@ export const approvalPolicyServiceFactory = ({
const updateById = async (
policyId: string,
- { name, maxRequestTtl, conditions, constraints, steps, bypassForMachineIdentities }: TUpdatePolicyDTO,
+ {
+ name,
+ maxRequestTtl,
+ conditions,
+ constraints,
+ steps,
+ bypassForMachineIdentities,
+ applicationId
+ }: TUpdatePolicyDTO,
actor: OrgServiceActor
) => {
const policy = await approvalPolicyDAL.findById(policyId);
@@ -236,17 +289,15 @@ export const approvalPolicyServiceFactory = ({
throw new ForbiddenRequestError({ message: "Policy not found" });
}
- const { hasRole } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: policy.projectId,
- actionProjectType: ActionProjectType.Any
- });
-
- if (!hasRole(ProjectMembershipRole.Admin)) {
- throw new ForbiddenRequestError({ message: "User has insufficient privileges" });
+ const targetAppId = applicationId !== undefined ? applicationId : policy.applicationId;
+ await $assertCanManagePolicy(
+ policy.projectId,
+ policy.applicationId,
+ actor,
+ ResourcePermissionApprovalPolicyActions.Edit
+ );
+ if (applicationId !== undefined && applicationId !== policy.applicationId) {
+ await $assertCanManagePolicy(policy.projectId, targetAppId, actor, ResourcePermissionApprovalPolicyActions.Edit);
}
if (steps !== undefined) {
@@ -281,6 +332,10 @@ export const approvalPolicyServiceFactory = ({
updateDoc.bypassForMachineIdentities = bypassForMachineIdentities;
}
+ if (applicationId !== undefined) {
+ updateDoc.applicationId = applicationId;
+ }
+
const updated = await approvalPolicyDAL.updateById(policyId, updateDoc, tx);
if (steps !== undefined) {
@@ -332,18 +387,12 @@ export const approvalPolicyServiceFactory = ({
throw new ForbiddenRequestError({ message: "Policy not found" });
}
- const { hasRole } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorAuthMethod: actor.authMethod,
- actorId: actor.id,
- actorOrgId: actor.orgId,
- projectId: policy.projectId,
- actionProjectType: ActionProjectType.Any
- });
-
- if (!hasRole(ProjectMembershipRole.Admin)) {
- throw new ForbiddenRequestError({ message: "User has insufficient privileges" });
- }
+ await $assertCanManagePolicy(
+ policy.projectId,
+ policy.applicationId,
+ actor,
+ ResourcePermissionApprovalPolicyActions.Delete
+ );
await approvalPolicyDAL.deleteById(policyId);
@@ -379,7 +428,8 @@ export const approvalPolicyServiceFactory = ({
requesterUserId,
machineIdentityId,
requesterName,
- requesterEmail
+ requesterEmail,
+ applicationId: policy.applicationId ?? null
},
{
approvalRequestDAL,
@@ -743,7 +793,12 @@ export const approvalPolicyServiceFactory = ({
return { request: { ...finalRequest, steps: finalSteps } };
};
- const listRequests = async (policyType: ApprovalPolicyType, projectId: string, actor: OrgServiceActor) => {
+ const listRequests = async (
+ policyType: ApprovalPolicyType,
+ projectId: string,
+ actor: OrgServiceActor,
+ options?: { applicationId?: string | null }
+ ) => {
const { permission } = await permissionService.getProjectPermission({
actor: actor.type,
actorAuthMethod: actor.authMethod,
@@ -758,7 +813,9 @@ export const approvalPolicyServiceFactory = ({
ProjectPermissionSub.ApprovalRequests
);
- const requests = await approvalRequestDAL.findByProjectId(policyType, projectId);
+ const requests = await approvalRequestDAL.findByProjectId(policyType, projectId, {
+ applicationId: options?.applicationId
+ });
// If user has read permission, return all requests
if (hasReadPermission) {
@@ -899,11 +956,36 @@ export const approvalPolicyServiceFactory = ({
actionProjectType: ActionProjectType.Any
});
- ForbiddenError.from(permission).throwUnlessCan(
+ const allowedAtProject = permission.can(
ProjectPermissionApprovalRequestGrantActions.Revoke,
ProjectPermissionSub.ApprovalRequestGrants
);
+ if (!allowedAtProject) {
+ const request = grant.requestId ? await approvalRequestDAL.findById(grant.requestId) : null;
+ const requestApplicationId = (request as { applicationId?: string | null } | null)?.applicationId ?? null;
+ if (requestApplicationId) {
+ const { permission: resourcePerm } = await permissionService.getResourcePermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId: grant.projectId,
+ resourceType: ResourceType.CertificateApplication,
+ resourceId: requestApplicationId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId
+ });
+ ForbiddenError.from(resourcePerm).throwUnlessCan(
+ ProjectPermissionApprovalRequestGrantActions.Revoke,
+ ResourcePermissionSub.ApprovalRequestGrants
+ );
+ } else {
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionApprovalRequestGrantActions.Revoke,
+ ProjectPermissionSub.ApprovalRequestGrants
+ );
+ }
+ }
+
if (grant.status !== ApprovalRequestGrantStatus.Active) {
throw new BadRequestError({ message: "Grant is not active" });
}
diff --git a/backend/src/services/approval-policy/approval-policy-types.ts b/backend/src/services/approval-policy/approval-policy-types.ts
index 871592c20e..6d91e2eea0 100644
--- a/backend/src/services/approval-policy/approval-policy-types.ts
+++ b/backend/src/services/approval-policy/approval-policy-types.ts
@@ -65,6 +65,7 @@ export interface TCreatePolicyDTO {
constraints: TApprovalPolicy["constraints"]["constraints"];
steps: ApprovalPolicyStep[];
bypassForMachineIdentities?: boolean;
+ applicationId?: string | null;
}
export interface TUpdatePolicyDTO {
@@ -74,6 +75,7 @@ export interface TUpdatePolicyDTO {
constraints?: TApprovalPolicy["constraints"]["constraints"];
steps?: ApprovalPolicyStep[];
bypassForMachineIdentities?: boolean;
+ applicationId?: string | null;
}
// Request DTOs
diff --git a/backend/src/services/approval-policy/approval-request-dal.ts b/backend/src/services/approval-policy/approval-request-dal.ts
index 27522a899a..53e5d3ab9b 100644
--- a/backend/src/services/approval-policy/approval-request-dal.ts
+++ b/backend/src/services/approval-policy/approval-request-dal.ts
@@ -68,10 +68,22 @@ export const approvalRequestDALFactory = (db: TDbClient) => {
}
};
- const findByProjectId = async (policyType: ApprovalPolicyType, projectId: string) => {
+ const findByProjectId = async (
+ policyType: ApprovalPolicyType,
+ projectId: string,
+ options?: { applicationId?: string | null }
+ ) => {
try {
const dbInstance = db.replicaNode();
- const requests = await dbInstance(TableName.ApprovalRequests).where({ type: policyType, projectId });
+ const baseQuery = dbInstance(TableName.ApprovalRequests).where({ type: policyType, projectId });
+
+ if (options?.applicationId === null) {
+ void baseQuery.whereNull("applicationId");
+ } else if (typeof options?.applicationId === "string") {
+ void baseQuery.where({ applicationId: options.applicationId });
+ }
+
+ const requests = await baseQuery;
if (!requests.length) {
return [];
diff --git a/backend/src/services/approval-policy/approval-request-fns.ts b/backend/src/services/approval-policy/approval-request-fns.ts
index 464ed92249..44536d7bf4 100644
--- a/backend/src/services/approval-policy/approval-request-fns.ts
+++ b/backend/src/services/approval-policy/approval-request-fns.ts
@@ -31,6 +31,7 @@ export interface TCreateApprovalRequestWithStepsParams {
machineIdentityId?: string | null;
requesterName: string;
requesterEmail: string;
+ applicationId?: string | null;
}
export type TApprovalRequestWithSteps = TApprovalRequests & {
@@ -64,7 +65,8 @@ export const createApprovalRequestWithSteps = async (
requesterUserId,
machineIdentityId,
requesterName,
- requesterEmail
+ requesterEmail,
+ applicationId
}: TCreateApprovalRequestWithStepsParams,
dependencies: {
approvalRequestDAL: Pick<TApprovalRequestDALFactory, "create" | "transaction">;
@@ -90,7 +92,8 @@ export const createApprovalRequestWithSteps = async (
justification,
currentStep: 1,
requestData: { version: 1, requestData },
- expiresAt
+ expiresAt,
+ applicationId: applicationId ?? null
},
tx
);
diff --git a/backend/src/services/approval-policy/cert-request/cert-request-policy-factory.ts b/backend/src/services/approval-policy/cert-request/cert-request-policy-factory.ts
index c0c1ce2deb..6c36e81fea 100644
--- a/backend/src/services/approval-policy/cert-request/cert-request-policy-factory.ts
+++ b/backend/src/services/approval-policy/cert-request/cert-request-policy-factory.ts
@@ -29,18 +29,16 @@ export const certRequestPolicyFactory: TApprovalResourceFactory<
) => {
const policies = await approvalPolicyDAL.findByProjectId(policyType, projectId);
- for (const policy of policies) {
- const p = policy as TCertRequestPolicy;
- if (p.isActive) {
- for (const condition of p.conditions.conditions) {
- if (condition.profileNames.includes(inputs.profileName)) {
- return p;
- }
- }
- }
- }
+ const inputAppId = inputs.applicationId ?? null;
+ const candidates = (policies as TCertRequestPolicy[]).filter(
+ (p) => p.isActive && (p.applicationId ?? null) === inputAppId
+ );
+
+ const matched = candidates.find((p) =>
+ p.conditions.conditions.some((c) => c.profileNames.includes(inputs.profileName))
+ );
- return null;
+ return matched ?? null;
};
const canAccess: TApprovalRequestFactoryCanAccess<TCertRequestPolicyInputs> = async () => {
diff --git a/backend/src/services/approval-policy/cert-request/cert-request-policy-schemas.ts b/backend/src/services/approval-policy/cert-request/cert-request-policy-schemas.ts
index 9ab786efcc..55c19265e3 100644
--- a/backend/src/services/approval-policy/cert-request/cert-request-policy-schemas.ts
+++ b/backend/src/services/approval-policy/cert-request/cert-request-policy-schemas.ts
@@ -10,7 +10,8 @@ import {
} from "../approval-policy-schemas";
export const CertRequestPolicyInputsSchema = z.object({
- profileName: z.string()
+ profileName: z.string(),
+ applicationId: z.string().uuid().optional()
});
export const CertRequestPolicyConditionsSchema = z
@@ -73,12 +74,14 @@ export const CreateCertRequestPolicySchema = BaseCreateApprovalPolicySchema.exte
conditions: CertRequestPolicyConditionsSchema,
constraints: CertRequestPolicyConstraintsSchema.optional()
.default({})
- .transform((val) => val ?? {})
+ .transform((val) => val ?? {}),
+ applicationId: z.string().uuid().nullable().optional()
});
export const UpdateCertRequestPolicySchema = BaseUpdateApprovalPolicySchema.extend({
conditions: CertRequestPolicyConditionsSchema.optional(),
- constraints: CertRequestPolicyConstraintsSchema.optional()
+ constraints: CertRequestPolicyConstraintsSchema.optional(),
+ applicationId: z.string().uuid().nullable().optional()
});
export const CertRequestRequestSchema = BaseApprovalRequestSchema.extend({
diff --git a/backend/src/services/certificate-authority/certificate-authority-schemas.ts b/backend/src/services/certificate-authority/certificate-authority-schemas.ts
index b50fb6293b..6af52f8e25 100644
--- a/backend/src/services/certificate-authority/certificate-authority-schemas.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-schemas.ts
@@ -18,7 +18,11 @@ export const BaseCertificateAuthoritySchema = CertificateAuthoritiesSchema.pick(
export const GenericCreateCertificateAuthorityFieldsSchema = (type: CaType) =>
z.object({
name: slugSchema({ field: "name" }).describe(CertificateAuthorities.CREATE(type).name),
- projectId: z.string().uuid("Project ID must be valid").describe(CertificateAuthorities.CREATE(type).projectId),
+ projectId: z
+ .string()
+ .uuid("Project ID must be valid")
+ .optional()
+ .describe(CertificateAuthorities.CREATE(type).projectId),
status: z.nativeEnum(CaStatus).describe(CertificateAuthorities.CREATE(type).status)
});
diff --git a/backend/src/services/certificate-authority/deprecated-certificate-authority-schemas.ts b/backend/src/services/certificate-authority/deprecated-certificate-authority-schemas.ts
index 5ecc50a4b8..984e34c8d2 100644
--- a/backend/src/services/certificate-authority/deprecated-certificate-authority-schemas.ts
+++ b/backend/src/services/certificate-authority/deprecated-certificate-authority-schemas.ts
@@ -18,7 +18,11 @@ export const BaseCertificateAuthoritySchema = CertificateAuthoritiesSchema.pick(
export const GenericCreateCertificateAuthorityFieldsSchema = (type: CaType) =>
z.object({
name: slugSchema({ field: "name" }).describe(CertificateAuthorities.CREATE(type).name),
- projectId: z.string().uuid("Project ID must be valid").describe(CertificateAuthorities.CREATE(type).projectId),
+ projectId: z
+ .string()
+ .uuid("Project ID must be valid")
+ .optional()
+ .describe(CertificateAuthorities.CREATE(type).projectId),
enableDirectIssuance: z.boolean().describe(CertificateAuthorities.CREATE(type).enableDirectIssuance),
status: z.nativeEnum(CaStatus).describe(CertificateAuthorities.CREATE(type).status)
});
@@ -26,7 +30,11 @@ export const GenericCreateCertificateAuthorityFieldsSchema = (type: CaType) =>
export const GenericUpdateCertificateAuthorityFieldsSchema = (type: CaType) =>
z.object({
name: slugSchema({ field: "name" }).optional().describe(CertificateAuthorities.UPDATE(type).name),
- projectId: z.string().uuid("Project ID must be valid").describe(CertificateAuthorities.UPDATE(type).projectId),
+ projectId: z
+ .string()
+ .uuid("Project ID must be valid")
+ .optional()
+ .describe(CertificateAuthorities.UPDATE(type).projectId),
enableDirectIssuance: z.boolean().optional().describe(CertificateAuthorities.UPDATE(type).enableDirectIssuance),
status: z.nativeEnum(CaStatus).optional().describe(CertificateAuthorities.UPDATE(type).status)
});
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
index 2ec15c2b0d..5476263588 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
@@ -122,7 +122,7 @@ type TInternalCertificateAuthorityServiceFactoryDep = {
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
pkiCollectionDAL: Pick<TPkiCollectionDALFactory, "findById">;
pkiCollectionItemDAL: Pick<TPkiCollectionItemDALFactory, "create">;
- projectDAL: Pick<TProjectDALFactory, "findProjectBySlug" | "findOne" | "updateById" | "findById" | "transaction">;
+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "findById" | "transaction">;
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
caSigningConfigDAL: Pick<TCaSigningConfigDALFactory, "findByCaId" | "create" | "deleteById" | "transaction">;
@@ -278,12 +278,8 @@ export const internalCertificateAuthorityServiceFactory = ({
crlDistributionPointUrls,
...dto
}: TCreateCaDTO) => {
- let projectId: string;
+ const { projectId } = dto;
if (!dto.isInternal) {
- const project = await projectDAL.findProjectBySlug(dto.projectSlug, dto.actorOrgId);
- if (!project) throw new NotFoundError({ message: `Project with slug '${dto.projectSlug}' not found` });
- projectId = project.id;
-
const { permission } = await permissionService.getProjectPermission({
actor: dto.actor,
actorId: dto.actorId,
@@ -297,8 +293,6 @@ export const internalCertificateAuthorityServiceFactory = ({
ProjectPermissionCertificateAuthorityActions.Create,
subject(ProjectPermissionSub.CertificateAuthorities, { name: commonName })
);
- } else {
- projectId = dto.projectId;
}
if (keyAlgorithm.startsWith("SLH-DSA")) {
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
index 5ff9d794e2..cbf19ed950 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
@@ -53,7 +53,7 @@ export type TCreateCaDTO =
}
| ({
isInternal: false;
- projectSlug: string;
+ projectId: string;
type: InternalCaType;
friendlyName?: string;
name?: string;
diff --git a/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts b/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts
index 22275b8e97..6a3d4df7d9 100644
--- a/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts
+++ b/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts
@@ -16,6 +16,7 @@ import { resolveEffectiveTtl } from "@app/services/certificate-v3/certificate-v3
import { TCertificateV3ServiceFactory } from "@app/services/certificate-v3/certificate-v3-service";
import { TEstEnrollmentConfigDALFactory } from "@app/services/enrollment-config/est-enrollment-config-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TPkiApplicationProfileDALFactory } from "@app/services/pki-application/pki-application-profile-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
@@ -34,6 +35,7 @@ type TCertificateEstV3ServiceFactoryDep = {
certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs">;
estEnrollmentConfigDAL: Pick<TEstEnrollmentConfigDALFactory, "findById">;
certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "findById">;
+ pkiApplicationProfileDAL?: Pick<TPkiApplicationProfileDALFactory, "findOne">;
};
export type TCertificateEstV3ServiceFactory = ReturnType<typeof certificateEstV3ServiceFactory>;
@@ -48,8 +50,25 @@ export const certificateEstV3ServiceFactory = ({
licenseService,
certificateProfileDAL,
estEnrollmentConfigDAL,
- certificatePolicyDAL
+ certificatePolicyDAL,
+ pkiApplicationProfileDAL
}: TCertificateEstV3ServiceFactoryDep) => {
+ const resolveEstConfigId = async (
+ profile: { estConfigId?: string | null },
+ profileId: string,
+ applicationId?: string
+ ): Promise<string | null> => {
+ if (applicationId && pkiApplicationProfileDAL) {
+ const junction = await pkiApplicationProfileDAL.findOne(applicationId, profileId);
+ if (!junction) {
+ throw new NotFoundError({
+ message: `Profile '${profileId}' is not attached to application '${applicationId}'.`
+ });
+ }
+ if (junction.estConfigId) return junction.estConfigId;
+ }
+ return profile.estConfigId ?? null;
+ };
const validateEstClientCertificate = async (
estConfig: { disableBootstrapCaValidation?: boolean | null; encryptedCaChain?: Buffer | null },
projectId: string,
@@ -100,11 +119,13 @@ export const certificateEstV3ServiceFactory = ({
const simpleEnrollByProfile = async ({
csr,
profileId,
- sslClientCert
+ sslClientCert,
+ applicationId
}: {
csr: string;
profileId: string;
sslClientCert: string;
+ applicationId?: string;
}) => {
const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
if (!profile) {
@@ -115,7 +136,8 @@ export const certificateEstV3ServiceFactory = ({
throw new BadRequestError({ message: "Profile is not configured for EST enrollment" });
}
- if (!profile.estConfigId) {
+ const estConfigId = await resolveEstConfigId(profile, profileId, applicationId);
+ if (!estConfigId) {
throw new BadRequestError({ message: "EST enrollment not configured for this profile" });
}
@@ -125,7 +147,7 @@ export const certificateEstV3ServiceFactory = ({
});
}
- const estConfig = await estEnrollmentConfigDAL.findById(profile.estConfigId);
+ const estConfig = await estEnrollmentConfigDAL.findById(estConfigId);
if (!estConfig) {
throw new NotFoundError({ message: "EST configuration not found" });
}
@@ -160,7 +182,8 @@ export const certificateEstV3ServiceFactory = ({
profileId,
csr,
validity: { ttl },
- enrollmentType: EnrollmentType.EST
+ enrollmentType: EnrollmentType.EST,
+ applicationId
});
if (result.status === CertificateRequestStatus.PENDING_APPROVAL) {
@@ -180,11 +203,13 @@ export const certificateEstV3ServiceFactory = ({
const simpleReenrollByProfile = async ({
csr,
profileId,
- sslClientCert
+ sslClientCert,
+ applicationId
}: {
csr: string;
profileId: string;
sslClientCert: string;
+ applicationId?: string;
}) => {
const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
if (!profile) {
@@ -195,7 +220,8 @@ export const certificateEstV3ServiceFactory = ({
throw new BadRequestError({ message: "Profile is not configured for EST enrollment" });
}
- if (!profile.estConfigId) {
+ const estConfigId = await resolveEstConfigId(profile, profileId, applicationId);
+ if (!estConfigId) {
throw new BadRequestError({ message: "EST enrollment not configured for this profile" });
}
@@ -205,7 +231,7 @@ export const certificateEstV3ServiceFactory = ({
});
}
- const estConfig = await estEnrollmentConfigDAL.findById(profile.estConfigId);
+ const estConfig = await estEnrollmentConfigDAL.findById(estConfigId);
if (!estConfig) {
throw new NotFoundError({ message: "EST configuration not found" });
}
@@ -306,7 +332,8 @@ export const certificateEstV3ServiceFactory = ({
profileId,
csr,
validity: { ttl },
- enrollmentType: EnrollmentType.EST
+ enrollmentType: EnrollmentType.EST,
+ applicationId
});
if (result.status === CertificateRequestStatus.PENDING_APPROVAL) {
@@ -323,7 +350,7 @@ export const certificateEstV3ServiceFactory = ({
return convertRawCertsToPkcs7([certObj.rawData]);
};
- const getCaCertsByProfile = async ({ profileId }: { profileId: string }) => {
+ const getCaCertsByProfile = async ({ profileId, applicationId }: { profileId: string; applicationId?: string }) => {
const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
if (!profile) {
throw new NotFoundError({ message: "Certificate profile not found" });
@@ -333,7 +360,8 @@ export const certificateEstV3ServiceFactory = ({
throw new BadRequestError({ message: "Profile is not configured for EST enrollment" });
}
- if (!profile.estConfigId) {
+ const estConfigId = await resolveEstConfigId(profile, profileId, applicationId);
+ if (!estConfigId) {
throw new BadRequestError({ message: "EST enrollment not configured for this profile" });
}
@@ -343,7 +371,7 @@ export const certificateEstV3ServiceFactory = ({
});
}
- const estConfig = await estEnrollmentConfigDAL.findById(profile.estConfigId);
+ const estConfig = await estEnrollmentConfigDAL.findById(estConfigId);
if (!estConfig) {
throw new NotFoundError({ message: "EST configuration not found" });
}
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.test.ts b/backend/src/services/certificate-profile/certificate-profile-service.test.ts
index b9bdd39d65..3404a47217 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.test.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.test.ts
@@ -382,24 +382,24 @@ describe("CertificateProfileService", () => {
).rejects.toThrow(ForbiddenRequestError);
});
- it("should throw ForbiddenRequestError for EST enrollment without EST config", async () => {
- const invalidData = {
+ it("should create profile with EST enrollment type but no EST config (config attached to Application junction)", async () => {
+ const data = {
...validProfileData,
enrollmentType: EnrollmentType.EST,
estConfigId: null
};
- await expect(
- service.createProfile({
- ...mockActor,
- projectId: "project-123",
- data: invalidData
- })
- ).rejects.toThrow(ForbiddenRequestError);
+ const result = await service.createProfile({
+ ...mockActor,
+ projectId: "project-123",
+ data
+ });
+
+ expect(result).toBeDefined();
});
- it("should throw ForbiddenRequestError for API enrollment without API config", async () => {
- const invalidData = {
+ it("should create profile with API enrollment type but no API config (config attached to Application junction)", async () => {
+ const data = {
slug: "invalid-profile",
description: "Invalid test profile",
enrollmentType: EnrollmentType.API,
@@ -408,13 +408,13 @@ describe("CertificateProfileService", () => {
certificatePolicyId: "policy-123"
};
- await expect(
- service.createProfile({
- ...mockActor,
- projectId: "project-123",
- data: invalidData
- })
- ).rejects.toThrow(ForbiddenRequestError);
+ const result = await service.createProfile({
+ ...mockActor,
+ projectId: "project-123",
+ data
+ });
+
+ expect(result).toBeDefined();
});
it("should create profile with API enrollment", async () => {
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.ts b/backend/src/services/certificate-profile/certificate-profile-service.ts
index 1a0cf859a4..b255fd5292 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.ts
@@ -39,6 +39,7 @@ import {
import { TEstEnrollmentConfigDALFactory } from "../enrollment-config/est-enrollment-config-dal";
import { TScepEnrollmentConfigDALFactory } from "../enrollment-config/scep-enrollment-config-dal";
import { TKmsServiceFactory } from "../kms/kms-service";
+import { TPkiApplicationProfileDALFactory } from "../pki-application/pki-application-profile-dal";
import { TProjectDALFactory } from "../project/project-dal";
import { getProjectKmsCertificateKeyId } from "../project/project-fns";
import { TResourceMetadataDALFactory } from "../resource-metadata/resource-metadata-dal";
@@ -145,7 +146,7 @@ const validateExternalConfigs = async (
validateTemplateByExternalCaType(externalCa.type as CaType, externalConfigs);
};
-const generateAndEncryptAcmeEabSecret = async (
+export const generateAndEncryptAcmeEabSecret = async (
projectId: string,
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey">,
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">
@@ -175,7 +176,7 @@ const generateAndEncryptAcmeEabSecret = async (
}
};
-const validateAndEncryptPemCaChain = async (
+export const validateAndEncryptPemCaChain = async (
caChain: string,
projectId: string,
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey">,
@@ -212,7 +213,7 @@ const validateAndEncryptPemCaChain = async (
}
};
-const decryptCaChain = async (
+export const decryptCaChain = async (
encryptedCaChain: Buffer,
projectId: string,
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "decryptWithKmsKey">,
@@ -266,6 +267,7 @@ type TCertificateProfileServiceFactoryDep = {
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
projectDAL: Pick<TProjectDALFactory, "findProjectBySlug" | "findOne" | "updateById" | "findById" | "transaction">;
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find">;
+ pkiApplicationProfileDAL?: Pick<TPkiApplicationProfileDALFactory, "findOne">;
};
export type TCertificateProfileServiceFactory = ReturnType<typeof certificateProfileServiceFactory>;
@@ -309,7 +311,8 @@ export const certificateProfileServiceFactory = ({
permissionService,
kmsService,
projectDAL,
- resourceMetadataDAL
+ resourceMetadataDAL,
+ pkiApplicationProfileDAL
}: TCertificateProfileServiceFactoryDep) => {
const createProfile = async ({
actor,
@@ -399,17 +402,6 @@ export const certificateProfileServiceFactory = ({
externalCertificateAuthorityDAL
);
- // Validate enrollment configuration requirements
- if (data.enrollmentType === EnrollmentType.EST && !data.estConfig) {
- throw new ForbiddenRequestError({
- message: "EST enrollment requires EST configuration"
- });
- }
- if (data.enrollmentType === EnrollmentType.API && !data.apiConfig) {
- throw new ForbiddenRequestError({
- message: "API enrollment requires API configuration"
- });
- }
if (data.enrollmentType === EnrollmentType.ACME && data.acmeConfig) {
if (data.acmeConfig.skipEabBinding && data.acmeConfig.skipDnsOwnershipVerification) {
throw new ForbiddenRequestError({
@@ -417,11 +409,6 @@ export const certificateProfileServiceFactory = ({
});
}
}
- if (data.enrollmentType === EnrollmentType.SCEP && !data.scepConfig) {
- throw new ForbiddenRequestError({
- message: "SCEP enrollment requires SCEP configuration"
- });
- }
// Perform crypto operations before the transaction to avoid holding DB connections
let precomputedScepConfig:
@@ -1320,6 +1307,7 @@ export const certificateProfileServiceFactory = ({
params:
| {
profileId: string;
+ applicationId?: string;
isInternal: true;
}
| {
@@ -1328,10 +1316,11 @@ export const certificateProfileServiceFactory = ({
actorAuthMethod: ActorAuthMethod;
actorOrgId: string | undefined;
profileId: string;
+ applicationId?: string;
isInternal?: false;
}
) => {
- const { profileId, isInternal = false } = params;
+ const { profileId, applicationId, isInternal = false } = params;
const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
if (!profile) {
throw new NotFoundError({ message: "Certificate profile not found" });
@@ -1368,6 +1357,31 @@ export const certificateProfileServiceFactory = ({
});
}
+ if (applicationId && pkiApplicationProfileDAL) {
+ const junction = await pkiApplicationProfileDAL.findOne(applicationId, profileId);
+ if (!junction) {
+ throw new NotFoundError({
+ message: `Profile '${profileId}' is not attached to application '${applicationId}'.`
+ });
+ }
+ if (!junction.estConfigId) {
+ throw new NotFoundError({
+ message: "EST configuration not found for this Application/Profile pair."
+ });
+ }
+ const estConfig = await estEnrollmentConfigDAL.findById(junction.estConfigId);
+ if (!estConfig) {
+ throw new NotFoundError({ message: "EST configuration not found." });
+ }
+ return {
+ orgId: profile.projectId,
+ isEnabled: true,
+ caChain: estConfig.encryptedCaChain ?? null,
+ disableBootstrapCertValidation: estConfig.disableBootstrapCaValidation ?? false,
+ hashedPassphrase: estConfig.hashedPassphrase
+ };
+ }
+
if (!profile.estConfig) {
throw new NotFoundError({ message: "EST configuration not found for this profile" });
}
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
index cee0d0a509..ac0797c886 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -260,7 +260,11 @@ describe("CertificateV3Service", () => {
insertMany: vi.fn().mockResolvedValue([]),
delete: vi.fn().mockResolvedValue([]),
find: vi.fn().mockResolvedValue([])
- }
+ },
+ pkiApplicationProfileDAL: {
+ findByProfileId: vi.fn().mockResolvedValue(null),
+ findAllByProfileId: vi.fn().mockResolvedValue([])
+ } as never
});
});
@@ -291,7 +295,8 @@ describe("CertificateV3Service", () => {
createdAt: new Date(),
updatedAt: new Date(),
slug: "test-profile",
- description: "Test profile"
+ description: "Test profile",
+ apiConfigId: "api-config-legacy"
};
const mockCA = {
@@ -448,7 +453,7 @@ describe("CertificateV3Service", () => {
slug: "test-profile-camel",
description: "Test camelCase profile",
estConfigId: null,
- apiConfigId: null
+ apiConfigId: "api-config-legacy"
};
const mockCA = {
@@ -670,7 +675,7 @@ describe("CertificateV3Service", () => {
slug: "test-profile-est",
description: "Test EST profile",
estConfigId: null,
- apiConfigId: null
+ apiConfigId: "api-config-legacy"
};
vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
@@ -724,7 +729,7 @@ describe("CertificateV3Service", () => {
slug: "test-profile-sign",
description: "Test signing profile",
estConfigId: null,
- apiConfigId: null
+ apiConfigId: "api-config-legacy"
};
const mockCA = {
@@ -893,7 +898,7 @@ describe("CertificateV3Service", () => {
slug: "test-profile-est-sign",
description: "Test EST signing profile",
estConfigId: null,
- apiConfigId: null
+ apiConfigId: "api-config-legacy"
};
vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
@@ -945,7 +950,7 @@ describe("CertificateV3Service", () => {
slug: "test-profile-est-order",
description: "Test EST order profile",
estConfigId: null,
- apiConfigId: null
+ apiConfigId: "api-config-legacy"
};
vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
@@ -981,7 +986,7 @@ describe("CertificateV3Service", () => {
updatedAt: new Date(),
description: "Test profile for algorithm compatibility",
estConfigId: null,
- apiConfigId: null
+ apiConfigId: "api-config-legacy"
};
const mockCertificateRequest = {
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index a8f5eb25fc..97048a8400 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -96,6 +96,7 @@ import { TCertificateRequestDALFactory } from "../certificate-request/certificat
import { TCertificateRequestServiceFactory } from "../certificate-request/certificate-request-service";
import { CertificateRequestStatus } from "../certificate-request/certificate-request-types";
import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
+import { TPkiApplicationProfileDALFactory } from "../pki-application/pki-application-profile-dal";
import { TPkiSyncDALFactory } from "../pki-sync/pki-sync-dal";
import { TPkiSyncQueueFactory } from "../pki-sync/pki-sync-queue";
import { addRenewedCertificateToSyncs, triggerAutoSyncForCertificate } from "../pki-sync/pki-sync-utils";
@@ -158,6 +159,7 @@ type TCertificateV3ServiceFactoryDep = {
approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "createRequestFromPolicy">;
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete" | "find">;
pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
+ pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findByProfileId" | "findAllByProfileId">;
};
export type TCertificateV3ServiceFactory = ReturnType<typeof certificateV3ServiceFactory>;
@@ -655,11 +657,43 @@ export const certificateV3ServiceFactory = ({
identityDAL,
approvalPolicyService,
resourceMetadataDAL,
- pkiAlertV2Queue
+ pkiAlertV2Queue,
+ pkiApplicationProfileDAL
}: TCertificateV3ServiceFactoryDep) => {
- /**
- * Resolves requester name and email based on actor type
- */
+ const $resolveApplicationIdForProfile = async (
+ profile: {
+ id: string;
+ apiConfigId?: string | null;
+ estConfigId?: string | null;
+ acmeConfigId?: string | null;
+ scepConfigId?: string | null;
+ },
+ explicit: string | undefined
+ ): Promise<string | undefined> => {
+ const junctions = await pkiApplicationProfileDAL.findAllByProfileId(profile.id);
+
+ if (explicit) {
+ if (junctions.length > 0 && !junctions.some((j) => j.applicationId === explicit)) {
+ throw new BadRequestError({
+ message: "This profile is not attached to the specified Application."
+ });
+ }
+ return explicit;
+ }
+
+ const hasProfileLevelEnrollment = Boolean(
+ profile.apiConfigId || profile.estConfigId || profile.acmeConfigId || profile.scepConfigId
+ );
+ if (!hasProfileLevelEnrollment) {
+ throw new BadRequestError({
+ message:
+ "This profile must be issued through a Cert Manager Application. Attach it to an Application and issue from there."
+ });
+ }
+
+ return undefined;
+ };
+
const resolveRequesterInfo = async (
actor: ActorType,
actorId: string,
@@ -692,9 +726,6 @@ export const certificateV3ServiceFactory = ({
return { requesterName: "Unknown Client", requesterEmail: "" };
};
- /**
- * Checks if actor should bypass approval based on machine identity flag
- */
const shouldBypassApproval = (actor: ActorType, policy: TCertRequestPolicy | null): boolean => {
return actor === ActorType.IDENTITY && policy?.bypassForMachineIdentities === true;
};
@@ -707,7 +738,8 @@ export const certificateV3ServiceFactory = ({
actorId,
actorAuthMethod,
actorOrgId,
- removeRootsFromChain
+ removeRootsFromChain,
+ applicationId: explicitApplicationId
}: TIssueCertificateFromProfileDTO): Promise<TCertificateIssuanceResponse> => {
const profile = await validateProfileAndPermissions({
profileId,
@@ -722,12 +754,15 @@ export const certificateV3ServiceFactory = ({
isInternal: actor === ActorType.EST_ACCOUNT || actor === ActorType.SCEP_ACCOUNT
});
+ const applicationId = await $resolveApplicationIdForProfile(profile, explicitApplicationId);
+
const approvalFactory = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.CertRequest](ApprovalPolicyType.CertRequest);
const matchedApprovalPolicy = (await approvalFactory.matchPolicy(
approvalPolicyDAL as TApprovalPolicyDALFactory,
profile.projectId,
{
- profileName: profile.slug
+ profileName: profile.slug,
+ applicationId
}
)) as TCertRequestPolicy | null;
@@ -1030,6 +1065,10 @@ export const certificateV3ServiceFactory = ({
);
}
+ if (applicationId) {
+ await certificateDAL.updateById(processResult.certificateData.id, { applicationId }, tx);
+ }
+
return { ...processResult, certificateRequestId: certRequestResult.id };
});
@@ -1160,10 +1199,15 @@ export const certificateV3ServiceFactory = ({
new Date(certificateRecord.notAfter)
);
- const updateData: { profileId: string; renewBeforeDays?: number } = { profileId };
+ const updateData: { profileId: string; renewBeforeDays?: number; applicationId?: string } = {
+ profileId
+ };
if (finalRenewBeforeDays !== undefined) {
updateData.renewBeforeDays = finalRenewBeforeDays;
}
+ if (applicationId) {
+ updateData.applicationId = applicationId;
+ }
await certificateDAL.updateById(certificateRecord.id, updateData, tx);
const certRequestResult = await certificateRequestService.createCertificateRequest({
@@ -1274,7 +1318,8 @@ export const certificateV3ServiceFactory = ({
enrollmentType,
metadata,
removeRootsFromChain,
- basicConstraints
+ basicConstraints,
+ applicationId: explicitApplicationId
}: TSignCertificateFromProfileDTO): Promise<TCertificateIssuanceResponse> => {
const profile = await validateProfileAndPermissions({
profileId,
@@ -1288,6 +1333,7 @@ export const certificateV3ServiceFactory = ({
requiredEnrollmentType: enrollmentType,
isInternal: actor === ActorType.EST_ACCOUNT || actor === ActorType.SCEP_ACCOUNT
});
+ const applicationId = await $resolveApplicationIdForProfile(profile, explicitApplicationId);
if (!profile.caId) {
throw new BadRequestError({
@@ -1364,7 +1410,8 @@ export const certificateV3ServiceFactory = ({
approvalPolicyDAL as TApprovalPolicyDALFactory,
profile.projectId,
{
- profileName: profile.slug
+ profileName: profile.slug,
+ applicationId
}
)) as TCertRequestPolicy | null;
@@ -1556,10 +1603,15 @@ export const certificateV3ServiceFactory = ({
new Date(signedCertRecord.notAfter)
);
- const updateData: { profileId: string; renewBeforeDays?: number } = { profileId };
+ const updateData: { profileId: string; renewBeforeDays?: number; applicationId?: string } = {
+ profileId
+ };
if (finalRenewBeforeDays !== undefined) {
updateData.renewBeforeDays = finalRenewBeforeDays;
}
+ if (applicationId) {
+ updateData.applicationId = applicationId;
+ }
await certificateDAL.updateById(signedCertRecord.id, updateData, tx);
const certRequestResult = await certificateRequestService.createCertificateRequest({
@@ -1643,7 +1695,8 @@ export const certificateV3ServiceFactory = ({
actor,
actorId,
actorAuthMethod,
- actorOrgId
+ actorOrgId,
+ applicationId: explicitApplicationId
}: TOrderCertificateFromProfileDTO): Promise<TCertificateIssuanceResponse> => {
const profile = await validateProfileAndPermissions({
profileId,
@@ -1657,6 +1710,7 @@ export const certificateV3ServiceFactory = ({
requiredEnrollmentType: EnrollmentType.API,
isInternal: actor === ActorType.EST_ACCOUNT || actor === ActorType.SCEP_ACCOUNT
});
+ const applicationId = await $resolveApplicationIdForProfile(profile, explicitApplicationId);
let certificateRequest: TCertificateRequest;
let extractedKeyAlgorithm: string | undefined;
@@ -1749,7 +1803,8 @@ export const certificateV3ServiceFactory = ({
approvalPolicyDAL as TApprovalPolicyDALFactory,
profile.projectId,
{
- profileName: profile.slug
+ profileName: profile.slug,
+ applicationId
}
)) as TCertRequestPolicy | null;
diff --git a/backend/src/services/certificate-v3/certificate-v3-types.ts b/backend/src/services/certificate-v3/certificate-v3-types.ts
index 4f3ebcb1b1..ad64eec1dc 100644
--- a/backend/src/services/certificate-v3/certificate-v3-types.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-types.ts
@@ -37,6 +37,7 @@ export type TIssueCertificateFromProfileDTO = {
};
metadata?: Array<{ key: string; value: string }>;
removeRootsFromChain?: boolean;
+ applicationId?: string;
} & Omit<TProjectPermission, "projectId">;
export type TSignCertificateFromProfileDTO = {
@@ -54,6 +55,7 @@ export type TSignCertificateFromProfileDTO = {
isCA: boolean;
pathLength?: number;
};
+ applicationId?: string;
} & Omit<TProjectPermission, "projectId">;
export type TOrderCertificateFromProfileDTO = {
@@ -83,6 +85,7 @@ export type TOrderCertificateFromProfileDTO = {
};
metadata?: Array<{ key: string; value: string }>;
removeRootsFromChain?: boolean;
+ applicationId?: string;
} & Omit<TProjectPermission, "projectId">;
export type TCertificateIssuanceResponse = {
diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.ts
index 207ff832e1..f10c77739c 100644
--- a/backend/src/services/certificate/certificate-dal.ts
+++ b/backend/src/services/certificate/certificate-dal.ts
@@ -85,6 +85,7 @@ export const certificateDALFactory = (db: TDbClient) => {
notAfterTo?: Date;
notBeforeFrom?: Date;
notBeforeTo?: Date;
+ applicationId?: string;
};
const applyInventoryFilters = (
@@ -222,6 +223,10 @@ export const certificateDALFactory = (db: TDbClient) => {
q = q.andWhere(`${TableName.Certificate}.notBefore`, "<=", filters.notBeforeTo);
}
+ if (filters.applicationId) {
+ q = q.andWhere(`${TableName.Certificate}.applicationId`, filters.applicationId);
+ }
+
return q;
};
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index 2c0a6c2920..9df271deb2 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -74,7 +74,7 @@ type TCertificateServiceFactoryDep = {
certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
pkiCollectionDAL: Pick<TPkiCollectionDALFactory, "findById">;
pkiCollectionItemDAL: Pick<TPkiCollectionItemDALFactory, "create">;
- projectDAL: Pick<TProjectDALFactory, "findProjectBySlug" | "findOne" | "updateById" | "findById" | "transaction">;
+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "findById" | "transaction">;
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findPkiSyncIdsByCertificateId">;
@@ -548,7 +548,7 @@ export const certificateServiceFactory = ({
* Import certificate
*/
const importCert = async ({
- projectSlug,
+ projectId,
pkiCollectionId,
actorId,
actorAuthMethod,
@@ -561,10 +561,6 @@ export const certificateServiceFactory = ({
}: TImportCertDTO) => {
const collectionId = pkiCollectionId;
- const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
- if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
- const projectId = project.id;
-
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
diff --git a/backend/src/services/certificate/certificate-types.ts b/backend/src/services/certificate/certificate-types.ts
index 59f1eb743e..120020d569 100644
--- a/backend/src/services/certificate/certificate-types.ts
+++ b/backend/src/services/certificate/certificate-types.ts
@@ -139,7 +139,7 @@ export type TGetCertBodyDTO = {
} & Omit<TProjectPermission, "projectId">;
export type TImportCertDTO = {
- projectSlug: string;
+ projectId: string;
friendlyName?: string;
pkiCollectionId?: string;
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index 77bccafc0c..163710421e 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -46,8 +46,10 @@ import { ActorAuthMethod, ActorType, AuthMethod, AuthModeJwtTokenPayload, AuthTo
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types";
import { TIdentityMetadataDALFactory } from "../identity/identity-metadata-dal";
+import { TMembershipDALFactory } from "../membership/membership-dal";
import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";
+import { bootstrapCertManagerProject } from "../pki-application/cert-manager-project-bootstrap";
import { TProjectDALFactory } from "../project/project-dal";
import { TProjectBotServiceFactory } from "../project-bot/project-bot-service";
import { TProjectKeyDALFactory } from "../project-key/project-key-dal";
@@ -92,6 +94,7 @@ type TOrgServiceFactoryDep = {
projectDAL: TProjectDALFactory;
identityMetadataDAL: Pick<TIdentityMetadataDALFactory, "delete" | "insertMany" | "transaction">;
membershipUserDAL: TMembershipUserDALFactory;
+ membershipDAL: TMembershipDALFactory;
projectMembershipDAL: Pick<
TProjectMembershipDALFactory,
"findProjectMembershipsByUserId" | "findProjectMembershipsByUserIds"
@@ -149,6 +152,7 @@ export const orgServiceFactory = ({
reminderService,
membershipRoleDAL,
membershipUserDAL,
+ membershipDAL,
userGroupMembershipDAL,
additionalPrivilegeDAL
}: TOrgServiceFactoryDep) => {
@@ -676,6 +680,15 @@ export const orgServiceFactory = ({
);
}
+ await bootstrapCertManagerProject(
+ {
+ orgId: org.id,
+ adminUserIds: userId ? [userId] : []
+ },
+ { projectDAL, membershipDAL, membershipRoleDAL },
+ tx
+ );
+
return org;
};
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-dal.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-dal.ts
index 55b5c0fc90..d0aec76d8c 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-dal.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-dal.ts
@@ -154,6 +154,7 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
enabled?: boolean;
limit?: number;
offset?: number;
+ applicationId?: string | null;
},
tx?: Knex
): Promise<{ alerts: TAlertWithChannels[]; total: number }> => {
@@ -175,6 +176,14 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
countQuery = countQuery.where(`${TableName.PkiAlertsV2}.enabled`, filters.enabled);
}
+ if (filters?.applicationId !== undefined) {
+ if (filters.applicationId === null) {
+ countQuery = countQuery.whereNull(`${TableName.PkiAlertsV2}.applicationId`);
+ } else {
+ countQuery = countQuery.where(`${TableName.PkiAlertsV2}.applicationId`, filters.applicationId);
+ }
+ }
+
let alertQuery = (tx || db.replicaNode())
.select(selectAllTableCols(TableName.PkiAlertsV2))
.from(TableName.PkiAlertsV2)
@@ -192,6 +201,14 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
alertQuery = alertQuery.where(`${TableName.PkiAlertsV2}.enabled`, filters.enabled);
}
+ if (filters?.applicationId !== undefined) {
+ if (filters.applicationId === null) {
+ alertQuery = alertQuery.whereNull(`${TableName.PkiAlertsV2}.applicationId`);
+ } else {
+ alertQuery = alertQuery.where(`${TableName.PkiAlertsV2}.applicationId`, filters.applicationId);
+ }
+ }
+
alertQuery = alertQuery.orderBy(`${TableName.PkiAlertsV2}.createdAt`, "desc");
if (filters?.limit) {
@@ -355,11 +372,13 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
excludeAlerted?: boolean;
alertId?: string;
certificateId?: string;
+ applicationId?: string;
},
tx?: Knex
): Promise<{ certificates: TCertificatePreview[]; total: number }> => {
try {
- const includeCAs = shouldIncludeCAs(filters);
+ const isApplicationScoped = Boolean(options?.applicationId);
+ const includeCAs = shouldIncludeCAs(filters) && !isApplicationScoped;
const needsProfileJoin = requiresProfileJoin(filters);
const limit = options?.limit || 10;
const offset = options?.offset || 0;
@@ -411,6 +430,10 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
certCountQuery = applyCertificateFilters(certCountQuery, filters, projectId) as typeof certCountQuery;
+ if (options?.applicationId) {
+ certCountQuery = certCountQuery.where(`${TableName.Certificate}.applicationId`, options.applicationId);
+ }
+
if (options?.certificateId) {
certCountQuery = certCountQuery.where(`${TableName.Certificate}.id`, options.certificateId);
}
@@ -489,6 +512,10 @@ export const pkiAlertV2DALFactory = (db: TDbClient) => {
certificateQuery = applyCertificateFilters(certificateQuery, filters, projectId) as typeof certificateQuery;
+ if (options?.applicationId) {
+ certificateQuery = certificateQuery.where(`${TableName.Certificate}.applicationId`, options.applicationId);
+ }
+
if (options?.certificateId) {
certificateQuery = certificateQuery.where(`${TableName.Certificate}.id`, options.certificateId);
}
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-queue.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-queue.ts
index 860fb0428c..0c0f9b3591 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-queue.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-queue.ts
@@ -70,6 +70,7 @@ export const pkiAlertV2QueueServiceFactory = ({
alertBefore: string;
filters: TPkiFilterRule[];
notificationConfig?: TNotificationConfig | null;
+ applicationId?: string | null;
},
projectId: string
): Promise<{ shouldNotify: boolean; certificateIds: string[] }> => {
@@ -81,7 +82,8 @@ export const pkiAlertV2QueueServiceFactory = ({
const result = await pkiAlertV2DAL.findMatchingCertificates(projectId, alert.filters, {
limit: 1000,
alertBefore: parseTimeToPostgresInterval(alert.alertBefore),
- showCurrentMatches: true
+ showCurrentMatches: true,
+ ...(alert.applicationId ? { applicationId: alert.applicationId } : {})
});
if (result.certificates.length === 0) {
@@ -145,7 +147,8 @@ export const pkiAlertV2QueueServiceFactory = ({
eventType: alert.eventType,
alertBefore: alert.alertBefore ?? "",
filters: (alert.filters ?? []) as TPkiFilterRule[],
- notificationConfig: alert.notificationConfig as TNotificationConfig | null
+ notificationConfig: alert.notificationConfig as TNotificationConfig | null,
+ applicationId: alert.applicationId ?? null
},
projectId
);
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-service.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-service.ts
index 2339ce7d8a..dea13024f1 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-service.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-service.ts
@@ -1,8 +1,9 @@
import { ForbiddenError } from "@casl/ability";
-import { ActionProjectType, ProjectMembershipRole } from "@app/db/schemas";
+import { ActionProjectType, ProjectMembershipRole, ResourceType } from "@app/db/schemas";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
+import { ResourcePermissionSub } from "@app/ee/services/permission/resource-permission";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
@@ -69,7 +70,7 @@ type TPkiAlertV2ServiceFactoryDep = {
>;
pkiAlertChannelDAL: Pick<TPkiAlertChannelDALFactory, "create" | "findByAlertId" | "deleteByAlertId" | "insertMany">;
pkiAlertHistoryDAL: Pick<TPkiAlertHistoryDALFactory, "createWithCertificates" | "findByAlertId">;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
smtpService: Pick<TSmtpService, "sendMail">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
@@ -90,6 +91,48 @@ export const pkiAlertV2ServiceFactory = ({
projectMembershipDAL,
projectDAL
}: TPkiAlertV2ServiceFactoryDep) => {
+ const $assertCanActOnAlert = async (
+ action: ProjectPermissionActions,
+ projectId: string,
+ applicationId: string | null | undefined,
+ ctx: {
+ actor: Parameters<TPermissionServiceFactory["getProjectPermission"]>[0]["actor"];
+ actorId: string;
+ actorAuthMethod: Parameters<TPermissionServiceFactory["getProjectPermission"]>[0]["actorAuthMethod"];
+ actorOrgId?: string;
+ }
+ ) => {
+ const projectPerm = await permissionService.getProjectPermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+
+ if (projectPerm.permission.can(action, ProjectPermissionSub.PkiAlerts)) {
+ return projectPerm;
+ }
+
+ if (!applicationId) {
+ ForbiddenError.from(projectPerm.permission).throwUnlessCan(action, ProjectPermissionSub.PkiAlerts);
+ return projectPerm;
+ }
+
+ const { permission: resourcePerm } = await permissionService.getResourcePermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ resourceType: ResourceType.CertificateApplication,
+ resourceId: applicationId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId
+ });
+ ForbiddenError.from(resourcePerm).throwUnlessCan(action, ResourcePermissionSub.PkiAlerts);
+ return projectPerm;
+ };
+
// Helper to encrypt channel config before storing in DB
const encryptChannelConfig = (
config: TChannelConfig,
@@ -167,6 +210,7 @@ export const pkiAlertV2ServiceFactory = ({
const createAlert = async ({
projectId,
+ applicationId,
name,
description,
eventType,
@@ -180,17 +224,13 @@ export const pkiAlertV2ServiceFactory = ({
actor,
actorOrgId
}: TCreateAlertV2DTO): Promise<TAlertV2Response> => {
- const { permission } = await permissionService.getProjectPermission({
+ await $assertCanActOnAlert(ProjectPermissionActions.Create, projectId, applicationId, {
actor,
actorId,
- projectId,
actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.CertificateManager
+ actorOrgId
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.PkiAlerts);
-
if (eventType === PkiAlertEventType.EXPIRATION && !alertBefore) {
throw new BadRequestError({ message: "alertBefore is required for expiration alerts" });
}
@@ -226,6 +266,7 @@ export const pkiAlertV2ServiceFactory = ({
const alert = await pkiAlertV2DAL.create(
{
projectId,
+ applicationId: applicationId ?? null,
name,
description,
eventType,
@@ -258,6 +299,7 @@ export const pkiAlertV2ServiceFactory = ({
const getAlertById = async ({
alertId,
+ applicationId,
actorId,
actorAuthMethod,
actor,
@@ -265,18 +307,19 @@ export const pkiAlertV2ServiceFactory = ({
}: TGetAlertV2DTO): Promise<TAlertV2Response> => {
const alert = await pkiAlertV2DAL.findByIdWithChannels(alertId);
if (!alert) throw new NotFoundError({ message: `Alert with ID '${alertId}' not found` });
+ if (applicationId && alert.applicationId !== applicationId) {
+ throw new NotFoundError({
+ message: `Alert with ID '${alertId}' is not scoped to application '${applicationId}'.`
+ });
+ }
- const { permission } = await permissionService.getProjectPermission({
+ await $assertCanActOnAlert(ProjectPermissionActions.Read, alert.projectId, alert.applicationId, {
actor,
actorId,
- projectId: alert.projectId,
actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.CertificateManager
+ actorOrgId
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts);
-
const { decryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.SecretManager,
projectId: alert.projectId
@@ -287,6 +330,7 @@ export const pkiAlertV2ServiceFactory = ({
const listAlerts = async ({
projectId,
+ applicationId,
search,
eventType,
enabled,
@@ -308,7 +352,7 @@ export const pkiAlertV2ServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PkiAlerts);
- const filters = { search, eventType, enabled, limit, offset };
+ const filters = { search, eventType, enabled, limit, offset, applicationId };
const { alerts, total } = await pkiAlertV2DAL.findByProjectIdWithCount(projectId, filters);
@@ -325,6 +369,7 @@ export const pkiAlertV2ServiceFactory = ({
const updateAlert = async ({
alertId,
+ applicationId,
name,
description,
eventType,
@@ -340,18 +385,19 @@ export const pkiAlertV2ServiceFactory = ({
}: TUpdateAlertV2DTO): Promise<TAlertV2Response> => {
let alert = await pkiAlertV2DAL.findById(alertId);
if (!alert) throw new NotFoundError({ message: `Alert with ID '${alertId}' not found` });
+ if (applicationId && alert.applicationId !== applicationId) {
+ throw new NotFoundError({
+ message: `Alert with ID '${alertId}' is not scoped to application '${applicationId}'.`
+ });
+ }
- const { permission } = await permissionService.getProjectPermission({
+ await $assertCanActOnAlert(ProjectPermissionActions.Edit, alert.projectId, alert.applicationId, {
actor,
actorId,
- projectId: alert.projectId,
actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.CertificateManager
+ actorOrgId
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.PkiAlerts);
-
const resultingEventType = eventType ?? (alert.eventType as PkiAlertEventType);
const resultingAlertBefore = alertBefore !== undefined ? alertBefore : alert.alertBefore;
if (resultingEventType === PkiAlertEventType.EXPIRATION && !resultingAlertBefore) {
@@ -475,6 +521,7 @@ export const pkiAlertV2ServiceFactory = ({
const deleteAlert = async ({
alertId,
+ applicationId,
actorId,
actorAuthMethod,
actor,
@@ -482,18 +529,19 @@ export const pkiAlertV2ServiceFactory = ({
}: TDeleteAlertV2DTO): Promise<TAlertV2Response> => {
const alert = await pkiAlertV2DAL.findByIdWithChannels(alertId);
if (!alert) throw new NotFoundError({ message: `Alert with ID '${alertId}' not found` });
+ if (applicationId && alert.applicationId !== applicationId) {
+ throw new NotFoundError({
+ message: `Alert with ID '${alertId}' is not scoped to application '${applicationId}'.`
+ });
+ }
- const { permission } = await permissionService.getProjectPermission({
+ await $assertCanActOnAlert(ProjectPermissionActions.Delete, alert.projectId, alert.applicationId, {
actor,
actorId,
- projectId: alert.projectId,
actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.CertificateManager
+ actorOrgId
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Delete, ProjectPermissionSub.PkiAlerts);
-
const { decryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.SecretManager,
projectId: alert.projectId
@@ -534,12 +582,14 @@ export const pkiAlertV2ServiceFactory = ({
showPreview?: boolean;
excludeAlerted?: boolean;
alertId?: string;
+ applicationId?: string;
} = {
limit,
offset,
showPreview: true,
excludeAlerted: alert.eventType === PkiAlertEventType.EXPIRATION,
- alertId
+ alertId,
+ ...(alert.applicationId ? { applicationId: alert.applicationId } : {})
};
const result = await pkiAlertV2DAL.findMatchingCertificates(
@@ -780,7 +830,8 @@ export const pkiAlertV2ServiceFactory = ({
const filters = (alert.filters ?? []) as TPkiFilterRule[];
const { certificates } = await pkiAlertV2DAL.findMatchingCertificates(projectId, filters, {
- alertBefore: parseTimeToPostgresInterval(alertBefore)
+ alertBefore: parseTimeToPostgresInterval(alertBefore),
+ ...(alert.applicationId ? { applicationId: alert.applicationId } : {})
});
const matchingCertificates = certificates.filter(
@@ -810,15 +861,17 @@ export const pkiAlertV2ServiceFactory = ({
if (channels.length === 0) return;
const filters = (alert.filters ?? []) as TPkiFilterRule[];
-
- const allCertificates: TCertificatePreview[] = [];
- for (const certId of certificateIds) {
- // eslint-disable-next-line no-await-in-loop
- const { certificates } = await pkiAlertV2DAL.findMatchingCertificates(projectId, filters, {
- certificateId: certId
- });
- allCertificates.push(...certificates);
- }
+ const applicationScope = alert.applicationId ? { applicationId: alert.applicationId } : {};
+
+ const matchingPerCert = await Promise.all(
+ certificateIds.map((certId) =>
+ pkiAlertV2DAL.findMatchingCertificates(projectId, filters, {
+ certificateId: certId,
+ ...applicationScope
+ })
+ )
+ );
+ const allCertificates: TCertificatePreview[] = matchingPerCert.flatMap((r) => r.certificates);
const matchingCertificates = allCertificates.filter((cert) => cert.enrollmentType !== CertificateOrigin.CA);
diff --git a/backend/src/services/pki-alert-v2/pki-alert-v2-types.ts b/backend/src/services/pki-alert-v2/pki-alert-v2-types.ts
index 8a04c95343..5819eb17ae 100644
--- a/backend/src/services/pki-alert-v2/pki-alert-v2-types.ts
+++ b/backend/src/services/pki-alert-v2/pki-alert-v2-types.ts
@@ -242,20 +242,56 @@ export type TCreatePkiAlertV2 = z.infer<typeof CreatePkiAlertV2Schema>;
export const UpdatePkiAlertV2Schema = BasePkiAlertV2Schema.partial();
export type TUpdatePkiAlertV2 = z.infer<typeof UpdatePkiAlertV2Schema>;
+export const PkiAlertV2ResponseSchema = z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ description: z.string().nullable(),
+ eventType: z.nativeEnum(PkiAlertEventType),
+ alertBefore: z.string().optional(),
+ filters: z.array(PkiFilterRuleSchema),
+ enabled: z.boolean(),
+ projectId: z.string(),
+ applicationId: z.string().uuid().nullable().optional(),
+ notificationConfig: NotificationConfigSchema.nullable(),
+ channels: z.array(
+ z.object({
+ id: z.string().uuid(),
+ channelType: z.nativeEnum(PkiAlertChannelType),
+ config: z.record(z.any()),
+ enabled: z.boolean(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+ })
+ ),
+ lastRun: z
+ .object({
+ timestamp: z.date(),
+ status: z.nativeEnum(PkiAlertRunStatus),
+ error: z.string().nullable()
+ })
+ .nullable(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
export type TCreateAlertV2DTO = TGenericPermission & {
projectId: string;
+ applicationId?: string;
} & TCreatePkiAlertV2;
export type TUpdateAlertV2DTO = TGenericPermission & {
alertId: string;
+ applicationId?: string;
} & TUpdatePkiAlertV2;
export type TGetAlertV2DTO = TGenericPermission & {
alertId: string;
+ applicationId?: string;
};
export type TDeleteAlertV2DTO = TGenericPermission & {
alertId: string;
+ applicationId?: string;
};
export type TListAlertsV2DTO = TGenericPermission & {
@@ -265,6 +301,7 @@ export type TListAlertsV2DTO = TGenericPermission & {
enabled?: boolean;
limit?: number;
offset?: number;
+ applicationId?: string | null;
};
export type TListMatchingCertificatesDTO = TGenericPermission & {
diff --git a/backend/src/services/pki-application/cert-manager-instance-service.ts b/backend/src/services/pki-application/cert-manager-instance-service.ts
new file mode 100644
index 0000000000..515efa403b
--- /dev/null
+++ b/backend/src/services/pki-application/cert-manager-instance-service.ts
@@ -0,0 +1,166 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { TDbClient } from "@app/db";
+import { OrganizationActionScope, ProjectType, TableName } from "@app/db/schemas";
+import { OrgPermissionCertManagerActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { ActorType } from "@app/services/auth/auth-type";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+
+type TCertManagerInstanceServiceDeps = {
+ db: TDbClient;
+ orgDAL: Pick<TOrgDALFactory, "findById" | "updateById">;
+ projectDAL: Pick<TProjectDALFactory, "find">;
+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
+};
+
+type TActor = {
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: Parameters<TPermissionServiceFactory["getOrgPermission"]>[0]["actorAuthMethod"];
+ actorOrgId: string;
+};
+
+export type TCertManagerInstanceServiceFactory = ReturnType<typeof certManagerInstanceServiceFactory>;
+
+export const certManagerInstanceServiceFactory = ({
+ db,
+ orgDAL,
+ projectDAL,
+ permissionService
+}: TCertManagerInstanceServiceDeps) => {
+ const getInstanceState = async ({ actor, actorId, actorAuthMethod, actorOrgId }: TActor) => {
+ const { permission } = await permissionService.getOrgPermission({
+ actor,
+ actorId,
+ orgId: actorOrgId,
+ actorAuthMethod,
+ actorOrgId,
+ scope: OrganizationActionScope.Any
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionCertManagerActions.Read,
+ OrgPermissionSubjects.CertManager
+ );
+
+ const org = await orgDAL.findById(actorOrgId);
+ if (!org) throw new NotFoundError({ message: "Organization not found" });
+
+ const projects = await projectDAL.find({ orgId: actorOrgId, type: ProjectType.CertificateManager });
+ const projectsSorted = [...projects].sort((a, b) => a.name.localeCompare(b.name));
+
+ let activeProjectId = org.defaultCertManagerProjectId ?? null;
+ if (!activeProjectId && projectsSorted.length === 1) {
+ activeProjectId = projectsSorted[0].id;
+ }
+
+ return {
+ activeProjectId,
+ projects: projectsSorted.map((p) => ({
+ id: p.id,
+ name: p.name,
+ slug: p.slug,
+ createdAt: p.createdAt
+ })),
+ isMultiInstance: projectsSorted.length > 1
+ };
+ };
+
+ const setActiveProject = async ({ actor, actorId, actorAuthMethod, actorOrgId }: TActor, projectId: string) => {
+ const { permission } = await permissionService.getOrgPermission({
+ actor,
+ actorId,
+ orgId: actorOrgId,
+ actorAuthMethod,
+ actorOrgId,
+ scope: OrganizationActionScope.Any
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionCertManagerActions.ManageInstance,
+ OrgPermissionSubjects.CertManager
+ );
+
+ const projects = await projectDAL.find({ orgId: actorOrgId, type: ProjectType.CertificateManager });
+ const target = projects.find((p) => p.id === projectId);
+ if (!target) {
+ throw new BadRequestError({
+ message: "The selected project is not a Cert Manager project in this organization."
+ });
+ }
+
+ const org = await orgDAL.findById(actorOrgId);
+ const previousActiveProjectId = org?.defaultCertManagerProjectId ?? null;
+
+ await orgDAL.updateById(actorOrgId, { defaultCertManagerProjectId: projectId });
+
+ return {
+ activeProjectId: projectId,
+ previousActiveProjectId,
+ projectName: target.name
+ };
+ };
+
+ const listLegacyInstances = async ({ actor, actorId, actorAuthMethod, actorOrgId }: TActor) => {
+ const { permission } = await permissionService.getOrgPermission({
+ actor,
+ actorId,
+ orgId: actorOrgId,
+ actorAuthMethod,
+ actorOrgId,
+ scope: OrganizationActionScope.Any
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionCertManagerActions.Read,
+ OrgPermissionSubjects.CertManager
+ );
+
+ const org = await orgDAL.findById(actorOrgId);
+ if (!org) throw new NotFoundError({ message: "Organization not found" });
+
+ const projects = await projectDAL.find({ orgId: actorOrgId, type: ProjectType.CertificateManager });
+ if (projects.length === 0) {
+ return { activeProjectId: org.defaultCertManagerProjectId ?? null, instances: [] };
+ }
+
+ const projectIds = projects.map((p) => p.id);
+ const replica = db.replicaNode();
+
+ const [certCounts, syncCounts, alertCounts] = await Promise.all([
+ replica(TableName.Certificate).whereIn("projectId", projectIds).groupBy("projectId").select("projectId").count(),
+ replica(TableName.PkiSync).whereIn("projectId", projectIds).groupBy("projectId").select("projectId").count(),
+ replica(TableName.PkiAlertsV2).whereIn("projectId", projectIds).groupBy("projectId").select("projectId").count()
+ ]);
+
+ const toMap = (rows: Array<{ projectId: string; count: string | number }>) =>
+ new Map(rows.map((r) => [r.projectId, Number(r.count)]));
+ const certs = toMap(certCounts as unknown as Array<{ projectId: string; count: string | number }>);
+ const syncs = toMap(syncCounts as unknown as Array<{ projectId: string; count: string | number }>);
+ const alerts = toMap(alertCounts as unknown as Array<{ projectId: string; count: string | number }>);
+
+ const instances = [...projects]
+ .sort((a, b) => a.name.localeCompare(b.name))
+ .map((p) => ({
+ id: p.id,
+ name: p.name,
+ slug: p.slug,
+ createdAt: p.createdAt,
+ certificateCount: certs.get(p.id) ?? 0,
+ syncCount: syncs.get(p.id) ?? 0,
+ alertCount: alerts.get(p.id) ?? 0,
+ isActive: p.id === org.defaultCertManagerProjectId
+ }));
+
+ return { activeProjectId: org.defaultCertManagerProjectId ?? null, instances };
+ };
+
+ return {
+ getInstanceState,
+ setActiveProject,
+ listLegacyInstances
+ };
+};
diff --git a/backend/src/services/pki-application/cert-manager-project-bootstrap.ts b/backend/src/services/pki-application/cert-manager-project-bootstrap.ts
new file mode 100644
index 0000000000..35ea4be7a7
--- /dev/null
+++ b/backend/src/services/pki-application/cert-manager-project-bootstrap.ts
@@ -0,0 +1,93 @@
+import slugify from "@sindresorhus/slugify";
+import { Knex } from "knex";
+
+import { AccessScope, ProjectMembershipRole, ProjectType, ProjectVersion, TProjects } from "@app/db/schemas";
+import { alphaNumericNanoId } from "@app/lib/nanoid";
+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+
+type TBootstrapDeps = {
+ projectDAL: Pick<TProjectDALFactory, "create" | "findOne">;
+ membershipDAL: Pick<TMembershipDALFactory, "create">;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create">;
+};
+
+type TBootstrapInput = {
+ orgId: string;
+ adminUserIds?: string[];
+ adminIdentityIds?: string[];
+};
+
+export const bootstrapCertManagerProject = async (
+ { orgId, adminUserIds = [], adminIdentityIds = [] }: TBootstrapInput,
+ { projectDAL, membershipDAL, membershipRoleDAL }: TBootstrapDeps,
+ tx: Knex
+): Promise<{ project: TProjects; created: boolean }> => {
+ const existing = await projectDAL.findOne({ orgId, type: ProjectType.CertificateManager }, tx);
+ if (existing) {
+ return { project: existing, created: false };
+ }
+
+ const slug = slugify(`cert-manager-${alphaNumericNanoId(4)}`);
+
+ const project = await projectDAL.create(
+ {
+ name: "Certificate Manager",
+ slug,
+ type: ProjectType.CertificateManager,
+ orgId,
+ version: ProjectVersion.V3,
+ pitVersionLimit: 10
+ },
+ tx
+ );
+
+ for (const userId of adminUserIds) {
+ // eslint-disable-next-line no-await-in-loop
+ const membership = await membershipDAL.create(
+ {
+ scope: AccessScope.Project,
+ scopeOrgId: orgId,
+ scopeProjectId: project.id,
+ actorUserId: userId,
+ isActive: true
+ },
+ tx
+ );
+
+ // eslint-disable-next-line no-await-in-loop
+ await membershipRoleDAL.create(
+ {
+ membershipId: membership.id,
+ role: ProjectMembershipRole.Admin
+ },
+ tx
+ );
+ }
+
+ for (const identityId of adminIdentityIds) {
+ // eslint-disable-next-line no-await-in-loop
+ const membership = await membershipDAL.create(
+ {
+ scope: AccessScope.Project,
+ scopeOrgId: orgId,
+ scopeProjectId: project.id,
+ actorIdentityId: identityId,
+ isActive: true
+ },
+ tx
+ );
+
+ // eslint-disable-next-line no-await-in-loop
+ await membershipRoleDAL.create(
+ {
+ membershipId: membership.id,
+ role: ProjectMembershipRole.Admin
+ },
+ tx
+ );
+ }
+
+ return { project, created: true };
+};
diff --git a/backend/src/services/pki-application/cert-manager-project-resolver.ts b/backend/src/services/pki-application/cert-manager-project-resolver.ts
new file mode 100644
index 0000000000..b174339c34
--- /dev/null
+++ b/backend/src/services/pki-application/cert-manager-project-resolver.ts
@@ -0,0 +1,46 @@
+import { ProjectType } from "@app/db/schemas";
+import { BadRequestError } from "@app/lib/errors";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+
+type TResolverDeps = {
+ orgDAL: Pick<TOrgDALFactory, "findById">;
+ projectDAL: Pick<TProjectDALFactory, "find" | "findById">;
+};
+
+export const resolveCertManagerProjectId = async (
+ { orgDAL, projectDAL }: TResolverDeps,
+ actorOrgId: string
+): Promise<string> => {
+ const projects = await projectDAL.find({ orgId: actorOrgId, type: ProjectType.CertificateManager });
+
+ if (projects.length === 1) return projects[0].id;
+
+ if (projects.length === 0) {
+ throw new BadRequestError({
+ message:
+ "This organization has no Cert Manager project. Contact your administrator; one should have been created automatically."
+ });
+ }
+
+ const org = await orgDAL.findById(actorOrgId);
+ if (!org) {
+ throw new BadRequestError({ message: "Organization not found." });
+ }
+ if (org.defaultCertManagerProjectId) return org.defaultCertManagerProjectId;
+
+ throw new BadRequestError({
+ message:
+ "This organization has multiple Cert Manager projects but no default is set. An org Admin must set the default in the Cert Manager settings."
+ });
+};
+
+export type TCertManagerProjectResolverFactory = ReturnType<typeof certManagerProjectResolverFactory>;
+
+export const certManagerProjectResolverFactory = (deps: TResolverDeps) => ({
+ resolve: (actorOrgId: string) => resolveCertManagerProjectId(deps, actorOrgId),
+ isCertManagerProject: async (projectId: string): Promise<boolean> => {
+ const project = await deps.projectDAL.findById(projectId);
+ return project?.type === ProjectType.CertificateManager;
+ }
+});
diff --git a/backend/src/services/pki-application/pki-application-dal.ts b/backend/src/services/pki-application/pki-application-dal.ts
new file mode 100644
index 0000000000..9c199d398b
--- /dev/null
+++ b/backend/src/services/pki-application/pki-application-dal.ts
@@ -0,0 +1,135 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { RESOURCE_SCOPE, ResourceType, TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify } from "@app/lib/knex";
+
+import { TPkiApplicationListItem } from "./pki-application-types";
+
+export type TPkiApplicationDALFactory = ReturnType<typeof pkiApplicationDALFactory>;
+
+export const pkiApplicationDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PkiApplication);
+
+ const findBySlugAndProjectId = async (slug: string, projectId: string, tx?: Knex) => {
+ try {
+ const row = await (tx || db.replicaNode())(TableName.PkiApplication).where({ slug, projectId }).first();
+ return row;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find pki application by slug and project id" });
+ }
+ };
+
+ const findByProjectId = async (
+ projectId: string,
+ options: {
+ search?: string;
+ limit?: number;
+ offset?: number;
+ applicationIds?: string[];
+ } = {},
+ tx?: Knex
+ ): Promise<TPkiApplicationListItem[]> => {
+ try {
+ const { search, limit = 20, offset = 0, applicationIds } = options;
+ const knex = tx || db.replicaNode();
+
+ const profileCountSub = knex(TableName.PkiApplicationProfile)
+ .select("applicationId")
+ .count<{ applicationId: string; count: string }[]>("* as count")
+ .groupBy("applicationId")
+ .as("pc");
+
+ const memberCountSub = knex(TableName.Membership)
+ .select("scopeResourceId")
+ .where("scope", RESOURCE_SCOPE)
+ .andWhere("scopeProjectId", projectId)
+ .andWhere("scopeResourceType", ResourceType.CertificateApplication)
+ .count<{ scopeResourceId: string; count: string }[]>("* as count")
+ .groupBy("scopeResourceId")
+ .as("mc");
+
+ const certCountSub = knex(TableName.Certificate)
+ .select("applicationId")
+ .whereNotNull("applicationId")
+ .count<{ applicationId: string; count: string }[]>("* as count")
+ .groupBy("applicationId")
+ .as("cc");
+
+ let query = knex(TableName.PkiApplication)
+ .leftJoin(profileCountSub, "pc.applicationId", `${TableName.PkiApplication}.id`)
+ .leftJoin(memberCountSub, function joinMemberCount() {
+ this.on(knex.raw(`mc."scopeResourceId" = ${TableName.PkiApplication}.id::text`));
+ })
+ .leftJoin(certCountSub, "cc.applicationId", `${TableName.PkiApplication}.id`)
+ .where(`${TableName.PkiApplication}.projectId`, projectId)
+ .select(
+ `${TableName.PkiApplication}.id`,
+ `${TableName.PkiApplication}.projectId`,
+ `${TableName.PkiApplication}.name`,
+ `${TableName.PkiApplication}.slug`,
+ `${TableName.PkiApplication}.description`,
+ `${TableName.PkiApplication}.createdAt`,
+ `${TableName.PkiApplication}.updatedAt`,
+ knex.raw('COALESCE(pc.count, 0)::int as "profileCount"'),
+ knex.raw('COALESCE(mc.count, 0)::int as "memberCount"'),
+ knex.raw('COALESCE(cc.count, 0)::int as "certificateCount"')
+ )
+ .orderBy(`${TableName.PkiApplication}.createdAt`, "desc")
+ .limit(limit)
+ .offset(offset);
+
+ if (search) {
+ query = query.where((qb) => {
+ void qb
+ .whereILike(`${TableName.PkiApplication}.name`, `%${search}%`)
+ .orWhereILike(`${TableName.PkiApplication}.slug`, `%${search}%`)
+ .orWhereILike(`${TableName.PkiApplication}.description`, `%${search}%`);
+ });
+ }
+
+ if (applicationIds) {
+ query = query.whereIn(`${TableName.PkiApplication}.id`, applicationIds);
+ }
+
+ const rows = (await query) as TPkiApplicationListItem[];
+ return rows;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "List pki applications by project id" });
+ }
+ };
+
+ const countByProjectId = async (
+ projectId: string,
+ search?: string,
+ tx?: Knex,
+ applicationIds?: string[]
+ ): Promise<number> => {
+ try {
+ let query = (tx || db.replicaNode())(TableName.PkiApplication).where({ projectId });
+ if (search) {
+ query = query.where((qb) => {
+ void qb
+ .whereILike("name", `%${search}%`)
+ .orWhereILike("slug", `%${search}%`)
+ .orWhereILike("description", `%${search}%`);
+ });
+ }
+ if (applicationIds) {
+ query = query.whereIn("id", applicationIds);
+ }
+ const result = await query.count("*").first();
+ return parseInt((result as unknown as { count: string }).count || "0", 10);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Count pki applications by project id" });
+ }
+ };
+
+ return {
+ ...orm,
+ findBySlugAndProjectId,
+ findByProjectId,
+ countByProjectId
+ };
+};
diff --git a/backend/src/services/pki-application/pki-application-enrollment-service.ts b/backend/src/services/pki-application/pki-application-enrollment-service.ts
new file mode 100644
index 0000000000..069735d22e
--- /dev/null
+++ b/backend/src/services/pki-application/pki-application-enrollment-service.ts
@@ -0,0 +1,706 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { ResourceType } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ResourcePermissionApplicationActions,
+ ResourcePermissionApplicationEnrollmentActions,
+ ResourcePermissionSub
+} from "@app/ee/services/permission/resource-permission";
+import { ScepChallengeType } from "@app/ee/services/pki-scep/challenge";
+import { generateRaCertificate } from "@app/ee/services/pki-scep/pki-scep-fns";
+import { getConfig } from "@app/lib/config/env";
+import { crypto } from "@app/lib/crypto";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { TProjectPermission } from "@app/lib/types";
+import {
+ generateAndEncryptAcmeEabSecret,
+ validateAndEncryptPemCaChain
+} from "@app/services/certificate-profile/certificate-profile-service";
+import { TAcmeEnrollmentConfigDALFactory } from "@app/services/enrollment-config/acme-enrollment-config-dal";
+import { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";
+import { TEstEnrollmentConfigDALFactory } from "@app/services/enrollment-config/est-enrollment-config-dal";
+import { TScepEnrollmentConfigDALFactory } from "@app/services/enrollment-config/scep-enrollment-config-dal";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+
+import { TPkiApplicationDALFactory } from "./pki-application-dal";
+import { TPkiApplicationProfileDALFactory } from "./pki-application-profile-dal";
+
+type TGetEnrollmentDTO = {
+ applicationId: string;
+ profileId: string;
+} & TProjectPermission;
+
+type TSetApiEnrollmentDTO = {
+ applicationId: string;
+ profileId: string;
+ config: { autoRenew?: boolean; renewBeforeDays?: number };
+} & TProjectPermission;
+
+type TClearApiEnrollmentDTO = {
+ applicationId: string;
+ profileId: string;
+} & TProjectPermission;
+
+type TSetEstEnrollmentDTO = {
+ applicationId: string;
+ profileId: string;
+ config: { passphrase: string; disableBootstrapCaValidation?: boolean; caChain?: string };
+} & TProjectPermission;
+
+type TSetAcmeEnrollmentDTO = {
+ applicationId: string;
+ profileId: string;
+ config: { skipDnsOwnershipVerification?: boolean; skipEabBinding?: boolean };
+} & TProjectPermission;
+
+type TSetScepEnrollmentDTO = {
+ applicationId: string;
+ profileId: string;
+ config: {
+ challengeType?: ScepChallengeType;
+ challengePassword?: string;
+ includeCaCertInResponse?: boolean;
+ allowCertBasedRenewal?: boolean;
+ dynamicChallengeExpiryMinutes?: number;
+ dynamicChallengeMaxPending?: number;
+ };
+} & TProjectPermission;
+
+type TClearMethodEnrollmentDTO = {
+ applicationId: string;
+ profileId: string;
+} & TProjectPermission;
+
+type TRevealEabSecretDTO = {
+ applicationId: string;
+ profileId: string;
+} & TProjectPermission;
+
+type TPkiApplicationEnrollmentServiceFactoryDep = {
+ pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
+ pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findOne" | "transaction" | "update">;
+ apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "create" | "updateById" | "deleteById" | "findById">;
+ estEnrollmentConfigDAL: Pick<TEstEnrollmentConfigDALFactory, "create" | "updateById" | "deleteById" | "findById">;
+ acmeEnrollmentConfigDAL: Pick<TAcmeEnrollmentConfigDALFactory, "create" | "updateById" | "deleteById" | "findById">;
+ scepEnrollmentConfigDAL: Pick<TScepEnrollmentConfigDALFactory, "create" | "updateById" | "deleteById" | "findById">;
+ kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
+ permissionService: Pick<TPermissionServiceFactory, "getResourcePermission">;
+};
+
+export type TPkiApplicationEnrollmentServiceFactory = ReturnType<typeof pkiApplicationEnrollmentServiceFactory>;
+
+export const pkiApplicationEnrollmentServiceFactory = ({
+ pkiApplicationDAL,
+ pkiApplicationProfileDAL,
+ apiEnrollmentConfigDAL,
+ estEnrollmentConfigDAL,
+ acmeEnrollmentConfigDAL,
+ scepEnrollmentConfigDAL,
+ kmsService,
+ projectDAL,
+ permissionService
+}: TPkiApplicationEnrollmentServiceFactoryDep) => {
+ const $loadJunction = async (applicationId: string, profileId: string, projectId: string) => {
+ const application = await pkiApplicationDAL.findById(applicationId);
+ if (!application || application.projectId !== projectId) {
+ throw new NotFoundError({ message: `Application with id '${applicationId}' not found.` });
+ }
+
+ const junction = await pkiApplicationProfileDAL.findOne(applicationId, profileId);
+ if (!junction) {
+ throw new NotFoundError({
+ message: `Profile '${profileId}' is not attached to application '${applicationId}'.`
+ });
+ }
+
+ return { junction };
+ };
+
+ const $assertEditEnrollment = async (
+ applicationId: string,
+ profileId: string,
+ projectId: string,
+ actor: TProjectPermission["actor"],
+ actorId: TProjectPermission["actorId"],
+ actorAuthMethod: TProjectPermission["actorAuthMethod"],
+ actorOrgId: TProjectPermission["actorOrgId"]
+ ) => {
+ const { junction } = await $loadJunction(applicationId, profileId, projectId);
+ const { permission } = await permissionService.getResourcePermission({
+ actor,
+ actorId,
+ projectId,
+ resourceType: ResourceType.CertificateApplication,
+ resourceId: applicationId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Edit,
+ ResourcePermissionSub.Application
+ );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationEnrollmentActions.Edit,
+ ResourcePermissionSub.ApplicationEnrollment
+ );
+ return { junction };
+ };
+
+ const getEnrollment = async ({
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TGetEnrollmentDTO) => {
+ const { junction } = await $loadJunction(applicationId, profileId, projectId);
+
+ const { permission } = await permissionService.getResourcePermission({
+ actor,
+ actorId,
+ projectId,
+ resourceType: ResourceType.CertificateApplication,
+ resourceId: applicationId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Read,
+ ResourcePermissionSub.Application
+ );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationEnrollmentActions.Read,
+ ResourcePermissionSub.ApplicationEnrollment
+ );
+
+ const apiConfig = junction.apiConfigId ? await apiEnrollmentConfigDAL.findById(junction.apiConfigId) : null;
+ const acmeConfig = junction.acmeConfigId ? await acmeEnrollmentConfigDAL.findById(junction.acmeConfigId) : null;
+ const estConfig = junction.estConfigId ? await estEnrollmentConfigDAL.findById(junction.estConfigId) : null;
+ const scepConfig = junction.scepConfigId ? await scepEnrollmentConfigDAL.findById(junction.scepConfigId) : null;
+
+ return {
+ applicationId,
+ profileId,
+ api: apiConfig
+ ? {
+ id: apiConfig.id,
+ autoRenew: Boolean(apiConfig.autoRenew),
+ renewBeforeDays: apiConfig.renewBeforeDays ?? null
+ }
+ : null,
+ est: estConfig
+ ? {
+ id: estConfig.id,
+ disableBootstrapCaValidation: Boolean(estConfig.disableBootstrapCaValidation)
+ }
+ : null,
+ acme: acmeConfig
+ ? {
+ id: acmeConfig.id,
+ skipDnsOwnershipVerification: Boolean(acmeConfig.skipDnsOwnershipVerification),
+ skipEabBinding: Boolean(acmeConfig.skipEabBinding)
+ }
+ : null,
+ scep: scepConfig
+ ? {
+ id: scepConfig.id,
+ challengeType: scepConfig.challengeType as ScepChallengeType,
+ includeCaCertInResponse: Boolean(scepConfig.includeCaCertInResponse),
+ allowCertBasedRenewal: Boolean(scepConfig.allowCertBasedRenewal),
+ dynamicChallengeExpiryMinutes: scepConfig.dynamicChallengeExpiryMinutes ?? null,
+ dynamicChallengeMaxPending: scepConfig.dynamicChallengeMaxPending ?? null
+ }
+ : null,
+ estConfigured: Boolean(junction.estConfigId),
+ acmeConfigured: Boolean(junction.acmeConfigId),
+ scepConfigured: Boolean(junction.scepConfigId)
+ };
+ };
+
+ const setApiEnrollment = async ({
+ applicationId,
+ profileId,
+ config,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TSetApiEnrollmentDTO) => {
+ const { junction } = await $assertEditEnrollment(
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ );
+
+ if (config.autoRenew && (config.renewBeforeDays === undefined || config.renewBeforeDays === null)) {
+ throw new BadRequestError({ message: "renewBeforeDays is required when autoRenew is true." });
+ }
+
+ return pkiApplicationProfileDAL.transaction(async (tx) => {
+ let { apiConfigId } = junction;
+
+ if (apiConfigId) {
+ await apiEnrollmentConfigDAL.updateById(
+ apiConfigId,
+ {
+ autoRenew: config.autoRenew ?? false,
+ renewBeforeDays: config.renewBeforeDays ?? null
+ },
+ tx
+ );
+ } else {
+ const created = await apiEnrollmentConfigDAL.create(
+ {
+ autoRenew: config.autoRenew ?? false,
+ renewBeforeDays: config.renewBeforeDays ?? null
+ },
+ tx
+ );
+ apiConfigId = created.id;
+ await pkiApplicationProfileDAL.update({ applicationId, profileId }, { apiConfigId }, tx);
+ }
+
+ const apiConfig = await apiEnrollmentConfigDAL.findById(apiConfigId, tx);
+ if (!apiConfig) {
+ throw new NotFoundError({ message: "API enrollment config not found after upsert." });
+ }
+ return {
+ applicationId,
+ profileId,
+ api: {
+ id: apiConfig.id,
+ autoRenew: Boolean(apiConfig.autoRenew),
+ renewBeforeDays: (apiConfig.renewBeforeDays as number | null) ?? null
+ }
+ };
+ });
+ };
+
+ const clearApiEnrollment = async ({
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TClearApiEnrollmentDTO) => {
+ const { junction } = await $assertEditEnrollment(
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ );
+
+ if (!junction.apiConfigId) {
+ return { applicationId, profileId };
+ }
+
+ await pkiApplicationProfileDAL.transaction(async (tx) => {
+ await pkiApplicationProfileDAL.update({ applicationId, profileId }, { apiConfigId: null }, tx);
+ await apiEnrollmentConfigDAL.deleteById(junction.apiConfigId as string, tx);
+ });
+
+ return { applicationId, profileId };
+ };
+
+ const setEstEnrollment = async ({
+ applicationId,
+ profileId,
+ config,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TSetEstEnrollmentDTO) => {
+ const { junction } = await $assertEditEnrollment(
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ );
+
+ if (!config.passphrase || config.passphrase.length < 8) {
+ throw new BadRequestError({ message: "EST passphrase must be at least 8 characters." });
+ }
+
+ const appCfg = getConfig();
+ const hashedPassphrase = await crypto.hashing().createHash(config.passphrase, appCfg.SALT_ROUNDS);
+
+ let encryptedCaChain: Buffer | null = null;
+ if (!config.disableBootstrapCaValidation && config.caChain) {
+ const result = await validateAndEncryptPemCaChain(config.caChain, projectId, kmsService, projectDAL);
+ encryptedCaChain = result.encryptedCaChain;
+ }
+
+ return pkiApplicationProfileDAL.transaction(async (tx) => {
+ let { estConfigId } = junction;
+ if (estConfigId) {
+ await estEnrollmentConfigDAL.updateById(
+ estConfigId,
+ {
+ disableBootstrapCaValidation: config.disableBootstrapCaValidation ?? false,
+ hashedPassphrase,
+ encryptedCaChain
+ },
+ tx
+ );
+ } else {
+ const created = await estEnrollmentConfigDAL.create(
+ {
+ disableBootstrapCaValidation: config.disableBootstrapCaValidation ?? false,
+ hashedPassphrase,
+ encryptedCaChain
+ },
+ tx
+ );
+ estConfigId = created.id;
+ await pkiApplicationProfileDAL.update({ applicationId, profileId }, { estConfigId }, tx);
+ }
+ return {
+ applicationId,
+ profileId,
+ est: { id: estConfigId, disableBootstrapCaValidation: config.disableBootstrapCaValidation ?? false }
+ };
+ });
+ };
+
+ const clearEstEnrollment = async ({
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TClearMethodEnrollmentDTO) => {
+ const { junction } = await $assertEditEnrollment(
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ );
+ if (!junction.estConfigId) return { applicationId, profileId };
+ await pkiApplicationProfileDAL.transaction(async (tx) => {
+ await pkiApplicationProfileDAL.update({ applicationId, profileId }, { estConfigId: null }, tx);
+ await estEnrollmentConfigDAL.deleteById(junction.estConfigId as string, tx);
+ });
+ return { applicationId, profileId };
+ };
+
+ const setAcmeEnrollment = async ({
+ applicationId,
+ profileId,
+ config,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TSetAcmeEnrollmentDTO) => {
+ const { junction } = await $assertEditEnrollment(
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ );
+
+ if (config.skipDnsOwnershipVerification && config.skipEabBinding) {
+ throw new BadRequestError({
+ message: "skipDnsOwnershipVerification and skipEabBinding cannot both be enabled — pick at most one."
+ });
+ }
+
+ return pkiApplicationProfileDAL.transaction(async (tx) => {
+ let { acmeConfigId } = junction;
+ if (acmeConfigId) {
+ await acmeEnrollmentConfigDAL.updateById(
+ acmeConfigId,
+ {
+ skipDnsOwnershipVerification: config.skipDnsOwnershipVerification ?? false,
+ skipEabBinding: config.skipEabBinding ?? false
+ },
+ tx
+ );
+ } else {
+ const { encryptedEabSecret } = await generateAndEncryptAcmeEabSecret(projectId, kmsService, projectDAL);
+ const created = await acmeEnrollmentConfigDAL.create(
+ {
+ skipDnsOwnershipVerification: config.skipDnsOwnershipVerification ?? false,
+ skipEabBinding: config.skipEabBinding ?? false,
+ encryptedEabSecret
+ },
+ tx
+ );
+ acmeConfigId = created.id;
+ await pkiApplicationProfileDAL.update({ applicationId, profileId }, { acmeConfigId }, tx);
+ }
+ return {
+ applicationId,
+ profileId,
+ acme: {
+ id: acmeConfigId,
+ skipDnsOwnershipVerification: config.skipDnsOwnershipVerification ?? false,
+ skipEabBinding: config.skipEabBinding ?? false
+ }
+ };
+ });
+ };
+
+ const clearAcmeEnrollment = async ({
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TClearMethodEnrollmentDTO) => {
+ const { junction } = await $assertEditEnrollment(
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ );
+ if (!junction.acmeConfigId) return { applicationId, profileId };
+ await pkiApplicationProfileDAL.transaction(async (tx) => {
+ await pkiApplicationProfileDAL.update({ applicationId, profileId }, { acmeConfigId: null }, tx);
+ await acmeEnrollmentConfigDAL.deleteById(junction.acmeConfigId as string, tx);
+ });
+ return { applicationId, profileId };
+ };
+
+ const revealAcmeEabSecret = async ({
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TRevealEabSecretDTO) => {
+ const { junction } = await $loadJunction(applicationId, profileId, projectId);
+ const { permission } = await permissionService.getResourcePermission({
+ actor,
+ actorId,
+ projectId,
+ resourceType: ResourceType.CertificateApplication,
+ resourceId: applicationId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Read,
+ ResourcePermissionSub.Application
+ );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationEnrollmentActions.RevealAcmeEabSecret,
+ ResourcePermissionSub.ApplicationEnrollment
+ );
+
+ if (!junction.acmeConfigId) {
+ throw new NotFoundError({ message: "ACME enrollment is not configured for this profile." });
+ }
+ const acmeConfig = await acmeEnrollmentConfigDAL.findById(junction.acmeConfigId);
+ if (!acmeConfig?.encryptedEabSecret) {
+ throw new NotFoundError({ message: "ACME EAB secret is not available." });
+ }
+
+ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({ projectId, projectDAL, kmsService });
+ const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId: certificateManagerKmsId });
+ const eabSecret = await kmsDecryptor({ cipherTextBlob: acmeConfig.encryptedEabSecret });
+
+ return {
+ applicationId,
+ profileId,
+ eabKid: acmeConfig.id,
+ eabSecret: eabSecret.toString("base64url")
+ };
+ };
+
+ const rotateAcmeEabSecret = async ({
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TRevealEabSecretDTO) => {
+ const { junction } = await $loadJunction(applicationId, profileId, projectId);
+ const { permission } = await permissionService.getResourcePermission({
+ actor,
+ actorId,
+ projectId,
+ resourceType: ResourceType.CertificateApplication,
+ resourceId: applicationId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Edit,
+ ResourcePermissionSub.Application
+ );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationEnrollmentActions.RotateAcmeEabSecret,
+ ResourcePermissionSub.ApplicationEnrollment
+ );
+
+ if (!junction.acmeConfigId) {
+ throw new NotFoundError({ message: "ACME enrollment is not configured for this profile." });
+ }
+ const { encryptedEabSecret } = await generateAndEncryptAcmeEabSecret(projectId, kmsService, projectDAL);
+ await acmeEnrollmentConfigDAL.updateById(junction.acmeConfigId, { encryptedEabSecret });
+ return { applicationId, profileId };
+ };
+
+ const setScepEnrollment = async ({
+ applicationId,
+ profileId,
+ config,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TSetScepEnrollmentDTO) => {
+ const { junction } = await $assertEditEnrollment(
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ );
+
+ const challengeType = config.challengeType ?? ScepChallengeType.STATIC;
+ const appCfg = getConfig();
+ let hashedChallengePassword: string | null = null;
+ if (challengeType === ScepChallengeType.STATIC) {
+ if (!config.challengePassword) {
+ throw new BadRequestError({ message: "challengePassword is required for static SCEP challenges." });
+ }
+ hashedChallengePassword = await crypto.hashing().createHash(config.challengePassword, appCfg.SALT_ROUNDS);
+ }
+
+ const raCert = await generateRaCertificate(`app-${applicationId}-${profileId}`);
+ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({ projectId, projectDAL, kmsService });
+ const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKmsId });
+ const { cipherTextBlob: encryptedRaPrivateKey } = await kmsEncryptor({
+ plainText: Buffer.from(raCert.privateKeyDer)
+ });
+
+ return pkiApplicationProfileDAL.transaction(async (tx) => {
+ let { scepConfigId } = junction;
+ const dynamicChallengeExpiryMinutes =
+ challengeType === ScepChallengeType.DYNAMIC ? (config.dynamicChallengeExpiryMinutes ?? 60) : null;
+ const dynamicChallengeMaxPending =
+ challengeType === ScepChallengeType.DYNAMIC ? (config.dynamicChallengeMaxPending ?? 100) : null;
+
+ if (scepConfigId) {
+ await scepEnrollmentConfigDAL.updateById(
+ scepConfigId,
+ {
+ encryptedRaPrivateKey,
+ raCertificate: raCert.certificatePem,
+ raCertExpiresAt: raCert.expiresAt,
+ hashedChallengePassword,
+ challengeType,
+ includeCaCertInResponse: config.includeCaCertInResponse ?? true,
+ allowCertBasedRenewal: config.allowCertBasedRenewal ?? true,
+ dynamicChallengeExpiryMinutes,
+ dynamicChallengeMaxPending
+ },
+ tx
+ );
+ } else {
+ const created = await scepEnrollmentConfigDAL.create(
+ {
+ encryptedRaPrivateKey,
+ raCertificate: raCert.certificatePem,
+ raCertExpiresAt: raCert.expiresAt,
+ hashedChallengePassword,
+ challengeType,
+ includeCaCertInResponse: config.includeCaCertInResponse ?? true,
+ allowCertBasedRenewal: config.allowCertBasedRenewal ?? true,
+ dynamicChallengeExpiryMinutes,
+ dynamicChallengeMaxPending
+ },
+ tx
+ );
+ scepConfigId = created.id;
+ await pkiApplicationProfileDAL.update({ applicationId, profileId }, { scepConfigId }, tx);
+ }
+ return { applicationId, profileId, scep: { id: scepConfigId, challengeType } };
+ });
+ };
+
+ const clearScepEnrollment = async ({
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TClearMethodEnrollmentDTO) => {
+ const { junction } = await $assertEditEnrollment(
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ );
+ if (!junction.scepConfigId) return { applicationId, profileId };
+ await pkiApplicationProfileDAL.transaction(async (tx) => {
+ await pkiApplicationProfileDAL.update({ applicationId, profileId }, { scepConfigId: null }, tx);
+ await scepEnrollmentConfigDAL.deleteById(junction.scepConfigId as string, tx);
+ });
+ return { applicationId, profileId };
+ };
+
+ return {
+ getEnrollment,
+ setApiEnrollment,
+ clearApiEnrollment,
+ setEstEnrollment,
+ clearEstEnrollment,
+ setAcmeEnrollment,
+ clearAcmeEnrollment,
+ revealAcmeEabSecret,
+ rotateAcmeEabSecret,
+ setScepEnrollment,
+ clearScepEnrollment
+ };
+};
diff --git a/backend/src/services/pki-application/pki-application-membership-service.ts b/backend/src/services/pki-application/pki-application-membership-service.ts
new file mode 100644
index 0000000000..2854ce5c51
--- /dev/null
+++ b/backend/src/services/pki-application/pki-application-membership-service.ts
@@ -0,0 +1,378 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { AccessScope, ApplicationMembershipRole, RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";
+import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { ProjectPermissionMemberActions } from "@app/ee/services/permission/project-permission";
+import {
+ ResourcePermissionApplicationActions,
+ ResourcePermissionSub
+} from "@app/ee/services/permission/resource-permission";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+
+import { TIdentityDALFactory } from "../identity/identity-dal";
+import { TMembershipDALFactory } from "../membership/membership-dal";
+import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
+import { TUserDALFactory } from "../user/user-dal";
+import { TPkiApplicationDALFactory } from "./pki-application-dal";
+import {
+ TAddApplicationMemberDTO,
+ TApplicationMember,
+ TListApplicationMembersDTO,
+ TRemoveApplicationMemberDTO,
+ TUpdateApplicationMemberRoleDTO
+} from "./pki-application-types";
+
+type TPkiApplicationMembershipServiceFactoryDep = {
+ pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
+ membershipDAL: Pick<TMembershipDALFactory, "create" | "findById" | "find" | "deleteById" | "transaction">;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "find" | "delete" | "update">;
+ permissionService: Pick<TPermissionServiceFactory, "getResourcePermission">;
+ userDAL: Pick<TUserDALFactory, "find">;
+ identityDAL: Pick<TIdentityDALFactory, "find">;
+ groupDAL: Pick<TGroupDALFactory, "find">;
+};
+
+export type TPkiApplicationMembershipServiceFactory = ReturnType<typeof pkiApplicationMembershipServiceFactory>;
+
+const VALID_BUILTIN_ROLES = new Set<string>([
+ ApplicationMembershipRole.Admin,
+ ApplicationMembershipRole.Operator,
+ ApplicationMembershipRole.Auditor
+]);
+
+const isBuiltInApplicationRole = (role: string) => VALID_BUILTIN_ROLES.has(role);
+
+export const pkiApplicationMembershipServiceFactory = ({
+ pkiApplicationDAL,
+ membershipDAL,
+ membershipRoleDAL,
+ permissionService,
+ userDAL,
+ identityDAL,
+ groupDAL
+}: TPkiApplicationMembershipServiceFactoryDep) => {
+ const $loadApplicationOrThrow = async (applicationId: string, projectId: string) => {
+ const application = await pkiApplicationDAL.findById(applicationId);
+ if (!application || application.projectId !== projectId) {
+ throw new NotFoundError({ message: `Application with id '${applicationId}' not found.` });
+ }
+ return application;
+ };
+
+ const $assertActorPresentInProject = async (
+ projectId: string,
+ actor: { userId?: string; identityId?: string; groupId?: string }
+ ) => {
+ const setActors = [actor.userId, actor.identityId, actor.groupId].filter(Boolean);
+ if (setActors.length !== 1) {
+ throw new BadRequestError({
+ message: "Exactly one of userId, identityId, or groupId must be provided."
+ });
+ }
+
+ const where: Record<string, unknown> = {
+ scope: AccessScope.Project,
+ scopeProjectId: projectId
+ };
+ if (actor.userId) where.actorUserId = actor.userId;
+ else if (actor.identityId) where.actorIdentityId = actor.identityId;
+ else if (actor.groupId) where.actorGroupId = actor.groupId;
+
+ const projectMembership = await membershipDAL.find(where);
+ if (!projectMembership.length) {
+ throw new BadRequestError({
+ message: "The actor is not a member of this project. Add them at the project level first."
+ });
+ }
+ return projectMembership[0];
+ };
+
+ const $loadResourcePermission = (
+ applicationId: string,
+ projectId: string,
+ ctx: {
+ actor: TAddApplicationMemberDTO["actor"];
+ actorId: string;
+ actorAuthMethod: TAddApplicationMemberDTO["actorAuthMethod"];
+ actorOrgId?: string;
+ }
+ ) =>
+ permissionService.getResourcePermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ resourceType: ResourceType.CertificateApplication,
+ resourceId: applicationId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId
+ });
+
+ const addMember = async ({
+ applicationId,
+ userId,
+ identityId,
+ groupId,
+ role,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TAddApplicationMemberDTO): Promise<TApplicationMember> => {
+ await $loadApplicationOrThrow(applicationId, projectId);
+
+ const { permission } = await $loadResourcePermission(applicationId, projectId, {
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Edit,
+ ResourcePermissionSub.Application
+ );
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Create, ResourcePermissionSub.Member);
+
+ if (!isBuiltInApplicationRole(role)) {
+ throw new BadRequestError({
+ message: `Unknown application role '${role}'. Expected one of: admin, operator, auditor.`
+ });
+ }
+
+ const projectMembership = await $assertActorPresentInProject(projectId, { userId, identityId, groupId });
+
+ return membershipDAL.transaction(async (tx) => {
+ const newMembership = await membershipDAL.create(
+ {
+ scope: RESOURCE_SCOPE,
+ scopeOrgId: projectMembership.scopeOrgId,
+ scopeProjectId: projectId,
+ actorUserId: userId ?? null,
+ actorIdentityId: identityId ?? null,
+ actorGroupId: groupId ?? null,
+ scopeResourceType: ResourceType.CertificateApplication,
+ scopeResourceId: applicationId,
+ isActive: true
+ },
+ tx
+ );
+
+ const newRole = await membershipRoleDAL.create(
+ {
+ membershipId: newMembership.id,
+ role
+ },
+ tx
+ );
+
+ return {
+ membershipId: newMembership.id,
+ applicationId,
+ actorUserId: newMembership.actorUserId ?? null,
+ actorIdentityId: newMembership.actorIdentityId ?? null,
+ actorGroupId: newMembership.actorGroupId ?? null,
+ role: newRole.role,
+ customRoleId: newRole.customRoleId ?? null,
+ createdAt: newMembership.createdAt,
+ updatedAt: newMembership.updatedAt
+ };
+ });
+ };
+
+ const listMembers = async ({
+ applicationId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TListApplicationMembersDTO): Promise<TApplicationMember[]> => {
+ await $loadApplicationOrThrow(applicationId, projectId);
+
+ const { permission } = await $loadResourcePermission(applicationId, projectId, {
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Read,
+ ResourcePermissionSub.Application
+ );
+
+ const memberships = await membershipDAL.find({
+ scope: RESOURCE_SCOPE,
+ scopeProjectId: projectId,
+ scopeResourceType: ResourceType.CertificateApplication,
+ scopeResourceId: applicationId
+ });
+
+ if (memberships.length === 0) return [];
+
+ const roles = await membershipRoleDAL.find({
+ $in: { membershipId: memberships.map((m) => m.id) }
+ });
+ const rolesByMembership = new Map<string, (typeof roles)[number]>();
+ for (const r of roles) rolesByMembership.set(r.membershipId, r);
+
+ const userIds = memberships.map((m) => m.actorUserId).filter((v): v is string => Boolean(v));
+ const identityIds = memberships.map((m) => m.actorIdentityId).filter((v): v is string => Boolean(v));
+ const groupIds = memberships.map((m) => m.actorGroupId).filter((v): v is string => Boolean(v));
+
+ const [users, identities, groups] = await Promise.all([
+ userIds.length > 0 ? userDAL.find({ $in: { id: userIds } }) : Promise.resolve([]),
+ identityIds.length > 0 ? identityDAL.find({ $in: { id: identityIds } }) : Promise.resolve([]),
+ groupIds.length > 0 ? groupDAL.find({ $in: { id: groupIds } }) : Promise.resolve([])
+ ]);
+
+ const userById = new Map(users.map((u) => [u.id, u]));
+ const identityById = new Map(identities.map((i) => [i.id, i]));
+ const groupById = new Map(groups.map((g) => [g.id, g]));
+
+ return memberships.map((m) => {
+ const r = rolesByMembership.get(m.id);
+
+ let details: TApplicationMember["details"] = null;
+ if (m.actorUserId) {
+ const u = userById.get(m.actorUserId);
+ if (u) {
+ const fullName = [u.firstName, u.lastName].filter((p): p is string => Boolean(p?.trim())).join(" ") || null;
+ details = {
+ name: fullName,
+ email: u.email ?? null,
+ username: u.username ?? null
+ };
+ }
+ } else if (m.actorIdentityId) {
+ const i = identityById.get(m.actorIdentityId);
+ if (i) {
+ details = { name: i.name, authMethod: i.authMethod ?? null };
+ }
+ } else if (m.actorGroupId) {
+ const g = groupById.get(m.actorGroupId);
+ if (g) {
+ details = { name: g.name, slug: g.slug };
+ }
+ }
+
+ return {
+ membershipId: m.id,
+ applicationId,
+ actorUserId: m.actorUserId ?? null,
+ actorIdentityId: m.actorIdentityId ?? null,
+ actorGroupId: m.actorGroupId ?? null,
+ role: r?.role ?? "",
+ customRoleId: r?.customRoleId ?? null,
+ createdAt: m.createdAt,
+ updatedAt: m.updatedAt,
+ details
+ };
+ });
+ };
+
+ const updateMemberRole = async ({
+ applicationId,
+ membershipId,
+ role,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TUpdateApplicationMemberRoleDTO): Promise<TApplicationMember> => {
+ await $loadApplicationOrThrow(applicationId, projectId);
+
+ const { permission } = await $loadResourcePermission(applicationId, projectId, {
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Edit,
+ ResourcePermissionSub.Application
+ );
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Edit, ResourcePermissionSub.Member);
+
+ if (!isBuiltInApplicationRole(role)) {
+ throw new BadRequestError({
+ message: `Unknown application role '${role}'. Expected one of: admin, operator, auditor.`
+ });
+ }
+
+ const membership = await membershipDAL.findById(membershipId);
+ if (
+ !membership ||
+ membership.scopeResourceType !== ResourceType.CertificateApplication ||
+ membership.scopeResourceId !== applicationId ||
+ membership.scopeProjectId !== projectId
+ ) {
+ throw new NotFoundError({ message: `Membership with id '${membershipId}' not found on this application.` });
+ }
+
+ return membershipDAL.transaction(async (tx) => {
+ const updatedRoles = await membershipRoleDAL.update({ membershipId }, { role, customRoleId: null }, tx);
+ const updated = updatedRoles[0];
+
+ return {
+ membershipId,
+ applicationId,
+ actorUserId: membership.actorUserId ?? null,
+ actorIdentityId: membership.actorIdentityId ?? null,
+ actorGroupId: membership.actorGroupId ?? null,
+ role: updated.role,
+ customRoleId: updated.customRoleId ?? null,
+ createdAt: membership.createdAt,
+ updatedAt: membership.updatedAt
+ };
+ });
+ };
+
+ const removeMember = async ({
+ applicationId,
+ membershipId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TRemoveApplicationMemberDTO): Promise<{ membershipId: string; applicationId: string }> => {
+ await $loadApplicationOrThrow(applicationId, projectId);
+
+ const { permission } = await $loadResourcePermission(applicationId, projectId, {
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Edit,
+ ResourcePermissionSub.Application
+ );
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Delete, ResourcePermissionSub.Member);
+
+ const membership = await membershipDAL.findById(membershipId);
+ if (
+ !membership ||
+ membership.scopeResourceType !== ResourceType.CertificateApplication ||
+ membership.scopeResourceId !== applicationId ||
+ membership.scopeProjectId !== projectId
+ ) {
+ throw new NotFoundError({ message: `Membership with id '${membershipId}' not found on this application.` });
+ }
+
+ await membershipDAL.transaction(async (tx) => {
+ await membershipRoleDAL.delete({ membershipId }, tx);
+ await membershipDAL.deleteById(membershipId, tx);
+ });
+
+ return { membershipId, applicationId };
+ };
+
+ return { addMember, listMembers, updateMemberRole, removeMember };
+};
diff --git a/backend/src/services/pki-application/pki-application-profile-dal.ts b/backend/src/services/pki-application/pki-application-profile-dal.ts
new file mode 100644
index 0000000000..9d9f7c30cb
--- /dev/null
+++ b/backend/src/services/pki-application/pki-application-profile-dal.ts
@@ -0,0 +1,113 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify } from "@app/lib/knex";
+
+import { TPkiApplicationProfile } from "./pki-application-types";
+
+export type TPkiApplicationProfileDALFactory = ReturnType<typeof pkiApplicationProfileDALFactory>;
+
+export const pkiApplicationProfileDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PkiApplicationProfile);
+
+ const findByApplicationId = async (applicationId: string, tx?: Knex): Promise<TPkiApplicationProfile[]> => {
+ try {
+ const rows = await (tx || db.replicaNode())(TableName.PkiApplicationProfile)
+ .innerJoin(
+ TableName.PkiCertificateProfile,
+ `${TableName.PkiApplicationProfile}.profileId`,
+ `${TableName.PkiCertificateProfile}.id`
+ )
+ .where(`${TableName.PkiApplicationProfile}.applicationId`, applicationId)
+ .select(
+ `${TableName.PkiApplicationProfile}.applicationId`,
+ `${TableName.PkiApplicationProfile}.profileId`,
+ `${TableName.PkiCertificateProfile}.slug as profileSlug`,
+ `${TableName.PkiCertificateProfile}.description as profileDescription`,
+ `${TableName.PkiApplicationProfile}.estConfigId`,
+ `${TableName.PkiApplicationProfile}.apiConfigId`,
+ `${TableName.PkiApplicationProfile}.acmeConfigId`,
+ `${TableName.PkiApplicationProfile}.scepConfigId`,
+ `${TableName.PkiApplicationProfile}.createdAt`,
+ `${TableName.PkiApplicationProfile}.updatedAt`
+ )
+ .orderBy(`${TableName.PkiApplicationProfile}.createdAt`, "desc");
+
+ return rows as TPkiApplicationProfile[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "List application profiles" });
+ }
+ };
+
+ const findOne = async (applicationId: string, profileId: string, tx?: Knex) => {
+ try {
+ const row = await (tx || db.replicaNode())(TableName.PkiApplicationProfile)
+ .where({ applicationId, profileId })
+ .first();
+ return row;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find application profile" });
+ }
+ };
+
+ const findProfilesInProject = async (profileIds: string[], projectId: string, tx?: Knex) => {
+ try {
+ const rows = await (tx || db.replicaNode())(TableName.PkiCertificateProfile)
+ .whereIn("id", profileIds)
+ .andWhere({ projectId });
+ return rows;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find profiles in project" });
+ }
+ };
+
+ const findByProfileId = async (profileId: string, tx?: Knex) => {
+ try {
+ const row = await (tx || db.replicaNode())(TableName.PkiApplicationProfile).where({ profileId }).first();
+ return row;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find application junction by profile" });
+ }
+ };
+
+ const findAllByProfileId = async (profileId: string, tx?: Knex) => {
+ try {
+ const rows = await (tx || db.replicaNode())(TableName.PkiApplicationProfile).where({ profileId });
+ return rows as Array<{
+ applicationId: string;
+ profileId: string;
+ apiConfigId?: string | null;
+ estConfigId?: string | null;
+ acmeConfigId?: string | null;
+ scepConfigId?: string | null;
+ }>;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find all application junctions for profile" });
+ }
+ };
+
+ const findOtherJunctionsForProfiles = async (profileIds: string[], excludeApplicationId: string, tx?: Knex) => {
+ try {
+ if (profileIds.length === 0) return [];
+ const rows = await (tx || db.replicaNode())(TableName.PkiApplicationProfile)
+ .whereIn("profileId", profileIds)
+ .whereNot({ applicationId: excludeApplicationId })
+ .select("profileId", "applicationId");
+ return rows as { profileId: string; applicationId: string }[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find other junctions for profiles" });
+ }
+ };
+
+ return {
+ ...orm,
+ findAllByProfileId,
+ findByApplicationId,
+ findOne,
+ findProfilesInProject,
+ findOtherJunctionsForProfiles,
+ findByProfileId
+ };
+};
diff --git a/backend/src/services/pki-application/pki-application-service.ts b/backend/src/services/pki-application/pki-application-service.ts
new file mode 100644
index 0000000000..42ef4447ef
--- /dev/null
+++ b/backend/src/services/pki-application/pki-application-service.ts
@@ -0,0 +1,481 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { ActionProjectType, RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionApplicationActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import {
+ ResourcePermissionApplicationActions,
+ ResourcePermissionSub
+} from "@app/ee/services/permission/resource-permission";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { ActorType } from "@app/services/auth/auth-type";
+
+import { TMembershipDALFactory } from "../membership/membership-dal";
+import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
+import { TPkiApplicationDALFactory } from "./pki-application-dal";
+import { TPkiApplicationProfileDALFactory } from "./pki-application-profile-dal";
+import {
+ TAttachProfilesDTO,
+ TCreatePkiApplicationDTO,
+ TDeletePkiApplicationDTO,
+ TDetachProfileDTO,
+ TGetPkiApplicationBySlugDTO,
+ TGetPkiApplicationDTO,
+ TListApplicationProfilesDTO,
+ TListPkiApplicationsDTO,
+ TUpdatePkiApplicationDTO
+} from "./pki-application-types";
+
+type TPkiApplicationServiceFactoryDep = {
+ pkiApplicationDAL: Pick<
+ TPkiApplicationDALFactory,
+ | "create"
+ | "findById"
+ | "updateById"
+ | "deleteById"
+ | "transaction"
+ | "findBySlugAndProjectId"
+ | "findByProjectId"
+ | "countByProjectId"
+ >;
+ pkiApplicationProfileDAL: Pick<
+ TPkiApplicationProfileDALFactory,
+ | "insertMany"
+ | "delete"
+ | "findByApplicationId"
+ | "findOne"
+ | "findProfilesInProject"
+ | "findOtherJunctionsForProfiles"
+ >;
+ membershipDAL: Pick<TMembershipDALFactory, "find" | "delete">;
+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "delete">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
+};
+
+export type TPkiApplicationServiceFactory = ReturnType<typeof pkiApplicationServiceFactory>;
+
+export const pkiApplicationServiceFactory = ({
+ pkiApplicationDAL,
+ pkiApplicationProfileDAL,
+ membershipDAL,
+ membershipRoleDAL,
+ permissionService
+}: TPkiApplicationServiceFactoryDep) => {
+ const $loadProjectPermission = (
+ projectId: string,
+ ctx: {
+ actor: TCreatePkiApplicationDTO["actor"];
+ actorId: string;
+ actorAuthMethod: TCreatePkiApplicationDTO["actorAuthMethod"];
+ actorOrgId?: string;
+ }
+ ) =>
+ permissionService.getProjectPermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+
+ const $loadResourcePermission = (
+ applicationId: string,
+ projectId: string,
+ ctx: {
+ actor: TCreatePkiApplicationDTO["actor"];
+ actorId: string;
+ actorAuthMethod: TCreatePkiApplicationDTO["actorAuthMethod"];
+ actorOrgId?: string;
+ }
+ ) =>
+ permissionService.getResourcePermission({
+ actor: ctx.actor,
+ actorId: ctx.actorId,
+ projectId,
+ resourceType: ResourceType.CertificateApplication,
+ resourceId: applicationId,
+ actorAuthMethod: ctx.actorAuthMethod,
+ actorOrgId: ctx.actorOrgId
+ });
+
+ const createApplication = async ({
+ name,
+ slug,
+ description,
+ profileIds,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TCreatePkiApplicationDTO) => {
+ const { permission } = await $loadProjectPermission(projectId, { actor, actorId, actorAuthMethod, actorOrgId });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionApplicationActions.Create,
+ ProjectPermissionSub.Application
+ );
+
+ const existing = await pkiApplicationDAL.findBySlugAndProjectId(slug, projectId);
+ if (existing) {
+ throw new BadRequestError({ message: `An application with slug '${slug}' already exists in this project.` });
+ }
+
+ if (profileIds && profileIds.length > 0) {
+ const profilesInProject = await pkiApplicationProfileDAL.findProfilesInProject(profileIds, projectId);
+ if (profilesInProject.length !== profileIds.length) {
+ throw new BadRequestError({
+ message: "One or more profileIds do not belong to this project."
+ });
+ }
+ }
+
+ return pkiApplicationDAL.transaction(async (tx) => {
+ const application = await pkiApplicationDAL.create(
+ { projectId, name, slug, description: description ?? null },
+ tx
+ );
+
+ if (profileIds && profileIds.length > 0) {
+ await pkiApplicationProfileDAL.insertMany(
+ profileIds.map((profileId) => ({ applicationId: application.id, profileId })),
+ tx
+ );
+ }
+
+ return application;
+ });
+ };
+
+ const getApplicationById = async ({
+ applicationId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TGetPkiApplicationDTO) => {
+ const application = await pkiApplicationDAL.findById(applicationId);
+ if (!application || application.projectId !== projectId) {
+ throw new NotFoundError({ message: `Application with id '${applicationId}' not found.` });
+ }
+
+ const { permission } = await $loadResourcePermission(applicationId, projectId, {
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Read,
+ ResourcePermissionSub.Application
+ );
+
+ return application;
+ };
+
+ const getApplicationBySlug = async ({
+ slug,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TGetPkiApplicationBySlugDTO) => {
+ const application = await pkiApplicationDAL.findBySlugAndProjectId(slug, projectId);
+ if (!application) {
+ throw new NotFoundError({ message: `Application with slug '${slug}' not found in this project.` });
+ }
+
+ const { permission } = await $loadResourcePermission(application.id, projectId, {
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Read,
+ ResourcePermissionSub.Application
+ );
+
+ return application;
+ };
+
+ const listApplications = async ({
+ search,
+ limit,
+ offset,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TListPkiApplicationsDTO) => {
+ const { permission } = await $loadProjectPermission(projectId, { actor, actorId, actorAuthMethod, actorOrgId });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionApplicationActions.List,
+ ProjectPermissionSub.Application
+ );
+
+ const isProjectAdmin = permission.can(ProjectPermissionApplicationActions.Create, ProjectPermissionSub.Application);
+
+ if (isProjectAdmin) {
+ const applications = await pkiApplicationDAL.findByProjectId(projectId, { search, limit, offset });
+ const total = await pkiApplicationDAL.countByProjectId(projectId, search);
+ return { applications, total };
+ }
+
+ const memberships = await membershipDAL.find({
+ scope: RESOURCE_SCOPE,
+ scopeProjectId: projectId,
+ scopeResourceType: ResourceType.CertificateApplication,
+ ...(actor === ActorType.USER ? { actorUserId: actorId } : { actorIdentityId: actorId })
+ });
+
+ const allowedIds = Array.from(
+ new Set(memberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id)))
+ );
+
+ if (allowedIds.length === 0) {
+ return { applications: [], total: 0 };
+ }
+
+ const applications = await pkiApplicationDAL.findByProjectId(projectId, {
+ search,
+ limit,
+ offset,
+ applicationIds: allowedIds
+ });
+ const total = await pkiApplicationDAL.countByProjectId(projectId, search, undefined, allowedIds);
+ return { applications, total };
+ };
+
+ const updateApplication = async ({
+ applicationId,
+ name,
+ slug,
+ description,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TUpdatePkiApplicationDTO) => {
+ const application = await pkiApplicationDAL.findById(applicationId);
+ if (!application || application.projectId !== projectId) {
+ throw new NotFoundError({ message: `Application with id '${applicationId}' not found.` });
+ }
+
+ const { permission } = await $loadResourcePermission(applicationId, projectId, {
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Edit,
+ ResourcePermissionSub.Application
+ );
+
+ if (slug && slug !== application.slug) {
+ const collision = await pkiApplicationDAL.findBySlugAndProjectId(slug, projectId);
+ if (collision) {
+ throw new BadRequestError({ message: `An application with slug '${slug}' already exists in this project.` });
+ }
+ }
+
+ return pkiApplicationDAL.updateById(applicationId, {
+ ...(name !== undefined && { name }),
+ ...(slug !== undefined && { slug }),
+ ...(description !== undefined && { description })
+ });
+ };
+
+ const deleteApplication = async ({
+ applicationId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TDeletePkiApplicationDTO) => {
+ const application = await pkiApplicationDAL.findById(applicationId);
+ if (!application || application.projectId !== projectId) {
+ throw new NotFoundError({ message: `Application with id '${applicationId}' not found.` });
+ }
+
+ const { permission } = await $loadResourcePermission(applicationId, projectId, {
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Delete,
+ ResourcePermissionSub.Application
+ );
+
+ await pkiApplicationDAL.transaction(async (tx) => {
+ const orphans = await membershipDAL.find(
+ {
+ scope: RESOURCE_SCOPE,
+ scopeResourceType: ResourceType.CertificateApplication,
+ scopeResourceId: applicationId
+ },
+ { tx }
+ );
+ if (orphans.length > 0) {
+ const ids = orphans.map((m) => m.id);
+ await membershipRoleDAL.delete({ $in: { membershipId: ids } }, tx);
+ await membershipDAL.delete({ $in: { id: ids } }, tx);
+ }
+ await pkiApplicationDAL.deleteById(applicationId, tx);
+ });
+
+ return application;
+ };
+
+ const listApplicationProfiles = async ({
+ applicationId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TListApplicationProfilesDTO) => {
+ const application = await pkiApplicationDAL.findById(applicationId);
+ if (!application || application.projectId !== projectId) {
+ throw new NotFoundError({ message: `Application with id '${applicationId}' not found.` });
+ }
+
+ const { permission } = await $loadResourcePermission(applicationId, projectId, {
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.Read,
+ ResourcePermissionSub.Application
+ );
+
+ const profiles = await pkiApplicationProfileDAL.findByApplicationId(applicationId);
+ return profiles;
+ };
+
+ const attachProfiles = async ({
+ applicationId,
+ profileIds,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TAttachProfilesDTO) => {
+ const application = await pkiApplicationDAL.findById(applicationId);
+ if (!application || application.projectId !== projectId) {
+ throw new NotFoundError({ message: `Application with id '${applicationId}' not found.` });
+ }
+
+ const { permission } = await $loadResourcePermission(applicationId, projectId, {
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.AttachProfile,
+ ResourcePermissionSub.Application
+ );
+
+ const profilesInProject = await pkiApplicationProfileDAL.findProfilesInProject(profileIds, projectId);
+ if (profilesInProject.length !== profileIds.length) {
+ throw new BadRequestError({ message: "One or more profileIds do not belong to this project." });
+ }
+
+ return pkiApplicationDAL.transaction(async (tx) => {
+ const conflicts = await pkiApplicationProfileDAL.findOtherJunctionsForProfiles(profileIds, applicationId, tx);
+ if (conflicts.length > 0) {
+ const profilesByOtherApp = Array.from(new Set(conflicts.map((c) => c.profileId)));
+ throw new BadRequestError({
+ message:
+ `Profile(s) [${profilesByOtherApp.join(", ")}] are already attached to a different ` +
+ `Application. Each Profile can belong to one Application at a time — detach it first.`
+ });
+ }
+
+ const existing = await pkiApplicationProfileDAL.findByApplicationId(applicationId, tx);
+ const existingProfileIds = new Set(existing.map((row) => row.profileId));
+ const toAttach = profileIds.filter((id) => !existingProfileIds.has(id));
+
+ if (toAttach.length > 0) {
+ await pkiApplicationProfileDAL.insertMany(
+ toAttach.map((profileId) => ({ applicationId, profileId })),
+ tx
+ );
+ }
+
+ return pkiApplicationProfileDAL.findByApplicationId(applicationId, tx);
+ });
+ };
+
+ const detachProfile = async ({
+ applicationId,
+ profileId,
+ projectId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TDetachProfileDTO) => {
+ const application = await pkiApplicationDAL.findById(applicationId);
+ if (!application || application.projectId !== projectId) {
+ throw new NotFoundError({ message: `Application with id '${applicationId}' not found.` });
+ }
+
+ const { permission } = await $loadResourcePermission(applicationId, projectId, {
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ResourcePermissionApplicationActions.DetachProfile,
+ ResourcePermissionSub.Application
+ );
+
+ const link = await pkiApplicationProfileDAL.findOne(applicationId, profileId);
+ if (!link) {
+ throw new NotFoundError({
+ message: `Profile '${profileId}' is not attached to application '${applicationId}'.`
+ });
+ }
+
+ await pkiApplicationProfileDAL.delete({ applicationId, profileId });
+ return { applicationId, profileId };
+ };
+
+ return {
+ createApplication,
+ getApplicationById,
+ getApplicationBySlug,
+ listApplications,
+ updateApplication,
+ deleteApplication,
+ listApplicationProfiles,
+ attachProfiles,
+ detachProfile
+ };
+};
diff --git a/backend/src/services/pki-application/pki-application-types.ts b/backend/src/services/pki-application/pki-application-types.ts
new file mode 100644
index 0000000000..f94f7e1842
--- /dev/null
+++ b/backend/src/services/pki-application/pki-application-types.ts
@@ -0,0 +1,115 @@
+import { TProjectPermission } from "@app/lib/types";
+
+export type TPkiApplicationListItem = {
+ id: string;
+ projectId: string;
+ name: string;
+ slug: string;
+ description?: string | null;
+ profileCount: number;
+ memberCount: number;
+ certificateCount: number;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+export type TPkiApplicationProfile = {
+ applicationId: string;
+ profileId: string;
+ profileSlug: string;
+ profileDescription?: string | null;
+ estConfigId?: string | null;
+ apiConfigId?: string | null;
+ acmeConfigId?: string | null;
+ scepConfigId?: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+export type TCreatePkiApplicationDTO = {
+ name: string;
+ slug: string;
+ description?: string;
+ profileIds?: string[];
+} & TProjectPermission;
+
+export type TUpdatePkiApplicationDTO = {
+ applicationId: string;
+ name?: string;
+ slug?: string;
+ description?: string | null;
+} & TProjectPermission;
+
+export type TGetPkiApplicationDTO = {
+ applicationId: string;
+} & TProjectPermission;
+
+export type TGetPkiApplicationBySlugDTO = {
+ slug: string;
+} & TProjectPermission;
+
+export type TListPkiApplicationsDTO = {
+ search?: string;
+ limit?: number;
+ offset?: number;
+} & TProjectPermission;
+
+export type TDeletePkiApplicationDTO = {
+ applicationId: string;
+} & TProjectPermission;
+
+export type TAttachProfilesDTO = {
+ applicationId: string;
+ profileIds: string[];
+} & TProjectPermission;
+
+export type TDetachProfileDTO = {
+ applicationId: string;
+ profileId: string;
+} & TProjectPermission;
+
+export type TListApplicationProfilesDTO = {
+ applicationId: string;
+} & TProjectPermission;
+
+export type TApplicationMember = {
+ membershipId: string;
+ applicationId: string;
+ actorUserId?: string | null;
+ actorIdentityId?: string | null;
+ actorGroupId?: string | null;
+ role: string;
+ customRoleId?: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+ details?: {
+ name: string | null;
+ email?: string | null;
+ username?: string | null;
+ authMethod?: string | null;
+ slug?: string | null;
+ } | null;
+};
+
+export type TAddApplicationMemberDTO = {
+ applicationId: string;
+ userId?: string;
+ identityId?: string;
+ groupId?: string;
+ role: string;
+} & TProjectPermission;
+
+export type TListApplicationMembersDTO = {
+ applicationId: string;
+} & TProjectPermission;
+
+export type TUpdateApplicationMemberRoleDTO = {
+ applicationId: string;
+ membershipId: string;
+ role: string;
+} & TProjectPermission;
+
+export type TRemoveApplicationMemberDTO = {
+ applicationId: string;
+ membershipId: string;
+} & TProjectPermission;
diff --git a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts
index ba77eaeffd..c49f6e96ba 100644
--- a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts
@@ -67,7 +67,8 @@ export const CreateAwsCertificateManagerPkiSyncSchema = z.object({
syncOptions: AwsCertificateManagerPkiSyncOptionsSchema.optional().default({}),
subscriberId: z.string().nullish(),
connectionId: z.string(),
- projectId: z.string().trim().min(1),
+ projectId: z.string().trim().min(1).optional(),
+ applicationId: z.string().uuid().optional(),
certificateIds: z.array(z.string().uuid()).optional()
});
diff --git a/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-schemas.ts b/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-schemas.ts
index 672c3d0d15..7b96e9239d 100644
--- a/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/aws-elastic-load-balancer/aws-elastic-load-balancer-pki-sync-schemas.ts
@@ -41,7 +41,8 @@ export const CreateAwsElasticLoadBalancerPkiSyncSchema = z.object({
syncOptions: AwsElasticLoadBalancerPkiSyncOptionsSchema.optional().default({}),
subscriberId: z.string().nullish(),
connectionId: z.string(),
- projectId: z.string().trim().min(1),
+ projectId: z.string().trim().min(1).optional(),
+ applicationId: z.string().uuid().optional(),
certificateIds: z.array(z.string().uuid()).optional()
});
diff --git a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts
index a6a02a5237..85415583de 100644
--- a/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/aws-secrets-manager/aws-secrets-manager-pki-sync-schemas.ts
@@ -81,7 +81,8 @@ export const CreateAwsSecretsManagerPkiSyncSchema = z.object({
syncOptions: AwsSecretsManagerPkiSyncOptionsSchema.optional().default({}),
subscriberId: z.string().nullish(),
connectionId: z.string(),
- projectId: z.string().trim().min(1),
+ projectId: z.string().trim().min(1).optional(),
+ applicationId: z.string().uuid().optional(),
certificateIds: z.array(z.string().uuid()).optional()
});
diff --git a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts
index 5624fa1d3c..20fd909c9e 100644
--- a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts
@@ -54,7 +54,8 @@ export const CreateAzureKeyVaultPkiSyncSchema = z.object({
syncOptions: AzureKeyVaultPkiSyncOptionsSchema.optional().default({}),
subscriberId: z.string().nullish(),
connectionId: z.string(),
- projectId: z.string().trim().min(1),
+ projectId: z.string().trim().min(1).optional(),
+ applicationId: z.string().uuid().optional(),
certificateIds: z.array(z.string().uuid()).optional()
});
diff --git a/backend/src/services/pki-sync/chef/chef-pki-sync-schemas.ts b/backend/src/services/pki-sync/chef/chef-pki-sync-schemas.ts
index a7bc55905c..726204f1b5 100644
--- a/backend/src/services/pki-sync/chef/chef-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/chef/chef-pki-sync-schemas.ts
@@ -88,7 +88,8 @@ export const CreateChefPkiSyncSchema = z.object({
syncOptions: ChefPkiSyncOptionsSchema.optional().default({}),
subscriberId: z.string().nullish(),
connectionId: z.string(),
- projectId: z.string().trim().min(1),
+ projectId: z.string().trim().min(1).optional(),
+ applicationId: z.string().uuid().optional(),
certificateIds: z.array(z.string().uuid()).optional()
});
diff --git a/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts b/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts
index b84f89ae0f..e762c9b13d 100644
--- a/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/cloudflare-custom-certificate/cloudflare-custom-certificate-pki-sync-schemas.ts
@@ -52,7 +52,8 @@ export const CreateCloudflareCustomCertificatePkiSyncSchema = z.object({
syncOptions: CloudflareCustomCertificatePkiSyncOptionsSchema.optional().default({}),
subscriberId: z.string().nullish(),
connectionId: z.string(),
- projectId: z.string().trim().min(1),
+ projectId: z.string().trim().min(1).optional(),
+ applicationId: z.string().uuid().optional(),
certificateIds: z.array(z.string().uuid()).optional()
});
diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts
index 948f0fdfdb..2911f17a52 100644
--- a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-schemas.ts
@@ -53,7 +53,8 @@ export const CreateNetScalerPkiSyncSchema = z.object({
syncOptions: NetScalerPkiSyncOptionsSchema.optional().default({}),
subscriberId: z.string().nullish(),
connectionId: z.string(),
- projectId: z.string().trim().min(1),
+ projectId: z.string().trim().min(1).optional(),
+ applicationId: z.string().uuid().optional(),
certificateIds: z.array(z.string().uuid()).optional()
});
diff --git a/backend/src/services/pki-sync/pki-sync-dal.ts b/backend/src/services/pki-sync/pki-sync-dal.ts
index d04344b1e8..959f008ce8 100644
--- a/backend/src/services/pki-sync/pki-sync-dal.ts
+++ b/backend/src/services/pki-sync/pki-sync-dal.ts
@@ -197,11 +197,16 @@ export const pkiSyncDALFactory = (db: TDbClient) => {
const findByProjectIdWithSubscribers = async (
projectId: string,
processedRules?: ProcessedPermissionRules,
- tx?: Knex
+ tx?: Knex,
+ options?: { applicationId?: string | null }
) => {
try {
+ const filter: PkiSyncFindFilter = { projectId };
+ if (options?.applicationId !== undefined) {
+ (filter as Record<string, unknown>).applicationId = options.applicationId;
+ }
const pkiSyncs = await basePkiSyncWithSubscriberQuery({
- filter: { projectId },
+ filter,
db,
tx,
processedRules
diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.ts
index 119a7f4cf7..6ee3cbfd07 100644
--- a/backend/src/services/pki-sync/pki-sync-service.ts
+++ b/backend/src/services/pki-sync/pki-sync-service.ts
@@ -1,9 +1,13 @@
import { ForbiddenError, subject } from "@casl/ability";
-import { ActionProjectType, TCertificateSyncs } from "@app/db/schemas";
+import { ActionProjectType, ResourceType, TCertificateSyncs } from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionPkiSyncActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
+import {
+ ResourcePermissionPkiSyncActions,
+ ResourcePermissionSub
+} from "@app/ee/services/permission/resource-permission";
import { getProcessedPermissionRules } from "@app/lib/casl/permission-filter-utils";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
import { OrgServiceActor } from "@app/lib/types";
@@ -69,7 +73,7 @@ type TPkiSyncServiceFactoryDep = {
>;
pkiSubscriberDAL: Pick<TPkiSubscriberDALFactory, "findById">;
appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
pkiSyncQueue: Pick<
TPkiSyncQueueFactory,
@@ -89,6 +93,55 @@ export const pkiSyncServiceFactory = ({
licenseService,
pkiSyncQueue
}: TPkiSyncServiceFactoryDep) => {
+ const $resourceFallback = async (
+ action: ResourcePermissionPkiSyncActions,
+ projectId: string,
+ applicationId: string | null | undefined,
+ actor: OrgServiceActor
+ ) => {
+ if (!applicationId) return false;
+ const { permission } = await permissionService.getResourcePermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId,
+ resourceType: ResourceType.CertificateApplication,
+ resourceId: applicationId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId
+ });
+ return permission.can(action, ResourcePermissionSub.PkiSyncs);
+ };
+
+ const $assertSyncAction = async (
+ projectAction: ProjectPermissionPkiSyncActions,
+ resourceAction: ResourcePermissionPkiSyncActions,
+ pkiSync: { projectId: string; applicationId?: string | null; name: string },
+ subscriberName: string | undefined,
+ actor: OrgServiceActor
+ ) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.CertificateManager,
+ projectId: pkiSync.projectId
+ });
+
+ const projectSubject = subject(ProjectPermissionSub.PkiSyncs, {
+ subscriberName,
+ name: pkiSync.name
+ });
+
+ if (permission.can(projectAction, projectSubject)) return permission;
+
+ const allowedByResource = await $resourceFallback(resourceAction, pkiSync.projectId, pkiSync.applicationId, actor);
+ if (allowedByResource) return permission;
+
+ ForbiddenError.from(permission).throwUnlessCan(projectAction, projectSubject);
+ return permission;
+ };
+
const validateCertificatesProjectOwnership = async (certificateIds: string[], expectedProjectId: string) => {
if (certificateIds.length === 0) return;
@@ -127,10 +180,18 @@ export const pkiSyncServiceFactory = ({
subscriberId,
connectionId,
projectId,
+ applicationId,
certificateIds = []
}: Omit<TCreatePkiSyncDTO, "auditLogInfo">,
actor: OrgServiceActor
): Promise<TPkiSync> => {
+ if (!applicationId) {
+ throw new BadRequestError({
+ message:
+ "Certificate Syncs must be created inside a Cert Manager Application. Open the Application's Certificate Syncs tab and click Add Sync."
+ });
+ }
+
await enterprisePkiSyncCheck(licenseService, actor.orgId, destination);
const { permission } = await permissionService.getProjectPermission({
@@ -150,13 +211,30 @@ export const pkiSyncServiceFactory = ({
}
}
- ForbiddenError.from(permission).throwUnlessCan(
+ const allowedByProject = permission.can(
ProjectPermissionPkiSyncActions.Create,
subject(ProjectPermissionSub.PkiSyncs, {
subscriberName: subscriber?.name,
name
})
);
+ if (!allowedByProject) {
+ const allowedByResource = await $resourceFallback(
+ ResourcePermissionPkiSyncActions.Create,
+ projectId,
+ applicationId,
+ actor
+ );
+ if (!allowedByResource) {
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPkiSyncActions.Create,
+ subject(ProjectPermissionSub.PkiSyncs, {
+ subscriberName: subscriber?.name,
+ name
+ })
+ );
+ }
+ }
// Get the destination app type based on PKI sync destination
const destinationApp = getDestinationAppType(destination);
@@ -185,6 +263,7 @@ export const pkiSyncServiceFactory = ({
subscriberId,
connectionId,
projectId,
+ applicationId: applicationId ?? null,
...(isAutoSyncEnabled && { syncStatus: PkiSyncStatus.Pending })
});
@@ -213,6 +292,7 @@ export const pkiSyncServiceFactory = ({
const updatePkiSync = async (
{
id,
+ applicationId,
name,
description,
isAutoSyncEnabled,
@@ -226,6 +306,11 @@ export const pkiSyncServiceFactory = ({
): Promise<TPkiSync> => {
const pkiSync = await pkiSyncDAL.findById(id);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
+ if (applicationId && pkiSync.applicationId !== applicationId) {
+ throw new NotFoundError({
+ message: `PKI sync with id "${id}" is not scoped to application "${applicationId}".`
+ });
+ }
const { permission } = await permissionService.getProjectPermission({
actor: actor.type,
@@ -241,13 +326,30 @@ export const pkiSyncServiceFactory = ({
currentSubscriber = await pkiSubscriberDAL.findById(pkiSync.subscriberId);
}
- ForbiddenError.from(permission).throwUnlessCan(
+ const editAllowedByProject = permission.can(
ProjectPermissionPkiSyncActions.Edit,
subject(ProjectPermissionSub.PkiSyncs, {
subscriberName: currentSubscriber?.name,
name: pkiSync.name
})
);
+ if (!editAllowedByProject) {
+ const editAllowedByResource = await $resourceFallback(
+ ResourcePermissionPkiSyncActions.Edit,
+ pkiSync.projectId,
+ pkiSync.applicationId,
+ actor
+ );
+ if (!editAllowedByResource) {
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPkiSyncActions.Edit,
+ subject(ProjectPermissionSub.PkiSyncs, {
+ subscriberName: currentSubscriber?.name,
+ name: pkiSync.name
+ })
+ );
+ }
+ }
if (name && name !== pkiSync.name) {
const existingPkiSync = await pkiSyncDAL.findByNameAndProjectId(name, pkiSync.projectId);
@@ -318,11 +420,16 @@ export const pkiSyncServiceFactory = ({
};
const deletePkiSync = async (
- { id }: Omit<TDeletePkiSyncDTO, "auditLogInfo" | "projectId">,
+ { id, applicationId }: Omit<TDeletePkiSyncDTO, "auditLogInfo" | "projectId">,
actor: OrgServiceActor
) => {
const pkiSync = await pkiSyncDAL.findById(id);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
+ if (applicationId && pkiSync.applicationId !== applicationId) {
+ throw new NotFoundError({
+ message: `PKI sync with id "${id}" is not scoped to application "${applicationId}".`
+ });
+ }
const { permission } = await permissionService.getProjectPermission({
actor: actor.type,
@@ -338,19 +445,36 @@ export const pkiSyncServiceFactory = ({
pkiSyncSubscriber = await pkiSubscriberDAL.findById(pkiSync.subscriberId);
}
- ForbiddenError.from(permission).throwUnlessCan(
+ const deleteAllowedByProject = permission.can(
ProjectPermissionPkiSyncActions.Delete,
subject(ProjectPermissionSub.PkiSyncs, {
subscriberName: pkiSyncSubscriber?.name,
name: pkiSync.name
})
);
+ if (!deleteAllowedByProject) {
+ const deleteAllowedByResource = await $resourceFallback(
+ ResourcePermissionPkiSyncActions.Delete,
+ pkiSync.projectId,
+ pkiSync.applicationId,
+ actor
+ );
+ if (!deleteAllowedByResource) {
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPkiSyncActions.Delete,
+ subject(ProjectPermissionSub.PkiSyncs, {
+ subscriberName: pkiSyncSubscriber?.name,
+ name: pkiSync.name
+ })
+ );
+ }
+ }
return pkiSyncDAL.deleteById(id);
};
const listPkiSyncsByProjectId = async (
- { projectId, certificateId }: TListPkiSyncsByProjectId,
+ { projectId, certificateId, applicationId }: TListPkiSyncsByProjectId,
actor: OrgServiceActor
): Promise<TPkiSync[]> => {
const { permission } = await permissionService.getProjectPermission({
@@ -362,7 +486,21 @@ export const pkiSyncServiceFactory = ({
projectId
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionPkiSyncActions.Read, ProjectPermissionSub.PkiSyncs);
+ const allowedByProject = permission.can(ProjectPermissionPkiSyncActions.Read, ProjectPermissionSub.PkiSyncs);
+ if (!allowedByProject) {
+ const allowedByResource = await $resourceFallback(
+ ResourcePermissionPkiSyncActions.Read,
+ projectId,
+ applicationId,
+ actor
+ );
+ if (!allowedByResource) {
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPkiSyncActions.Read,
+ ProjectPermissionSub.PkiSyncs
+ );
+ }
+ }
const processedRules = getProcessedPermissionRules(
permission,
@@ -370,7 +508,12 @@ export const pkiSyncServiceFactory = ({
ProjectPermissionSub.PkiSyncs
);
- const pkiSyncsWithSubscribers = await pkiSyncDAL.findByProjectIdWithSubscribers(projectId, processedRules);
+ const pkiSyncsWithSubscribers = await pkiSyncDAL.findByProjectIdWithSubscribers(
+ projectId,
+ processedRules,
+ undefined,
+ applicationId !== undefined ? { applicationId } : undefined
+ );
if (certificateId) {
const syncsWithCertificateInfo = await Promise.all(
@@ -398,9 +541,13 @@ export const pkiSyncServiceFactory = ({
return pkiSyncsWithSubscribers as TPkiSync[];
};
- const findPkiSyncById = async ({ id, projectId }: TFindPkiSyncByIdDTO, actor: OrgServiceActor) => {
+ const findPkiSyncById = async ({ id, projectId, applicationId }: TFindPkiSyncByIdDTO, actor: OrgServiceActor) => {
const pkiSync = await pkiSyncDAL.findById(id);
- if (!pkiSync || (projectId && pkiSync.projectId !== projectId)) {
+ if (
+ !pkiSync ||
+ (projectId && pkiSync.projectId !== projectId) ||
+ (applicationId && pkiSync.applicationId !== applicationId)
+ ) {
throw new NotFoundError({
message: `Could not find PKI Sync with ID "${id}"`
});
@@ -420,13 +567,30 @@ export const pkiSyncServiceFactory = ({
findSubscriber = await pkiSubscriberDAL.findById(pkiSync.subscriberId);
}
- ForbiddenError.from(permission).throwUnlessCan(
+ const allowedByProject = permission.can(
ProjectPermissionPkiSyncActions.Read,
subject(ProjectPermissionSub.PkiSyncs, {
subscriberName: findSubscriber?.name,
name: pkiSync.name
})
);
+ if (!allowedByProject) {
+ const allowedByResource = await $resourceFallback(
+ ResourcePermissionPkiSyncActions.Read,
+ pkiSync.projectId,
+ pkiSync.applicationId,
+ actor
+ );
+ if (!allowedByResource) {
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPkiSyncActions.Read,
+ subject(ProjectPermissionSub.PkiSyncs, {
+ subscriberName: findSubscriber?.name,
+ name: pkiSync.name
+ })
+ );
+ }
+ }
const result = {
...pkiSync,
@@ -443,26 +607,17 @@ export const pkiSyncServiceFactory = ({
const pkiSync = await pkiSyncDAL.findById(id);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- actionProjectType: ActionProjectType.CertificateManager,
- projectId: pkiSync.projectId
- });
-
let syncSubscriber;
if (pkiSync.subscriberId) {
syncSubscriber = await pkiSubscriberDAL.findById(pkiSync.subscriberId);
}
- ForbiddenError.from(permission).throwUnlessCan(
+ await $assertSyncAction(
ProjectPermissionPkiSyncActions.SyncCertificates,
- subject(ProjectPermissionSub.PkiSyncs, {
- subscriberName: syncSubscriber?.name,
- name: pkiSync.name
- })
+ ResourcePermissionPkiSyncActions.SyncCertificates,
+ pkiSync,
+ syncSubscriber?.name,
+ actor
);
await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: id });
@@ -477,15 +632,6 @@ export const pkiSyncServiceFactory = ({
const pkiSync = await pkiSyncDAL.findById(id);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- actionProjectType: ActionProjectType.CertificateManager,
- projectId: pkiSync.projectId
- });
-
// Check if the PKI sync destination supports importing certificates
const syncOptions = listPkiSyncOptions().find((option) => option.destination === pkiSync.destination);
if (!syncOptions?.canImportCertificates) {
@@ -499,12 +645,12 @@ export const pkiSyncServiceFactory = ({
importSubscriber = await pkiSubscriberDAL.findById(pkiSync.subscriberId);
}
- ForbiddenError.from(permission).throwUnlessCan(
+ await $assertSyncAction(
ProjectPermissionPkiSyncActions.ImportCertificates,
- subject(ProjectPermissionSub.PkiSyncs, {
- subscriberName: importSubscriber?.name,
- name: pkiSync.name
- })
+ ResourcePermissionPkiSyncActions.ImportCertificates,
+ pkiSync,
+ importSubscriber?.name,
+ actor
);
await pkiSyncQueue.queuePkiSyncImportCertificatesById({ syncId: id });
@@ -519,26 +665,17 @@ export const pkiSyncServiceFactory = ({
const pkiSync = await pkiSyncDAL.findById(id);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- actionProjectType: ActionProjectType.CertificateManager,
- projectId: pkiSync.projectId
- });
-
let removeSubscriber;
if (pkiSync.subscriberId) {
removeSubscriber = await pkiSubscriberDAL.findById(pkiSync.subscriberId);
}
- ForbiddenError.from(permission).throwUnlessCan(
+ await $assertSyncAction(
ProjectPermissionPkiSyncActions.RemoveCertificates,
- subject(ProjectPermissionSub.PkiSyncs, {
- subscriberName: removeSubscriber?.name,
- name: pkiSync.name
- })
+ ResourcePermissionPkiSyncActions.RemoveCertificates,
+ pkiSync,
+ removeSubscriber?.name,
+ actor
);
await pkiSyncQueue.queuePkiSyncRemoveCertificatesById({ syncId: id });
@@ -560,26 +697,17 @@ export const pkiSyncServiceFactory = ({
const pkiSync = await pkiSyncDAL.findById(pkiSyncId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- actionProjectType: ActionProjectType.CertificateManager,
- projectId: pkiSync.projectId
- });
-
let pkiSyncSubscriber;
if (pkiSync.subscriberId) {
pkiSyncSubscriber = await pkiSubscriberDAL.findById(pkiSync.subscriberId);
}
- ForbiddenError.from(permission).throwUnlessCan(
+ await $assertSyncAction(
ProjectPermissionPkiSyncActions.Edit,
- subject(ProjectPermissionSub.PkiSyncs, {
- subscriberName: pkiSyncSubscriber?.name,
- name: pkiSync.name
- })
+ ResourcePermissionPkiSyncActions.Edit,
+ pkiSync,
+ pkiSyncSubscriber?.name,
+ actor
);
await validateCertificatesProjectOwnership(certificateIds, pkiSync.projectId);
@@ -610,20 +738,17 @@ export const pkiSyncServiceFactory = ({
const pkiSync = await pkiSyncDAL.findById(pkiSyncId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- actionProjectType: ActionProjectType.CertificateManager,
- projectId: pkiSync.projectId
- });
+ let pkiSyncSubscriber;
+ if (pkiSync.subscriberId) {
+ pkiSyncSubscriber = await pkiSubscriberDAL.findById(pkiSync.subscriberId);
+ }
- ForbiddenError.from(permission).throwUnlessCan(
+ await $assertSyncAction(
ProjectPermissionPkiSyncActions.Edit,
- subject(ProjectPermissionSub.PkiSyncs, {
- name: pkiSync.name
- })
+ ResourcePermissionPkiSyncActions.Edit,
+ pkiSync,
+ pkiSyncSubscriber?.name,
+ actor
);
const removedCount = await certificateSyncDAL.removeCertificates(pkiSyncId, certificateIds);
@@ -653,20 +778,17 @@ export const pkiSyncServiceFactory = ({
const pkiSync = await pkiSyncDAL.findById(pkiSyncId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- actionProjectType: ActionProjectType.CertificateManager,
- projectId: pkiSync.projectId
- });
+ let pkiSyncSubscriber;
+ if (pkiSync.subscriberId) {
+ pkiSyncSubscriber = await pkiSubscriberDAL.findById(pkiSync.subscriberId);
+ }
- ForbiddenError.from(permission).throwUnlessCan(
+ await $assertSyncAction(
ProjectPermissionPkiSyncActions.Read,
- subject(ProjectPermissionSub.PkiSyncs, {
- name: pkiSync.name
- })
+ ResourcePermissionPkiSyncActions.Read,
+ pkiSync,
+ pkiSyncSubscriber?.name,
+ actor
);
const result = await certificateSyncDAL.findWithDetails({
@@ -718,26 +840,17 @@ export const pkiSyncServiceFactory = ({
const pkiSync = await pkiSyncDAL.findById(pkiSyncId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- actionProjectType: ActionProjectType.CertificateManager,
- projectId: pkiSync.projectId
- });
-
let pkiSyncSubscriber;
if (pkiSync.subscriberId) {
pkiSyncSubscriber = await pkiSubscriberDAL.findById(pkiSync.subscriberId);
}
- ForbiddenError.from(permission).throwUnlessCan(
+ await $assertSyncAction(
ProjectPermissionPkiSyncActions.Edit,
- subject(ProjectPermissionSub.PkiSyncs, {
- subscriberName: pkiSyncSubscriber?.name,
- name: pkiSync.name
- })
+ ResourcePermissionPkiSyncActions.Edit,
+ pkiSync,
+ pkiSyncSubscriber?.name,
+ actor
);
const certificateSync = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSyncId, certificateId);
@@ -772,26 +885,17 @@ export const pkiSyncServiceFactory = ({
const pkiSync = await pkiSyncDAL.findById(pkiSyncId);
if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" });
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- actionProjectType: ActionProjectType.CertificateManager,
- projectId: pkiSync.projectId
- });
-
let pkiSyncSubscriber;
if (pkiSync.subscriberId) {
pkiSyncSubscriber = await pkiSubscriberDAL.findById(pkiSync.subscriberId);
}
- ForbiddenError.from(permission).throwUnlessCan(
+ await $assertSyncAction(
ProjectPermissionPkiSyncActions.Edit,
- subject(ProjectPermissionSub.PkiSyncs, {
- subscriberName: pkiSyncSubscriber?.name,
- name: pkiSync.name
- })
+ ResourcePermissionPkiSyncActions.Edit,
+ pkiSync,
+ pkiSyncSubscriber?.name,
+ actor
);
await certificateSyncDAL.clearSyncMetadataFlag(pkiSyncId, "isDefault");
diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.ts
index 72818091e0..71ca6b57ad 100644
--- a/backend/src/services/pki-sync/pki-sync-types.ts
+++ b/backend/src/services/pki-sync/pki-sync-types.ts
@@ -95,6 +95,7 @@ export type TCreatePkiSyncDTO = {
subscriberId?: string | null;
connectionId: string;
projectId: string;
+ applicationId?: string;
certificateIds?: string[];
auditLogInfo: AuditLogInfo;
resourceInternalMetadata?: ResourceMetadataDTO;
@@ -103,6 +104,7 @@ export type TCreatePkiSyncDTO = {
export type TUpdatePkiSyncDTO = {
id: string;
projectId?: string;
+ applicationId?: string;
name?: string;
description?: string;
isAutoSyncEnabled?: boolean;
@@ -118,17 +120,20 @@ export type TUpdatePkiSyncDTO = {
export type TDeletePkiSyncDTO = {
id: string;
projectId?: string;
+ applicationId?: string;
auditLogInfo: AuditLogInfo;
};
export type TListPkiSyncsByProjectId = {
projectId: string;
certificateId?: string;
+ applicationId?: string | null;
};
export type TFindPkiSyncByIdDTO = {
id: string;
projectId?: string;
+ applicationId?: string;
};
export type TTriggerPkiSyncSyncCertificatesByIdDTO = {
diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.ts
index 0694687c9c..2924dabb04 100644
--- a/backend/src/services/project/project-service.ts
+++ b/backend/src/services/project/project-service.ts
@@ -1230,6 +1230,7 @@ export const projectServiceFactory = ({
notAfterTo,
notBeforeFrom,
notBeforeTo,
+ applicationId,
sortBy,
sortOrder,
actorId,
@@ -1277,7 +1278,8 @@ export const projectServiceFactory = ({
...(notAfterFrom && { notAfterFrom }),
...(notAfterTo && { notAfterTo }),
...(notBeforeFrom && { notBeforeFrom }),
- ...(notBeforeTo && { notBeforeTo })
+ ...(notBeforeTo && { notBeforeTo }),
+ ...(applicationId && { applicationId })
};
const permissionFilters = getProcessedPermissionRules(
permission,
@@ -1329,7 +1331,8 @@ export const projectServiceFactory = ({
...(regularFilters.notAfterFrom && { notAfterFrom: regularFilters.notAfterFrom }),
...(regularFilters.notAfterTo && { notAfterTo: regularFilters.notAfterTo }),
...(regularFilters.notBeforeFrom && { notBeforeFrom: regularFilters.notBeforeFrom }),
- ...(regularFilters.notBeforeTo && { notBeforeTo: regularFilters.notBeforeTo })
+ ...(regularFilters.notBeforeTo && { notBeforeTo: regularFilters.notBeforeTo }),
+ ...(regularFilters.applicationId && { applicationId: regularFilters.applicationId })
};
const count = forPkiSync
diff --git a/backend/src/services/project/project-types.ts b/backend/src/services/project/project-types.ts
index 59f8fe8a3c..743bb41e15 100644
--- a/backend/src/services/project/project-types.ts
+++ b/backend/src/services/project/project-types.ts
@@ -162,6 +162,7 @@ export type TListProjectCertsDTO = {
notAfterTo?: Date;
notBeforeFrom?: Date;
notBeforeTo?: Date;
+ applicationId?: string;
sortBy?: string;
sortOrder?: "asc" | "desc";
} & Omit<TProjectPermission, "projectId">;
diff --git a/frontend/src/components/pki-syncs/CreatePkiSyncModal.tsx b/frontend/src/components/pki-syncs/CreatePkiSyncModal.tsx
index 71ab6fcaf9..2d983973b1 100644
--- a/frontend/src/components/pki-syncs/CreatePkiSyncModal.tsx
+++ b/frontend/src/components/pki-syncs/CreatePkiSyncModal.tsx
@@ -12,6 +12,7 @@ type Props = {
onOpenChange: (isOpen: boolean) => void;
selectSync?: PkiSync | null;
initialData?: any;
+ applicationId?: string;
};
type ContentProps = {
@@ -19,9 +20,16 @@ type ContentProps = {
selectedSync: PkiSync | null;
setSelectedSync: (selectedSync: PkiSync | null) => void;
initialData?: any;
+ applicationId?: string;
};
-const Content = ({ onComplete, setSelectedSync, selectedSync, initialData }: ContentProps) => {
+const Content = ({
+ onComplete,
+ setSelectedSync,
+ selectedSync,
+ initialData,
+ applicationId
+}: ContentProps) => {
if (selectedSync) {
return (
<CreatePkiSyncForm
@@ -29,6 +37,7 @@ const Content = ({ onComplete, setSelectedSync, selectedSync, initialData }: Con
onCancel={() => setSelectedSync(null)}
destination={selectedSync}
initialData={initialData}
+ applicationId={applicationId}
/>
);
}
@@ -40,6 +49,7 @@ export const CreatePkiSyncModal = ({
onOpenChange,
selectSync = null,
initialData,
+ applicationId,
...props
}: Props) => {
const [selectedSync, setSelectedSync] = useState<PkiSync | null>(selectSync);
@@ -78,6 +88,7 @@ export const CreatePkiSyncModal = ({
selectedSync={selectedSync}
setSelectedSync={setSelectedSync}
initialData={initialData}
+ applicationId={applicationId}
/>
</ModalContent>
</Modal>
diff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
index 068518a115..715b61544e 100644
--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
@@ -24,6 +24,7 @@ type Props = {
destination: PkiSync;
onCancel: () => void;
initialData?: any;
+ applicationId?: string;
};
const getFormTabs = (
@@ -59,7 +60,13 @@ const getFormTabs = (
return baseTabs;
};
-export const CreatePkiSyncForm = ({ destination, onComplete, onCancel, initialData }: Props) => {
+export const CreatePkiSyncForm = ({
+ destination,
+ onComplete,
+ onCancel,
+ initialData,
+ applicationId
+}: Props) => {
const createPkiSync = useCreatePkiSync();
const { currentProject } = useProject();
const { name: destinationName } = PKI_SYNC_MAP[destination];
@@ -111,6 +118,7 @@ export const CreatePkiSyncForm = ({ destination, onComplete, onCancel, initialDa
...formData,
connectionId: connection.id,
projectId: currentProject.id,
+ applicationId,
destinationConfig,
certificateIds: certificateIds || []
});
diff --git a/frontend/src/components/projects/NewProjectModal.tsx b/frontend/src/components/projects/NewProjectModal.tsx
index 41fd839054..996536dee2 100644
--- a/frontend/src/components/projects/NewProjectModal.tsx
+++ b/frontend/src/components/projects/NewProjectModal.tsx
@@ -65,10 +65,6 @@ const PROJECT_TYPE_MENU_ITEMS = [
label: "Secrets Management",
value: ProjectType.SecretManager
},
- {
- label: "Certificate Manager",
- value: ProjectType.CertificateManager
- },
{
label: "KMS",
value: ProjectType.KMS
diff --git a/frontend/src/context/OrgPermissionContext/types.ts b/frontend/src/context/OrgPermissionContext/types.ts
index a5862bd7e9..455909f21e 100644
--- a/frontend/src/context/OrgPermissionContext/types.ts
+++ b/frontend/src/context/OrgPermissionContext/types.ts
@@ -81,7 +81,14 @@ export enum OrgPermissionSubjects {
GithubOrgSyncManual = "github-org-sync-manual",
MachineIdentityAuthTemplate = "machine-identity-auth-template",
SubOrganization = "sub-organization",
- EmailDomains = "email-domains"
+ EmailDomains = "email-domains",
+ CertManager = "certificate-manager"
+}
+
+export enum OrgPermissionCertManagerActions {
+ Read = "read",
+ ManageInstance = "manage-instance",
+ ManageSettings = "manage-settings"
}
export enum OrgPermissionEmailDomainActions {
@@ -188,6 +195,7 @@ export type OrgPermissionSet =
)
]
| [OrgPermissionSubOrgActions, OrgPermissionSubjects.SubOrganization]
- | [OrgPermissionEmailDomainActions, OrgPermissionSubjects.EmailDomains];
+ | [OrgPermissionEmailDomainActions, OrgPermissionSubjects.EmailDomains]
+ | [OrgPermissionCertManagerActions, OrgPermissionSubjects.CertManager];
export type TOrgPermission = MongoAbility<OrgPermissionSet>;
diff --git a/frontend/src/helpers/project.ts b/frontend/src/helpers/project.ts
index 3cbd87ced2..4c500c285e 100644
--- a/frontend/src/helpers/project.ts
+++ b/frontend/src/helpers/project.ts
@@ -1,6 +1,6 @@
import { apiRequest } from "@app/config/request";
import { createWorkspace } from "@app/hooks/api/projects/queries";
-import { ProjectEnv, ProjectType } from "@app/hooks/api/projects/types";
+import { Project, ProjectEnv, ProjectType } from "@app/hooks/api/projects/types";
const secretsToBeAdded = [
{
@@ -99,6 +99,31 @@ export const getProjectTitle = (type: ProjectType) => {
return titleConvert[type];
};
+export const collapseCertManagerProjects = (
+ projects: Project[],
+ activeCertManagerProjectId: string | null
+): Project[] => {
+ const certManagerProjects = projects.filter((p) => p.type === ProjectType.CertificateManager);
+ if (certManagerProjects.length <= 1) return projects;
+
+ const others = projects.filter((p) => p.type !== ProjectType.CertificateManager);
+ const display =
+ certManagerProjects.find((p) => p.id === activeCertManagerProjectId) ?? certManagerProjects[0];
+ const otherCount = certManagerProjects.length - 1;
+
+ return [
+ ...others,
+ {
+ ...display,
+ name: "Certificate Manager",
+ description:
+ otherCount > 0
+ ? `Active: ${display.name} · ${otherCount} other instance${otherCount === 1 ? "" : "s"}`
+ : display.name
+ }
+ ];
+};
+
export const getProjectLottieIcon = (type: ProjectType) => {
const titleConvert = {
[ProjectType.SecretManager]: "vault",
diff --git a/frontend/src/hooks/api/approvalPolicies/queries.tsx b/frontend/src/hooks/api/approvalPolicies/queries.tsx
index 1c524ddac9..25fe9c6dd4 100644
--- a/frontend/src/hooks/api/approvalPolicies/queries.tsx
+++ b/frontend/src/hooks/api/approvalPolicies/queries.tsx
@@ -28,7 +28,8 @@ export const approvalPolicyQuery = {
policies: TApprovalPolicy[];
}>(`/api/v1/approval-policies/${params.policyType}`, {
params: {
- projectId: params.projectId
+ projectId: params.projectId,
+ ...(params.applicationId && { applicationId: params.applicationId })
}
});
return data.policies;
diff --git a/frontend/src/hooks/api/approvalPolicies/types.ts b/frontend/src/hooks/api/approvalPolicies/types.ts
index da28ec6ddd..873f43b897 100644
--- a/frontend/src/hooks/api/approvalPolicies/types.ts
+++ b/frontend/src/hooks/api/approvalPolicies/types.ts
@@ -66,6 +66,7 @@ export type TApprovalPolicy = {
};
steps: ApprovalPolicyStep[];
bypassForMachineIdentities?: boolean;
+ applicationId?: string | null;
createdAt: string;
updatedAt: string;
};
@@ -82,6 +83,7 @@ export type TCreateApprovalPolicyDTO = {
| CodeSigningPolicyConstraints;
steps: ApprovalPolicyStep[];
bypassForMachineIdentities?: boolean;
+ applicationId?: string;
};
export type TUpdateApprovalPolicyDTO = {
@@ -109,6 +111,7 @@ export type TGetApprovalPolicyByIdDTO = {
export type TListApprovalPoliciesDTO = {
policyType: ApprovalPolicyType;
projectId: string;
+ applicationId?: string;
};
export type TDeleteApprovalPolicyDTO = {
diff --git a/frontend/src/hooks/api/approvalRequests/types.ts b/frontend/src/hooks/api/approvalRequests/types.ts
index fc0b19e49b..5750240d9e 100644
--- a/frontend/src/hooks/api/approvalRequests/types.ts
+++ b/frontend/src/hooks/api/approvalRequests/types.ts
@@ -96,6 +96,7 @@ export type TApprovalRequest = {
id: string;
projectId: string;
policyId: string;
+ applicationId?: string | null;
type: ApprovalPolicyType;
status: ApprovalRequestStatus;
requesterId: string;
diff --git a/frontend/src/hooks/api/ca/mutations.tsx b/frontend/src/hooks/api/ca/mutations.tsx
index 36106bbc8d..7ed6ff8fd5 100644
--- a/frontend/src/hooks/api/ca/mutations.tsx
+++ b/frontend/src/hooks/api/ca/mutations.tsx
@@ -35,16 +35,16 @@ export const useUpdateCa = () => {
return data;
},
- onSuccess: ({ projectId, type }, { id }) => {
+ onSuccess: ({ type }, { id }) => {
queryClient.invalidateQueries({
- queryKey: caKeys.listCasByTypeAndProjectId(type, projectId)
+ queryKey: caKeys.listCasByTypeAndProjectId(type)
});
queryClient.invalidateQueries({
queryKey: caKeys.getCaById(id)
});
// Invalidate external CAs list
queryClient.invalidateQueries({
- queryKey: caKeys.listExternalCasByProjectId(projectId)
+ queryKey: caKeys.listExternalCasByProjectId()
});
}
});
@@ -60,13 +60,13 @@ export const useCreateCa = () => {
);
return data;
},
- onSuccess: (_, { type, projectId }) => {
+ onSuccess: (_, { type }) => {
queryClient.invalidateQueries({
- queryKey: caKeys.listCasByTypeAndProjectId(type, projectId)
+ queryKey: caKeys.listCasByTypeAndProjectId(type)
});
// Invalidate external CAs list
queryClient.invalidateQueries({
- queryKey: caKeys.listExternalCasByProjectId(projectId)
+ queryKey: caKeys.listExternalCasByProjectId()
});
}
});
@@ -81,13 +81,13 @@ export const useDeleteCa = () => {
);
return data;
},
- onSuccess: (_, { type, projectId }) => {
+ onSuccess: (_, { type }) => {
queryClient.invalidateQueries({
- queryKey: caKeys.listCasByTypeAndProjectId(type, projectId)
+ queryKey: caKeys.listCasByTypeAndProjectId(type)
});
// Invalidate external CAs list
queryClient.invalidateQueries({
- queryKey: caKeys.listExternalCasByProjectId(projectId)
+ queryKey: caKeys.listExternalCasByProjectId()
});
}
});
@@ -106,7 +106,7 @@ export const useSignIntermediate = () => {
});
};
-export const useImportCaCertificate = (projectId: string) => {
+export const useImportCaCertificate = () => {
const queryClient = useQueryClient();
return useMutation<TImportCaCertificateResponse, object, TImportCaCertificateDTO>({
mutationFn: async ({ caId, ...body }) => {
@@ -117,12 +117,11 @@ export const useImportCaCertificate = (projectId: string) => {
return data;
},
onSuccess: (_, { caId }) => {
- queryClient.invalidateQueries({ queryKey: projectKeys.getProjectCas({ projectId }) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaById(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCerts(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCert(caId) });
queryClient.invalidateQueries({
- queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL, projectId)
+ queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL)
});
}
});
@@ -139,15 +138,15 @@ export const useCreateCertificate = () => {
);
return data;
},
- onSuccess: (_, { projectSlug }) => {
+ onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: projectKeys.forProjectCertificates(projectSlug)
+ queryKey: projectKeys.allProjectCertificates()
});
}
});
};
-export const useCreateCertificateV3 = (options?: { projectId?: string }) => {
+export const useCreateCertificateV3 = () => {
const queryClient = useQueryClient();
return useMutation<TCreateCertificateV3Response, object, TCreateCertificateV3DTO>({
mutationFn: async (body) => {
@@ -157,17 +156,11 @@ export const useCreateCertificateV3 = (options?: { projectId?: string }) => {
);
return data;
},
- onSuccess: (_, { projectSlug }) => {
+ onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: projectKeys.forProjectCertificates(projectSlug)
+ queryKey: projectKeys.allProjectCertificates()
});
- if (options?.projectId) {
- queryClient.invalidateQueries({
- queryKey: projectKeys.forProjectCertificates(options.projectId)
- });
- }
-
queryClient.invalidateQueries({
queryKey: ["certificate-profiles"]
});
@@ -185,9 +178,9 @@ export const useOrderCertificateWithProfile = () => {
);
return data;
},
- onSuccess: (_, { projectSlug }) => {
+ onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: projectKeys.forProjectCertificates(projectSlug)
+ queryKey: projectKeys.allProjectCertificates()
});
}
});
@@ -203,8 +196,7 @@ export const useRenewCa = () => {
);
return data;
},
- onSuccess: ({ projectId }, { caId }) => {
- queryClient.invalidateQueries({ queryKey: projectKeys.getProjectCas({ projectId }) });
+ onSuccess: (_, { caId }) => {
queryClient.invalidateQueries({ queryKey: caKeys.getCaById(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCert(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCerts(caId) });
@@ -214,7 +206,7 @@ export const useRenewCa = () => {
});
};
-export const useInstallCaCertificateVenafi = (projectId: string) => {
+export const useInstallCaCertificateVenafi = () => {
const queryClient = useQueryClient();
return useMutation<
{ message: string; caId: string },
@@ -231,18 +223,17 @@ export const useInstallCaCertificateVenafi = (projectId: string) => {
onSuccess: (_, { caId }) => {
queryClient.invalidateQueries({ queryKey: caKeys.getCaAutoRenewal(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaSigningConfig(caId) });
- queryClient.invalidateQueries({ queryKey: projectKeys.getProjectCas({ projectId }) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaById(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCert(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCerts(caId) });
queryClient.invalidateQueries({
- queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL, projectId)
+ queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL)
});
}
});
};
-export const useInstallCaCertificateAdcs = (projectId: string) => {
+export const useInstallCaCertificateAdcs = () => {
const queryClient = useQueryClient();
return useMutation<
{ message: string; caId: string },
@@ -259,12 +250,11 @@ export const useInstallCaCertificateAdcs = (projectId: string) => {
onSuccess: (_, { caId }) => {
queryClient.invalidateQueries({ queryKey: caKeys.getCaAutoRenewal(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaSigningConfig(caId) });
- queryClient.invalidateQueries({ queryKey: projectKeys.getProjectCas({ projectId }) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaById(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCert(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCerts(caId) });
queryClient.invalidateQueries({
- queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL, projectId)
+ queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL)
});
}
});
@@ -380,7 +370,7 @@ export const useGenerateCaCertificate = () => {
queryClient.invalidateQueries({ queryKey: caKeys.getCaCsr(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCrl(caId) });
queryClient.invalidateQueries({
- queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL, "")
+ queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL)
});
}
});
diff --git a/frontend/src/hooks/api/ca/queries.tsx b/frontend/src/hooks/api/ca/queries.tsx
index 1cf31a0ad0..3bcaf6eeea 100644
--- a/frontend/src/hooks/api/ca/queries.tsx
+++ b/frontend/src/hooks/api/ca/queries.tsx
@@ -12,10 +12,10 @@ import {
export const caKeys = {
getCaById: (caId: string) => [{ caId }, "ca"],
- getCaByNameAndProjectId: (caName: string, projectId: string) => [{ caName, projectId }, "ca"],
- listCasByTypeAndProjectId: (type: CaType, projectId: string) => [{ type, projectId }, "cas"],
- listCasByProjectId: (projectId: string) => [{ projectId }, "cas"],
- listExternalCasByProjectId: (projectId: string) => [{ projectId }, "external-cas"],
+ getCaByNameAndProjectId: (caName: string) => [{ caName }, "ca"],
+ listCasByTypeAndProjectId: (type: CaType) => [{ type }, "cas"],
+ listCasByProjectId: () => ["cas"] as const,
+ listExternalCasByProjectId: () => ["external-cas"] as const,
getCaCerts: (caId: string) => [{ caId }, "ca-cert"],
getCaCrls: (caId: string) => [{ caId }, "ca-crls"],
getCaCert: (caId: string) => [{ caId }, "ca-cert"],
@@ -23,10 +23,7 @@ export const caKeys = {
getCaCrl: (caId: string) => [{ caId }, "ca-crl"],
getCaCertTemplates: (caId: string) => [{ caId }, "ca-cert-templates"],
getCaEstConfig: (caId: string) => [{ caId }, "ca-est-config"],
- getAzureAdcsTemplates: (caId: string, projectId: string) => [
- { caId, projectId },
- "azure-adcs-templates"
- ],
+ getAzureAdcsTemplates: (caId: string) => [{ caId }, "azure-adcs-templates"],
getCaSigningConfig: (caId: string) => [{ caId }, "ca-signing-config"],
getCaAutoRenewal: (caId: string) => [{ caId }, "ca-auto-renewal"]
};
@@ -52,12 +49,12 @@ export const useGetCa = ({
});
};
-export const useListCasByTypeAndProjectId = (type: CaType, projectId: string) => {
+export const useListCasByTypeAndProjectId = (type: CaType) => {
return useQuery({
- queryKey: caKeys.listCasByTypeAndProjectId(type, projectId),
+ queryKey: caKeys.listCasByTypeAndProjectId(type),
queryFn: async () => {
const { data } = await apiRequest.get<TUnifiedCertificateAuthority[]>(
- `/api/v1/cert-manager/ca/${type}?projectId=${projectId}`
+ `/api/v1/cert-manager/ca/${type}`
);
return data;
@@ -65,22 +62,22 @@ export const useListCasByTypeAndProjectId = (type: CaType, projectId: string) =>
});
};
-export const useListCasByProjectId = (projectId: string) => {
+export const useListCasByProjectId = () => {
return useQuery({
- queryKey: caKeys.listCasByProjectId(projectId),
+ queryKey: caKeys.listCasByProjectId(),
queryFn: async () => {
const { data } = await apiRequest.get<{
certificateAuthorities: TUnifiedCertificateAuthority[];
- }>(`/api/v1/cert-manager/ca?projectId=${projectId}`);
+ }>("/api/v1/cert-manager/ca");
return data.certificateAuthorities;
}
});
};
-export const useListExternalCasByProjectId = (projectId: string) => {
+export const useListExternalCasByProjectId = () => {
return useQuery({
- queryKey: caKeys.listExternalCasByProjectId(projectId),
+ queryKey: caKeys.listExternalCasByProjectId(),
queryFn: async () => {
const [
acmeResponse,
@@ -90,23 +87,19 @@ export const useListExternalCasByProjectId = (projectId: string) => {
awsAcmPublicCaResponse,
venafiTppResponse
] = await Promise.allSettled([
+ apiRequest.get<TUnifiedCertificateAuthority[]>(`/api/v1/cert-manager/ca/${CaType.ACME}`),
apiRequest.get<TUnifiedCertificateAuthority[]>(
- `/api/v1/cert-manager/ca/${CaType.ACME}?projectId=${projectId}`
+ `/api/v1/cert-manager/ca/${CaType.AZURE_AD_CS}`
),
+ apiRequest.get<TUnifiedCertificateAuthority[]>(`/api/v1/cert-manager/ca/${CaType.AWS_PCA}`),
apiRequest.get<TUnifiedCertificateAuthority[]>(
- `/api/v1/cert-manager/ca/${CaType.AZURE_AD_CS}?projectId=${projectId}`
+ `/api/v1/cert-manager/ca/${CaType.DIGICERT}`
),
apiRequest.get<TUnifiedCertificateAuthority[]>(
- `/api/v1/cert-manager/ca/${CaType.AWS_PCA}?projectId=${projectId}`
+ `/api/v1/cert-manager/ca/${CaType.AWS_ACM_PUBLIC_CA}`
),
apiRequest.get<TUnifiedCertificateAuthority[]>(
- `/api/v1/cert-manager/ca/${CaType.DIGICERT}?projectId=${projectId}`
- ),
- apiRequest.get<TUnifiedCertificateAuthority[]>(
- `/api/v1/cert-manager/ca/${CaType.AWS_ACM_PUBLIC_CA}?projectId=${projectId}`
- ),
- apiRequest.get<TUnifiedCertificateAuthority[]>(
- `/api/v1/cert-manager/ca/${CaType.VENAFI_TPP}?projectId=${projectId}`
+ `/api/v1/cert-manager/ca/${CaType.VENAFI_TPP}`
)
]);
@@ -285,21 +278,19 @@ export const useGetCaAutoRenewal = (caId: string, options?: { enabled?: boolean
export const useGetAzureAdcsTemplates = ({
caId,
- projectId,
isAzureAdcsCa
}: {
caId: string;
- projectId: string;
isAzureAdcsCa: boolean;
}) => {
return useQuery({
- queryKey: caKeys.getAzureAdcsTemplates(caId, projectId),
+ queryKey: caKeys.getAzureAdcsTemplates(caId),
queryFn: async () => {
const { data } = await apiRequest.get<{
templates: TAzureAdCsTemplate[];
- }>(`/api/v1/cert-manager/ca/azure-ad-cs/${caId}/templates?projectId=${projectId}`);
+ }>(`/api/v1/cert-manager/ca/azure-ad-cs/${caId}/templates`);
return data;
},
- enabled: Boolean(caId && projectId && isAzureAdcsCa)
+ enabled: Boolean(caId && isAzureAdcsCa)
});
};
diff --git a/frontend/src/hooks/api/ca/types.ts b/frontend/src/hooks/api/ca/types.ts
index b42b0d0747..8ba60745f2 100644
--- a/frontend/src/hooks/api/ca/types.ts
+++ b/frontend/src/hooks/api/ca/types.ts
@@ -133,16 +133,17 @@ export type TUnifiedCertificateAuthority =
export type TCreateCertificateAuthorityDTO = Omit<
TUnifiedCertificateAuthority,
- "id" | "enableDirectIssuance"
+ "id" | "enableDirectIssuance" | "projectId"
>;
-export type TUpdateCertificateAuthorityDTO = Partial<TUnifiedCertificateAuthority> & {
+export type TUpdateCertificateAuthorityDTO = Partial<
+ Omit<TUnifiedCertificateAuthority, "projectId">
+> & {
id: string;
type: CaType;
};
export type TDeleteCertificateAuthorityDTO = {
id: string;
- projectId: string;
type: CaType;
};
@@ -171,14 +172,12 @@ export type TCertificateAuthority = {
};
export type TUpdateCaDTO = {
- projectSlug: string;
caId: string;
status?: CaStatus;
requireTemplateForIssuance?: boolean;
};
export type TDeleteCaDTO = {
- projectSlug: string;
caId: string;
};
@@ -205,7 +204,6 @@ export type TAzureAdCsTemplate = {
export type TImportCaCertificateDTO = {
caId: string;
- projectSlug: string;
certificate: string;
certificateChain: string;
};
@@ -216,7 +214,6 @@ export type TImportCaCertificateResponse = {
};
export type TCreateCertificateDTO = {
- projectSlug: string;
caId?: string;
certificateTemplateId?: string;
pkiCollectionId?: string;
@@ -239,7 +236,6 @@ export type TCreateCertificateResponse = {
};
export type TCreateCertificateV3DTO = {
- projectSlug: string;
profileId: string;
pkiCollectionId?: string;
friendlyName?: string;
@@ -269,7 +265,6 @@ export type TCreateCertificateV3Response = TCreateCertificateResponse & {
};
export type TOrderCertificateDTO = {
- projectSlug: string;
profileId: string;
subjectAlternativeNames: Array<{
type: "dns" | "ip";
@@ -317,7 +312,6 @@ export type TOrderCertificateResponse = {
};
export type TRenewCaDTO = {
- projectSlug: string;
caId: string;
type: CaRenewalType;
notAfter: string;
diff --git a/frontend/src/hooks/api/certManagerAccess/index.ts b/frontend/src/hooks/api/certManagerAccess/index.ts
new file mode 100644
index 0000000000..41fee67462
--- /dev/null
+++ b/frontend/src/hooks/api/certManagerAccess/index.ts
@@ -0,0 +1,29 @@
+import { ProjectType } from "@app/hooks/api/projects/types";
+
+export const isCertManagerProject = (type?: string): boolean =>
+ type === ProjectType.CertificateManager;
+
+export const userMembershipsBase = (type?: string, projectId?: string): string =>
+ isCertManagerProject(type)
+ ? "/api/v1/cert-manager/access/users"
+ : `/api/v1/projects/${projectId ?? ""}/memberships`;
+
+export const identityMembershipsBase = (type?: string, projectId?: string): string =>
+ isCertManagerProject(type)
+ ? "/api/v1/cert-manager/access/identities"
+ : `/api/v1/projects/${projectId ?? ""}/memberships/identities`;
+
+export const groupMembershipsBase = (type?: string, projectId?: string): string =>
+ isCertManagerProject(type)
+ ? "/api/v1/cert-manager/access/groups"
+ : `/api/v1/projects/${projectId ?? ""}/memberships/groups`;
+
+export const rolesBase = (type?: string, projectId?: string): string =>
+ isCertManagerProject(type)
+ ? "/api/v1/cert-manager/access/roles"
+ : `/api/v1/projects/${projectId ?? ""}/roles`;
+
+export const availableIdentitiesUrl = (type?: string, projectId?: string): string =>
+ isCertManagerProject(type)
+ ? "/api/v1/cert-manager/access/identities/available"
+ : `/api/v1/projects/${projectId ?? ""}/memberships/available-identities`;
diff --git a/frontend/src/hooks/api/certManagerInstance/index.ts b/frontend/src/hooks/api/certManagerInstance/index.ts
new file mode 100644
index 0000000000..632364bc61
--- /dev/null
+++ b/frontend/src/hooks/api/certManagerInstance/index.ts
@@ -0,0 +1,70 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+const BASE_URL = "/api/v1/cert-manager/instance";
+
+export type TCertManagerInstanceProject = {
+ id: string;
+ name: string;
+ slug: string;
+ createdAt: string;
+};
+
+export type TCertManagerInstanceState = {
+ activeProjectId: string | null;
+ projects: TCertManagerInstanceProject[];
+ isMultiInstance: boolean;
+};
+
+export const certManagerInstanceKeys = {
+ all: ["cert-manager-instance"] as const,
+ state: () => [...certManagerInstanceKeys.all, "state"] as const
+};
+
+export const useCertManagerInstanceState = () =>
+ useQuery({
+ queryKey: certManagerInstanceKeys.state(),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TCertManagerInstanceState>(BASE_URL);
+ return data;
+ }
+ });
+
+export type TCertManagerLegacyInstance = TCertManagerInstanceProject & {
+ certificateCount: number;
+ syncCount: number;
+ alertCount: number;
+ isActive: boolean;
+};
+
+export type TCertManagerLegacyInstancesResponse = {
+ activeProjectId: string | null;
+ instances: TCertManagerLegacyInstance[];
+};
+
+export const useCertManagerLegacyInstances = () =>
+ useQuery({
+ queryKey: [...certManagerInstanceKeys.all, "legacy"] as const,
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TCertManagerLegacyInstancesResponse>(
+ `${BASE_URL}/legacy`
+ );
+ return data;
+ }
+ });
+
+export const useSetCertManagerActiveProject = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async (projectId: string) => {
+ const { data } = await apiRequest.post<{
+ activeProjectId: string;
+ previousActiveProjectId: string | null;
+ projectName: string;
+ }>(`${BASE_URL}/active-project`, { projectId });
+ return data;
+ },
+ onSuccess: () => qc.invalidateQueries({ queryKey: certManagerInstanceKeys.all })
+ });
+};
diff --git a/frontend/src/hooks/api/certificateCleanup/mutations.tsx b/frontend/src/hooks/api/certificateCleanup/mutations.tsx
index 96db5e5704..3cdc5871ee 100644
--- a/frontend/src/hooks/api/certificateCleanup/mutations.tsx
+++ b/frontend/src/hooks/api/certificateCleanup/mutations.tsx
@@ -16,9 +16,9 @@ export const useUpdateCertificateCleanupConfig = () => {
);
return data.config;
},
- onSuccess: (_, variables) => {
+ onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: certificateCleanupKeys.getConfig(variables.projectId)
+ queryKey: certificateCleanupKeys.getConfig()
});
}
});
diff --git a/frontend/src/hooks/api/certificateCleanup/queries.tsx b/frontend/src/hooks/api/certificateCleanup/queries.tsx
index 2df8428fc2..6f6b05abe0 100644
--- a/frontend/src/hooks/api/certificateCleanup/queries.tsx
+++ b/frontend/src/hooks/api/certificateCleanup/queries.tsx
@@ -5,19 +5,17 @@ import { apiRequest } from "@app/config/request";
import { TCertificateCleanupConfig } from "./types";
export const certificateCleanupKeys = {
- getConfig: (projectId: string) => [{ projectId }, "certificate-cleanup-config"] as const
+ getConfig: () => ["certificate-cleanup-config"] as const
};
-export const useGetCertificateCleanupConfig = (projectId: string) => {
+export const useGetCertificateCleanupConfig = () => {
return useQuery({
- queryKey: certificateCleanupKeys.getConfig(projectId),
+ queryKey: certificateCleanupKeys.getConfig(),
queryFn: async () => {
const { data } = await apiRequest.get<{ config: TCertificateCleanupConfig | null }>(
- "/api/v1/cert-manager/certificate-cleanup",
- { params: { projectId } }
+ "/api/v1/cert-manager/certificate-cleanup"
);
return data.config;
- },
- enabled: Boolean(projectId)
+ }
});
};
diff --git a/frontend/src/hooks/api/certificateCleanup/types.ts b/frontend/src/hooks/api/certificateCleanup/types.ts
index eb4f288c78..2963a02be6 100644
--- a/frontend/src/hooks/api/certificateCleanup/types.ts
+++ b/frontend/src/hooks/api/certificateCleanup/types.ts
@@ -11,7 +11,6 @@ export type TCertificateCleanupConfig = {
};
export type TUpdateCertificateCleanupConfigDTO = {
- projectId: string;
isEnabled?: boolean;
postExpiryRetentionDays?: number;
skipCertsWithActiveSyncs?: boolean;
diff --git a/frontend/src/hooks/api/certificateInventoryViews/mutations.tsx b/frontend/src/hooks/api/certificateInventoryViews/mutations.tsx
index d6b7a1fd07..1a36be05bc 100644
--- a/frontend/src/hooks/api/certificateInventoryViews/mutations.tsx
+++ b/frontend/src/hooks/api/certificateInventoryViews/mutations.tsx
@@ -14,21 +14,15 @@ export const useCreateCertificateInventoryView = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({
- projectId,
- name,
- filters,
- columns,
- isShared
- }: TCreateInventoryViewDTO) => {
+ mutationFn: async ({ name, filters, columns, isShared }: TCreateInventoryViewDTO) => {
const { data } = await apiRequest.post<{ view: TCertificateInventoryView }>(
- `/api/v1/projects/${projectId}/certificate-inventory-views`,
+ "/api/v1/cert-manager/certificate-inventory-views",
{ name, filters, columns, isShared }
);
return data.view;
},
- onSuccess: (_, { projectId }) => {
- queryClient.invalidateQueries({ queryKey: certificateInventoryViewKeys.list(projectId) });
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: certificateInventoryViewKeys.list() });
}
});
};
@@ -37,22 +31,15 @@ export const useUpdateCertificateInventoryView = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({
- projectId,
- viewId,
- name,
- filters,
- columns,
- isShared
- }: TUpdateInventoryViewDTO) => {
+ mutationFn: async ({ viewId, name, filters, columns, isShared }: TUpdateInventoryViewDTO) => {
const { data } = await apiRequest.patch<{ view: TCertificateInventoryView }>(
- `/api/v1/projects/${projectId}/certificate-inventory-views/${viewId}`,
+ `/api/v1/cert-manager/certificate-inventory-views/${viewId}`,
{ name, filters, columns, isShared }
);
return data.view;
},
- onSuccess: (_, { projectId }) => {
- queryClient.invalidateQueries({ queryKey: certificateInventoryViewKeys.list(projectId) });
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: certificateInventoryViewKeys.list() });
}
});
};
@@ -61,14 +48,14 @@ export const useDeleteCertificateInventoryView = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ projectId, viewId }: TDeleteInventoryViewDTO) => {
+ mutationFn: async ({ viewId }: TDeleteInventoryViewDTO) => {
const { data } = await apiRequest.delete<{ view: TCertificateInventoryView }>(
- `/api/v1/projects/${projectId}/certificate-inventory-views/${viewId}`
+ `/api/v1/cert-manager/certificate-inventory-views/${viewId}`
);
return data.view;
},
- onSuccess: (_, { projectId }) => {
- queryClient.invalidateQueries({ queryKey: certificateInventoryViewKeys.list(projectId) });
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: certificateInventoryViewKeys.list() });
}
});
};
diff --git a/frontend/src/hooks/api/certificateInventoryViews/queries.tsx b/frontend/src/hooks/api/certificateInventoryViews/queries.tsx
index 4ef515b074..831a6762df 100644
--- a/frontend/src/hooks/api/certificateInventoryViews/queries.tsx
+++ b/frontend/src/hooks/api/certificateInventoryViews/queries.tsx
@@ -6,18 +6,17 @@ import { TListInventoryViewsResponse } from "./types";
export const certificateInventoryViewKeys = {
all: ["certificateInventoryViews"] as const,
- list: (projectId: string) => [...certificateInventoryViewKeys.all, { projectId }] as const
+ list: () => [...certificateInventoryViewKeys.all, "list"] as const
};
-export const useListCertificateInventoryViews = (projectId: string) => {
+export const useListCertificateInventoryViews = () => {
return useQuery({
- queryKey: certificateInventoryViewKeys.list(projectId),
+ queryKey: certificateInventoryViewKeys.list(),
queryFn: async () => {
const { data } = await apiRequest.get<TListInventoryViewsResponse>(
- `/api/v1/projects/${projectId}/certificate-inventory-views`
+ "/api/v1/cert-manager/certificate-inventory-views"
);
return data;
- },
- enabled: Boolean(projectId)
+ }
});
};
diff --git a/frontend/src/hooks/api/certificateInventoryViews/types.ts b/frontend/src/hooks/api/certificateInventoryViews/types.ts
index 9efb9c8aad..8e40de0332 100644
--- a/frontend/src/hooks/api/certificateInventoryViews/types.ts
+++ b/frontend/src/hooks/api/certificateInventoryViews/types.ts
@@ -45,7 +45,6 @@ export type TListInventoryViewsResponse = {
};
export type TCreateInventoryViewDTO = {
- projectId: string;
name: string;
filters: TInventoryViewFilters;
columns?: string[];
@@ -53,7 +52,6 @@ export type TCreateInventoryViewDTO = {
};
export type TUpdateInventoryViewDTO = {
- projectId: string;
viewId: string;
name?: string;
filters?: TInventoryViewFilters;
@@ -62,6 +60,5 @@ export type TUpdateInventoryViewDTO = {
};
export type TDeleteInventoryViewDTO = {
- projectId: string;
viewId: string;
};
diff --git a/frontend/src/hooks/api/certificatePolicies/mutations.tsx b/frontend/src/hooks/api/certificatePolicies/mutations.tsx
index 5772733303..095b1da792 100644
--- a/frontend/src/hooks/api/certificatePolicies/mutations.tsx
+++ b/frontend/src/hooks/api/certificatePolicies/mutations.tsx
@@ -19,9 +19,9 @@ export const useCreateCertificatePolicy = () => {
}>("/api/v1/cert-manager/certificate-policies", data);
return response.certificatePolicy;
},
- onSuccess: (_, { projectId }) => {
+ onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: certificatePolicyKeys.listPolicies({ projectId })
+ queryKey: ["list-certificate-policies"]
});
}
});
@@ -36,9 +36,9 @@ export const useUpdateCertificatePolicy = () => {
}>(`/api/v1/cert-manager/certificate-policies/${policyId}`, data);
return response.certificatePolicy;
},
- onSuccess: (policy, { policyId }) => {
+ onSuccess: (_, { policyId }) => {
queryClient.invalidateQueries({
- queryKey: certificatePolicyKeys.listPolicies({ projectId: policy.projectId })
+ queryKey: ["list-certificate-policies"]
});
queryClient.invalidateQueries({
queryKey: certificatePolicyKeys.getPolicyById(policyId)
@@ -56,9 +56,9 @@ export const useDeleteCertificatePolicy = () => {
}>(`/api/v1/cert-manager/certificate-policies/${policyId}`);
return response.certificatePolicy;
},
- onSuccess: (policy, { policyId }) => {
+ onSuccess: (_, { policyId }) => {
queryClient.invalidateQueries({
- queryKey: certificatePolicyKeys.listPolicies({ projectId: policy.projectId })
+ queryKey: ["list-certificate-policies"]
});
queryClient.removeQueries({
queryKey: certificatePolicyKeys.getPolicyById(policyId)
diff --git a/frontend/src/hooks/api/certificatePolicies/queries.tsx b/frontend/src/hooks/api/certificatePolicies/queries.tsx
index 54e59a3c59..6af5756eca 100644
--- a/frontend/src/hooks/api/certificatePolicies/queries.tsx
+++ b/frontend/src/hooks/api/certificatePolicies/queries.tsx
@@ -9,35 +9,28 @@ import {
} from "./types";
export const certificatePolicyKeys = {
- listPolicies: ({ projectId, ...el }: { limit?: number; offset?: number; projectId: string }) => [
- "list-certificate-policies",
- projectId,
- el
- ],
+ listPolicies: (el: { limit?: number; offset?: number } = {}) => ["list-certificate-policies", el],
getPolicyById: (id: string) => ["certificate-policy", id]
};
export const useListCertificatePolicies = ({
- projectId,
limit = 20,
offset = 0
-}: TListCertificatePoliciesDTO) => {
+}: TListCertificatePoliciesDTO = {}) => {
return useQuery({
- queryKey: certificatePolicyKeys.listPolicies({ projectId, limit, offset }),
+ queryKey: certificatePolicyKeys.listPolicies({ limit, offset }),
queryFn: async () => {
const { data } = await apiRequest.get<{
certificatePolicies: TCertificatePolicy[];
totalCount: number;
}>("/api/v1/cert-manager/certificate-policies", {
params: {
- projectId,
limit,
offset
}
});
return data;
- },
- enabled: Boolean(projectId)
+ }
});
};
diff --git a/frontend/src/hooks/api/certificatePolicies/types.ts b/frontend/src/hooks/api/certificatePolicies/types.ts
index df1516cc75..f4e56c0ece 100644
--- a/frontend/src/hooks/api/certificatePolicies/types.ts
+++ b/frontend/src/hooks/api/certificatePolicies/types.ts
@@ -77,7 +77,6 @@ export type TCertificatePolicy = {
};
export type TCreateCertificatePolicyDTO = {
- projectId: string;
name: string;
description?: string;
subject?: TCertificatePolicyRule["subject"];
@@ -107,7 +106,6 @@ export type TDeleteCertificatePolicyDTO = {
};
export type TListCertificatePoliciesDTO = {
- projectId: string;
limit?: number;
offset?: number;
};
diff --git a/frontend/src/hooks/api/certificateProfiles/mutations.tsx b/frontend/src/hooks/api/certificateProfiles/mutations.tsx
index 8cfb04b76f..3a76ca1d30 100644
--- a/frontend/src/hooks/api/certificateProfiles/mutations.tsx
+++ b/frontend/src/hooks/api/certificateProfiles/mutations.tsx
@@ -20,9 +20,9 @@ export const useCreateCertificateProfile = () => {
}>("/api/v1/cert-manager/certificate-profiles", data);
return response.certificateProfile;
},
- onSuccess: (_, { projectId }) => {
+ onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: certificateProfileKeys.list({ projectId })
+ queryKey: ["certificate-profiles", "list"]
});
}
});
@@ -38,9 +38,9 @@ export const useUpdateCertificateProfile = () => {
}>(`/api/v1/cert-manager/certificate-profiles/${profileId}`, data);
return response.certificateProfile;
},
- onSuccess: (profile, { profileId }) => {
+ onSuccess: (_, { profileId }) => {
queryClient.invalidateQueries({
- queryKey: certificateProfileKeys.list({ projectId: profile.projectId })
+ queryKey: ["certificate-profiles", "list"]
});
queryClient.invalidateQueries({
queryKey: certificateProfileKeys.getById(profileId)
@@ -59,9 +59,9 @@ export const useDeleteCertificateProfile = () => {
}>(`/api/v1/cert-manager/certificate-profiles/${profileId}`);
return response.certificateProfile;
},
- onSuccess: (profile, { profileId }) => {
+ onSuccess: (_, { profileId }) => {
queryClient.invalidateQueries({
- queryKey: certificateProfileKeys.list({ projectId: profile.projectId })
+ queryKey: ["certificate-profiles", "list"]
});
queryClient.removeQueries({
queryKey: certificateProfileKeys.getById(profileId)
diff --git a/frontend/src/hooks/api/certificateProfiles/queries.tsx b/frontend/src/hooks/api/certificateProfiles/queries.tsx
index 71f0e6ce9c..9b5e4d771f 100644
--- a/frontend/src/hooks/api/certificateProfiles/queries.tsx
+++ b/frontend/src/hooks/api/certificateProfiles/queries.tsx
@@ -16,7 +16,6 @@ import {
export const certificateProfileKeys = {
list: (params: {
- projectId: string;
limit?: number;
offset?: number;
search?: string;
@@ -25,12 +24,7 @@ export const certificateProfileKeys = {
expiringDays?: number;
}) => ["certificate-profiles", "list", params],
getById: (profileId: string) => ["certificate-profiles", "get-by-id", profileId],
- getBySlug: (projectId: string, slug: string) => [
- "certificate-profiles",
- "get-by-slug",
- projectId,
- slug
- ],
+ getBySlug: (slug: string) => ["certificate-profiles", "get-by-slug", slug],
getCertificates: (profileId: string, params?: Omit<TGetProfileCertificatesDTO, "profileId">) => [
"certificate-profiles",
"certificates",
@@ -51,7 +45,6 @@ export const certificateProfileKeys = {
};
export const useListCertificateProfiles = ({
- projectId,
limit = 20,
offset = 0,
search,
@@ -60,7 +53,6 @@ export const useListCertificateProfiles = ({
}: TListCertificateProfilesDTO) => {
return useQuery({
queryKey: certificateProfileKeys.list({
- projectId,
limit,
offset,
search,
@@ -73,7 +65,6 @@ export const useListCertificateProfiles = ({
totalCount: number;
}>("/api/v1/cert-manager/certificate-profiles", {
params: {
- projectId,
limit,
offset,
search,
@@ -82,8 +73,7 @@ export const useListCertificateProfiles = ({
}
});
return data;
- },
- enabled: Boolean(projectId)
+ }
});
};
@@ -100,21 +90,16 @@ export const useGetCertificateProfileById = ({ profileId }: TGetCertificateProfi
});
};
-export const useGetCertificateProfileBySlug = ({
- projectId,
- slug
-}: TGetCertificateProfileBySlugDTO) => {
+export const useGetCertificateProfileBySlug = ({ slug }: TGetCertificateProfileBySlugDTO) => {
return useQuery({
- queryKey: certificateProfileKeys.getBySlug(projectId, slug),
+ queryKey: certificateProfileKeys.getBySlug(slug),
queryFn: async () => {
const { data } = await apiRequest.get<{
certificateProfile: TCertificateProfile;
- }>(`/api/v1/cert-manager/certificate-profiles/slug/${slug}`, {
- params: { projectId }
- });
+ }>(`/api/v1/cert-manager/certificate-profiles/slug/${slug}`);
return data.certificateProfile;
},
- enabled: Boolean(projectId && slug)
+ enabled: Boolean(slug)
});
};
diff --git a/frontend/src/hooks/api/certificateProfiles/types.ts b/frontend/src/hooks/api/certificateProfiles/types.ts
index 6443f99783..66c3faee85 100644
--- a/frontend/src/hooks/api/certificateProfiles/types.ts
+++ b/frontend/src/hooks/api/certificateProfiles/types.ts
@@ -102,7 +102,6 @@ export type TCertificateProfileWithDetails = TCertificateProfile & {
};
export type TCreateCertificateProfileDTO = {
- projectId: string;
caId?: string;
certificatePolicyId: string;
slug: string;
@@ -170,7 +169,6 @@ export type TDeleteCertificateProfileDTO = {
};
export type TListCertificateProfilesDTO = {
- projectId: string;
limit?: number;
offset?: number;
search?: string;
@@ -185,7 +183,6 @@ export type TGetCertificateProfileByIdDTO = {
};
export type TGetCertificateProfileBySlugDTO = {
- projectId: string;
slug: string;
};
diff --git a/frontend/src/hooks/api/certificateTemplates/mutations.tsx b/frontend/src/hooks/api/certificateTemplates/mutations.tsx
index a402ad4209..ed2fc0de01 100644
--- a/frontend/src/hooks/api/certificateTemplates/mutations.tsx
+++ b/frontend/src/hooks/api/certificateTemplates/mutations.tsx
@@ -88,12 +88,9 @@ export const useCreateCertTemplateV2 = () => {
}>("/api/v2/pki/certificate-templates", dto);
return data.certificateTemplate;
},
- onSuccess: (_, { projectId }) => {
+ onSuccess: () => {
queryClient.invalidateQueries({
- predicate: (query) => {
- const [firstKey, queryProjectId] = query.queryKey;
- return firstKey === "list-template" && queryProjectId === projectId;
- }
+ predicate: (query) => query.queryKey[0] === "list-template"
});
}
});
@@ -110,12 +107,9 @@ export const useUpdateCertTemplateV2 = () => {
return data.certificateTemplate;
},
- onSuccess: (_, { projectId }) => {
+ onSuccess: () => {
queryClient.invalidateQueries({
- predicate: (query) => {
- const [firstKey, queryProjectId] = query.queryKey;
- return firstKey === "list-template" && queryProjectId === projectId;
- }
+ predicate: (query) => query.queryKey[0] === "list-template"
});
}
});
@@ -126,21 +120,13 @@ export const useDeleteCertTemplateV2 = () => {
return useMutation<TCertificateTemplate, object, TDeleteCertificateTemplateV2DTO>({
mutationFn: async (dto) => {
const { data } = await apiRequest.delete<{ certificateTemplate: TCertificateTemplate }>(
- `/api/v2/pki/certificate-templates/${dto.templateName}`,
- {
- data: {
- projectId: dto.projectId
- }
- }
+ `/api/v2/pki/certificate-templates/${dto.templateName}`
);
return data.certificateTemplate;
},
- onSuccess: (_, { projectId }) => {
+ onSuccess: () => {
queryClient.invalidateQueries({
- predicate: (query) => {
- const [firstKey, queryProjectId] = query.queryKey;
- return firstKey === "list-template" && queryProjectId === projectId;
- }
+ predicate: (query) => query.queryKey[0] === "list-template"
});
}
});
diff --git a/frontend/src/hooks/api/certificateTemplates/queries.tsx b/frontend/src/hooks/api/certificateTemplates/queries.tsx
index 531a00bb51..329137ab5b 100644
--- a/frontend/src/hooks/api/certificateTemplates/queries.tsx
+++ b/frontend/src/hooks/api/certificateTemplates/queries.tsx
@@ -11,11 +11,7 @@ import {
export const certTemplateKeys = {
getCertTemplateById: (id: string) => [{ id }, "cert-template"],
- listTemplates: ({ projectId, ...el }: { limit?: number; offset?: number; projectId: string }) => [
- "list-template",
- projectId,
- el
- ],
+ listTemplates: (el: { limit?: number; offset?: number } = {}) => ["list-template", el] as const,
getEstConfig: (id: string) => [{ id }, "cert-template-est-config"]
};
@@ -36,11 +32,10 @@ export const useGetCertTemplate = (id: string) => {
// TODO: DEPRECATE
export const useListCertificateTemplates = ({
limit = 100,
- offset = 0,
- projectId
-}: TListCertificateTemplatesDTO) => {
+ offset = 0
+}: TListCertificateTemplatesDTO = {}) => {
return useQuery({
- queryKey: certTemplateKeys.listTemplates({ limit, offset, projectId }),
+ queryKey: certTemplateKeys.listTemplates({ limit, offset }),
queryFn: async () => {
const { data } = await apiRequest.get<{
certificateTemplates: TCertificateTemplateV2[];
@@ -48,8 +43,7 @@ export const useListCertificateTemplates = ({
}>("/api/v2/pki/certificate-templates", {
params: {
limit,
- offset,
- projectId
+ offset
}
});
return data;
diff --git a/frontend/src/hooks/api/certificateTemplates/types.ts b/frontend/src/hooks/api/certificateTemplates/types.ts
index 448f388256..b5a8cb67de 100644
--- a/frontend/src/hooks/api/certificateTemplates/types.ts
+++ b/frontend/src/hooks/api/certificateTemplates/types.ts
@@ -70,7 +70,6 @@ export type TCreateCertificateTemplateV2DTO = {
commonName: string;
subjectAlternativeName: string;
ttl: string;
- projectId: string;
keyUsages: string[];
extendedKeyUsages: string[];
};
@@ -82,14 +81,12 @@ export type TUpdateCertificateTemplateV2DTO = {
commonName?: string;
subjectAlternativeName?: string;
ttl?: string;
- projectId: string;
keyUsages?: string[];
extendedKeyUsages?: string[];
};
export type TDeleteCertificateTemplateV2DTO = {
templateName: string;
- projectId: string;
};
export type TCreateEstConfigDTO = {
@@ -119,5 +116,4 @@ export type TEstConfig = {
export type TListCertificateTemplatesDTO = {
limit?: number;
offset?: number;
- projectId: string;
};
diff --git a/frontend/src/hooks/api/certificates/mutations.tsx b/frontend/src/hooks/api/certificates/mutations.tsx
index 2438b8331a..62f6f9f460 100644
--- a/frontend/src/hooks/api/certificates/mutations.tsx
+++ b/frontend/src/hooks/api/certificates/mutations.tsx
@@ -32,7 +32,7 @@ export const useDeleteCert = () => {
);
return certificate;
},
- onSuccess: (_, { id, projectId }) => {
+ onSuccess: (_, { id }) => {
queryClient.invalidateQueries({
queryKey: certKeys.getCertificateById(id)
});
@@ -46,10 +46,7 @@ export const useDeleteCert = () => {
queryKey: projectKeys.allProjectCertificates()
});
queryClient.invalidateQueries({
- queryKey: projectKeys.forProjectCertificates(projectId)
- });
- queryClient.invalidateQueries({
- queryKey: certKeys.getDashboardStats(projectId)
+ queryKey: ["cert-dashboard-stats"]
});
}
});
@@ -69,7 +66,7 @@ export const useRevokeCert = () => {
);
return certificate;
},
- onSuccess: (_, { id, projectId }) => {
+ onSuccess: (_, { id }) => {
queryClient.invalidateQueries({
queryKey: certKeys.getCertificateById(id)
});
@@ -83,10 +80,7 @@ export const useRevokeCert = () => {
queryKey: projectKeys.allProjectCertificates()
});
queryClient.invalidateQueries({
- queryKey: projectKeys.forProjectCertificates(projectId)
- });
- queryClient.invalidateQueries({
- queryKey: certKeys.getDashboardStats(projectId)
+ queryKey: ["cert-dashboard-stats"]
});
}
});
@@ -102,9 +96,9 @@ export const useImportCertificate = () => {
);
return data;
},
- onSuccess: (_, { projectSlug }) => {
+ onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: projectKeys.forProjectCertificates(projectSlug)
+ queryKey: projectKeys.allProjectCertificates()
});
queryClient.invalidateQueries({
queryKey: ["cert-dashboard-stats"]
@@ -162,13 +156,10 @@ export const useUpdateRenewalConfig = () => {
);
return data;
},
- onSuccess: (_, { certificateId, projectSlug }) => {
+ onSuccess: (_, { certificateId }) => {
queryClient.invalidateQueries({
queryKey: certKeys.getCertificateById(certificateId)
});
- queryClient.invalidateQueries({
- queryKey: projectKeys.forProjectCertificates(projectSlug)
- });
queryClient.invalidateQueries({
queryKey: projectKeys.allProjectCertificates()
});
@@ -178,7 +169,7 @@ export const useUpdateRenewalConfig = () => {
export const useDownloadCertPkcs12 = () => {
return useMutation<void, object, TDownloadPkcs12DTO>({
- mutationFn: async ({ certificateId, projectSlug, password, alias }) => {
+ mutationFn: async ({ certificateId, password, alias }) => {
try {
const response = await apiRequest.post(
`/api/v1/cert-manager/certificates/${certificateId}/pkcs12`,
@@ -187,7 +178,6 @@ export const useDownloadCertPkcs12 = () => {
alias
},
{
- params: { projectSlug },
responseType: "arraybuffer"
}
);
@@ -228,16 +218,13 @@ export const useUpdateCertificate = () => {
}>(`/api/v1/cert-manager/certificates/${certificateId}`, { metadata });
return data;
},
- onSuccess: (_, { certificateId, projectId }) => {
+ onSuccess: (_, { certificateId }) => {
queryClient.invalidateQueries({
queryKey: certKeys.getCertificateById(certificateId)
});
queryClient.invalidateQueries({
queryKey: projectKeys.allProjectCertificates()
});
- queryClient.invalidateQueries({
- queryKey: projectKeys.forProjectCertificates(projectId)
- });
}
});
};
@@ -246,14 +233,13 @@ export const useUnifiedCertificateIssuance = () => {
const queryClient = useQueryClient();
return useMutation<TUnifiedCertificateIssuanceResponse, object, TUnifiedCertificateIssuanceDTO>({
mutationFn: async (body) => {
- const { projectSlug, ...requestData } = body;
const { data } = await apiRequest.post<TUnifiedCertificateIssuanceResponse>(
"/api/v1/cert-manager/certificates",
- requestData
+ body
);
return data;
},
- onSuccess: (_, { projectSlug }) => {
+ onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["certificate-profiles", "list"]
});
@@ -264,10 +250,7 @@ export const useUnifiedCertificateIssuance = () => {
queryKey: projectKeys.allProjectCertificates()
});
queryClient.invalidateQueries({
- queryKey: projectKeys.forProjectCertificates(projectSlug)
- });
- queryClient.invalidateQueries({
- queryKey: ["certificateRequests", "list", projectSlug]
+ queryKey: ["certificateRequests", "list"]
});
queryClient.invalidateQueries({
queryKey: ["cert-dashboard-stats"]
diff --git a/frontend/src/hooks/api/certificates/queries.tsx b/frontend/src/hooks/api/certificates/queries.tsx
index be6e2213ec..3a20398a1d 100644
--- a/frontend/src/hooks/api/certificates/queries.tsx
+++ b/frontend/src/hooks/api/certificates/queries.tsx
@@ -18,14 +18,10 @@ export const certKeys = {
getCertBody: (serialNumber: string) => [{ serialNumber }, "certBody"],
getCertBundle: (serialNumber: string) => [{ serialNumber }, "certBundle"],
getCertificateById: (certificateId: string) => [{ certificateId }, "certificateById"],
- getCertificateRequest: (requestId: string, projectSlug: string) => [
- { requestId, projectSlug },
- "certificateRequest"
- ],
+ getCertificateRequest: (requestId: string) => [{ requestId }, "certificateRequest"],
listCertificateRequests: (params: TListCertificateRequestsParams) => [
"certificateRequests",
"list",
- params.projectSlug,
params.offset,
params.limit,
params.search,
@@ -115,7 +111,6 @@ export const useListCertificateRequests = (params: TListCertificateRequestsParam
const { data } = await apiRequest.post<TListCertificateRequestsResponse>(
"/api/v1/cert-manager/certificates/certificate-requests/search",
{
- projectSlug: params.projectSlug,
offset: params.offset,
limit: params.limit,
search: params.search,
@@ -130,21 +125,20 @@ export const useListCertificateRequests = (params: TListCertificateRequestsParam
);
return data;
},
- enabled: Boolean(params.projectSlug),
placeholderData: (previousData) => previousData
});
};
-export const useGetCertificateRequest = (requestId: string, projectSlug: string) => {
+export const useGetCertificateRequest = (requestId: string) => {
return useQuery({
- queryKey: certKeys.getCertificateRequest(requestId, projectSlug),
+ queryKey: certKeys.getCertificateRequest(requestId),
queryFn: async () => {
const { data } = await apiRequest.get<TCertificateRequestDetails>(
- `/api/v1/cert-manager/certificates/certificate-requests/${requestId}?projectSlug=${projectSlug}`
+ `/api/v1/cert-manager/certificates/certificate-requests/${requestId}`
);
return data;
},
- enabled: Boolean(requestId) && Boolean(projectSlug)
+ enabled: Boolean(requestId)
});
};
diff --git a/frontend/src/hooks/api/certificates/types.ts b/frontend/src/hooks/api/certificates/types.ts
index a95413e703..889aceb063 100644
--- a/frontend/src/hooks/api/certificates/types.ts
+++ b/frontend/src/hooks/api/certificates/types.ts
@@ -70,18 +70,14 @@ export type TCertificateByIdResponse = {
export type TDeleteCertDTO = {
id: string;
- projectId: string;
};
export type TRevokeCertDTO = {
- projectId: string;
id: string;
revocationReason: string;
};
export type TImportCertificateDTO = {
- projectSlug: string;
-
certificatePem: string;
privateKeyPem: string;
chainPem: string;
@@ -116,20 +112,16 @@ export type TUpdateRenewalConfigDTO = {
certificateId: string;
renewBeforeDays?: number;
enableAutoRenewal?: boolean;
- projectSlug: string;
};
export type TDownloadPkcs12DTO = {
certificateId: string;
- projectSlug: string;
password: string;
alias: string;
};
export type TUnifiedCertificateIssuanceDTO = {
- projectSlug: string;
profileId: string;
- projectId: string;
csr?: string;
attributes?: {
commonName?: string | null;
@@ -204,7 +196,6 @@ export type TCertificateRequestDetails = {
export type TUpdateCertificateDTO = {
certificateId: string;
- projectId: string;
metadata: Array<{ key: string; value: string }>;
};
@@ -234,7 +225,6 @@ export type TListCertificateRequestsResponse = {
};
export type TListCertificateRequestsParams = {
- projectSlug: string;
offset?: number;
limit?: number;
search?: string;
diff --git a/frontend/src/hooks/api/index.tsx b/frontend/src/hooks/api/index.tsx
index 1cb852ac8f..72f7c5f8d9 100644
--- a/frontend/src/hooks/api/index.tsx
+++ b/frontend/src/hooks/api/index.tsx
@@ -39,6 +39,8 @@ export * from "./organization";
export * from "./orgIdentity";
export * from "./orgIdentityMembership";
export * from "./pkiAlerts";
+export * from "./pkiAlertsV2";
+export * from "./pkiApplications";
export * from "./pkiCollections";
export * from "./pkiDiscovery";
export * from "./pkiSubscriber";
diff --git a/frontend/src/hooks/api/pkiAlerts/mutations.tsx b/frontend/src/hooks/api/pkiAlerts/mutations.tsx
index 5c41dd6190..7baa24cc5f 100644
--- a/frontend/src/hooks/api/pkiAlerts/mutations.tsx
+++ b/frontend/src/hooks/api/pkiAlerts/mutations.tsx
@@ -14,8 +14,8 @@ export const useCreatePkiAlert = () => {
const { data: alert } = await apiRequest.post<TPkiAlert>("/api/v1/pki/alerts", body);
return alert;
},
- onSuccess: (_, { projectId }) => {
- queryClient.invalidateQueries({ queryKey: projectKeys.getProjectPkiAlerts(projectId) });
+ onSuccess: (alert) => {
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectPkiAlerts(alert.projectId) });
}
});
};
@@ -31,8 +31,8 @@ export const useUpdatePkiAlert = () => {
);
return alert;
},
- onSuccess: (_, { projectId, alertId }) => {
- queryClient.invalidateQueries({ queryKey: projectKeys.getProjectPkiAlerts(projectId) });
+ onSuccess: (alert, { alertId }) => {
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectPkiAlerts(alert.projectId) });
queryClient.invalidateQueries({ queryKey: pkiAlertKeys.getPkiAlertById(alertId) });
}
});
@@ -46,8 +46,8 @@ export const useDeletePkiAlert = () => {
const { data: alert } = await apiRequest.delete<TPkiAlert>(`/api/v1/pki/alerts/${alertId}`);
return alert;
},
- onSuccess: (_, { projectId, alertId }) => {
- queryClient.invalidateQueries({ queryKey: projectKeys.getProjectPkiAlerts(projectId) });
+ onSuccess: (alert, { alertId }) => {
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectPkiAlerts(alert.projectId) });
queryClient.invalidateQueries({ queryKey: pkiAlertKeys.getPkiAlertById(alertId) });
}
});
diff --git a/frontend/src/hooks/api/pkiAlerts/types.ts b/frontend/src/hooks/api/pkiAlerts/types.ts
index 744c4e598e..db339da02e 100644
--- a/frontend/src/hooks/api/pkiAlerts/types.ts
+++ b/frontend/src/hooks/api/pkiAlerts/types.ts
@@ -10,7 +10,6 @@ export type TPkiAlert = {
};
export type TCreatePkiAlertDTO = {
- projectId: string;
name: string;
pkiCollectionId: string;
alertBeforeDays: number;
@@ -19,7 +18,6 @@ export type TCreatePkiAlertDTO = {
export type TUpdatePkiAlertDTO = {
alertId: string;
- projectId: string;
pkiCollectionId?: string;
name?: string;
alertBeforeDays?: number;
@@ -28,5 +26,4 @@ export type TUpdatePkiAlertDTO = {
export type TDeletePkiAlertDTO = {
alertId: string;
- projectId: string;
};
diff --git a/frontend/src/hooks/api/pkiAlertsV2/mutations.ts b/frontend/src/hooks/api/pkiAlertsV2/mutations.ts
index e840aa7106..c5d05bbd4d 100644
--- a/frontend/src/hooks/api/pkiAlertsV2/mutations.ts
+++ b/frontend/src/hooks/api/pkiAlertsV2/mutations.ts
@@ -10,6 +10,14 @@ export const useCreatePkiAlertV2 = () => {
return useMutation<TPkiAlertV2, unknown, TCreatePkiAlertV2>({
mutationFn: async (data) => {
+ if (data.applicationId) {
+ const { applicationId, ...rest } = data;
+ const { data: response } = await apiRequest.post<{ alert: TPkiAlertV2 }>(
+ `/api/v1/cert-manager/applications/${applicationId}/alerts`,
+ rest
+ );
+ return response.alert;
+ }
const { data: response } = await apiRequest.post<{ alert: TPkiAlertV2 }>(
"/api/v1/cert-manager/alerts",
data
@@ -18,7 +26,9 @@ export const useCreatePkiAlertV2 = () => {
},
onSuccess: (_, variables) => {
queryClient.invalidateQueries({
- queryKey: pkiAlertsV2Keys.allPkiAlertsV2({ projectId: variables.projectId })
+ queryKey: pkiAlertsV2Keys.allPkiAlertsV2({
+ applicationId: variables.applicationId
+ })
});
}
});
@@ -27,8 +37,15 @@ export const useCreatePkiAlertV2 = () => {
export const useUpdatePkiAlertV2 = () => {
const queryClient = useQueryClient();
- return useMutation<TPkiAlertV2, unknown, TUpdatePkiAlertV2>({
- mutationFn: async ({ alertId, ...data }) => {
+ return useMutation<TPkiAlertV2, unknown, TUpdatePkiAlertV2 & { applicationId?: string }>({
+ mutationFn: async ({ alertId, applicationId, ...data }) => {
+ if (applicationId) {
+ const { data: response } = await apiRequest.patch<{ alert: TPkiAlertV2 }>(
+ `/api/v1/cert-manager/applications/${applicationId}/alerts/${alertId}`,
+ data
+ );
+ return response.alert;
+ }
const { data: response } = await apiRequest.patch<{ alert: TPkiAlertV2 }>(
`/api/v1/cert-manager/alerts/${alertId}`,
data
@@ -49,8 +66,14 @@ export const useUpdatePkiAlertV2 = () => {
export const useDeletePkiAlertV2 = () => {
const queryClient = useQueryClient();
- return useMutation<TPkiAlertV2, unknown, TDeletePkiAlertV2>({
- mutationFn: async ({ alertId }) => {
+ return useMutation<TPkiAlertV2, unknown, TDeletePkiAlertV2 & { applicationId?: string }>({
+ mutationFn: async ({ alertId, applicationId }) => {
+ if (applicationId) {
+ const { data } = await apiRequest.delete<{ alert: TPkiAlertV2 }>(
+ `/api/v1/cert-manager/applications/${applicationId}/alerts/${alertId}`
+ );
+ return data.alert;
+ }
const { data } = await apiRequest.delete<{ alert: TPkiAlertV2 }>(
`/api/v1/cert-manager/alerts/${alertId}`
);
@@ -68,7 +91,6 @@ export const useDeletePkiAlertV2 = () => {
};
export interface TTestPkiWebhookConfigV2 {
- projectId: string;
url: string;
signingSecret?: string;
}
@@ -80,10 +102,10 @@ export interface TTestPkiWebhookConfigV2Response {
export const useTestPkiWebhookConfigV2 = () => {
return useMutation<TTestPkiWebhookConfigV2Response, unknown, TTestPkiWebhookConfigV2>({
- mutationFn: async ({ projectId, url, signingSecret }) => {
+ mutationFn: async ({ url, signingSecret }) => {
const { data } = await apiRequest.post<TTestPkiWebhookConfigV2Response>(
"/api/v2/pki/alerts/test-webhook",
- { projectId, url, signingSecret }
+ { url, signingSecret }
);
return data;
}
diff --git a/frontend/src/hooks/api/pkiAlertsV2/queries.ts b/frontend/src/hooks/api/pkiAlertsV2/queries.ts
index a4ca9006f8..6774b95898 100644
--- a/frontend/src/hooks/api/pkiAlertsV2/queries.ts
+++ b/frontend/src/hooks/api/pkiAlertsV2/queries.ts
@@ -24,6 +24,14 @@ export const pkiAlertsV2Keys = {
};
const fetchPkiAlertsV2 = async (params: TGetPkiAlertsV2): Promise<TGetPkiAlertsV2Response> => {
+ if (params.applicationId) {
+ const { applicationId, ...rest } = params;
+ const { data } = await apiRequest.get<TGetPkiAlertsV2Response>(
+ `/api/v1/cert-manager/applications/${applicationId}/alerts`,
+ { params: rest }
+ );
+ return data;
+ }
const { data } = await apiRequest.get<TGetPkiAlertsV2Response>("/api/v1/cert-manager/alerts", {
params
});
@@ -73,7 +81,6 @@ export const useGetPkiAlertsV2 = (
return useQuery({
queryKey: pkiAlertsV2Keys.allPkiAlertsV2(params),
queryFn: () => fetchPkiAlertsV2(params),
- enabled: !!params.projectId,
...options
});
};
@@ -134,7 +141,7 @@ export const useGetPkiAlertV2CurrentMatchingCertificates = (
return useQuery({
queryKey: pkiAlertsV2Keys.pkiAlertV2CurrentMatchingCertificates(params),
queryFn: () => fetchPkiAlertV2CurrentMatchingCertificates(params),
- enabled: !!params.projectId && params.filters !== undefined,
+ enabled: params.filters !== undefined,
placeholderData: (previousData) => previousData,
...options
});
diff --git a/frontend/src/hooks/api/pkiAlertsV2/types.ts b/frontend/src/hooks/api/pkiAlertsV2/types.ts
index 8cbbd70aba..22c2ab880f 100644
--- a/frontend/src/hooks/api/pkiAlertsV2/types.ts
+++ b/frontend/src/hooks/api/pkiAlertsV2/types.ts
@@ -89,6 +89,7 @@ export interface TLastRun {
export interface TPkiAlertV2 {
id: string;
projectId: string;
+ applicationId?: string | null;
name: string;
description?: string;
eventType: PkiAlertEventTypeV2;
@@ -115,7 +116,7 @@ export interface TPkiCertificateMatchV2 {
}
export interface TGetPkiAlertsV2 {
- projectId: string;
+ applicationId?: string;
search?: string;
eventType?: PkiAlertEventTypeV2;
enabled?: boolean;
@@ -133,7 +134,7 @@ export interface TGetPkiAlertV2ById {
}
export interface TCreatePkiAlertV2 {
- projectId: string;
+ applicationId?: string;
name: string;
description?: string;
eventType: PkiAlertEventTypeV2;
@@ -174,7 +175,6 @@ export interface TGetPkiAlertV2MatchingCertificatesResponse {
}
export interface TGetPkiAlertV2CurrentMatchingCertificates {
- projectId: string;
filters: TPkiFilterRuleV2[];
alertBefore?: string;
limit?: number;
@@ -278,7 +278,7 @@ export const pkiAlertChannelV2Schema = z.discriminatedUnion("channelType", [
]);
const basePkiAlertV2Schema = z.object({
- projectId: z.string().uuid(),
+ applicationId: z.string().uuid().optional(),
name: z
.string()
.min(1)
@@ -313,4 +313,4 @@ export const createPkiAlertV2Schema = basePkiAlertV2Schema.superRefine((data, ct
}
});
-export const updatePkiAlertV2Schema = basePkiAlertV2Schema.partial().omit({ projectId: true });
+export const updatePkiAlertV2Schema = basePkiAlertV2Schema.partial();
diff --git a/frontend/src/hooks/api/pkiApplications/index.ts b/frontend/src/hooks/api/pkiApplications/index.ts
new file mode 100644
index 0000000000..177955438b
--- /dev/null
+++ b/frontend/src/hooks/api/pkiApplications/index.ts
@@ -0,0 +1,3 @@
+export * from "./mutations";
+export * from "./queries";
+export * from "./types";
diff --git a/frontend/src/hooks/api/pkiApplications/mutations.ts b/frontend/src/hooks/api/pkiApplications/mutations.ts
new file mode 100644
index 0000000000..2ec0c67c40
--- /dev/null
+++ b/frontend/src/hooks/api/pkiApplications/mutations.ts
@@ -0,0 +1,268 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { pkiApplicationKeys } from "./queries";
+import {
+ TAddPkiApplicationMemberDTO,
+ TAttachPkiApplicationProfilesDTO,
+ TClearEnrollmentMethodDTO,
+ TCreatePkiApplicationDTO,
+ TDeletePkiApplicationDTO,
+ TDetachPkiApplicationProfileDTO,
+ TPkiApplication,
+ TPkiApplicationMember,
+ TPkiApplicationProfile,
+ TPkiApplicationResponse,
+ TRemovePkiApplicationMemberDTO,
+ TRevealAcmeEabSecretResponse,
+ TSetAcmeEnrollmentDTO,
+ TSetApiEnrollmentDTO,
+ TSetEstEnrollmentDTO,
+ TSetScepEnrollmentDTO,
+ TUpdatePkiApplicationDTO,
+ TUpdatePkiApplicationMemberRoleDTO
+} from "./types";
+
+const BASE_URL = "/api/v1/cert-manager/applications";
+
+const invalidateAll = (qc: ReturnType<typeof useQueryClient>) =>
+ qc.invalidateQueries({ queryKey: pkiApplicationKeys.all });
+
+export const useCreatePkiApplication = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async (dto: TCreatePkiApplicationDTO) => {
+ const { data } = await apiRequest.post<TPkiApplicationResponse>(BASE_URL, dto);
+ return data.application;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useUpdatePkiApplication = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, ...body }: TUpdatePkiApplicationDTO) => {
+ const { data } = await apiRequest.patch<TPkiApplicationResponse>(
+ `${BASE_URL}/${applicationId}`,
+ body
+ );
+ return data.application;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useDeletePkiApplication = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId }: TDeletePkiApplicationDTO) => {
+ const { data } = await apiRequest.delete<{ application: TPkiApplication }>(
+ `${BASE_URL}/${applicationId}`
+ );
+ return data.application;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useAttachPkiApplicationProfiles = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, ...body }: TAttachPkiApplicationProfilesDTO) => {
+ const { data } = await apiRequest.post<{ profiles: TPkiApplicationProfile[] }>(
+ `${BASE_URL}/${applicationId}/profiles`,
+ body
+ );
+ return data.profiles;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useDetachPkiApplicationProfile = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, profileId }: TDetachPkiApplicationProfileDTO) => {
+ const { data } = await apiRequest.delete<{ applicationId: string; profileId: string }>(
+ `${BASE_URL}/${applicationId}/profiles/${profileId}`
+ );
+ return data;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useAddPkiApplicationMember = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, ...body }: TAddPkiApplicationMemberDTO) => {
+ const { data } = await apiRequest.post<{ membership: TPkiApplicationMember }>(
+ `${BASE_URL}/${applicationId}/memberships`,
+ body
+ );
+ return data.membership;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useUpdatePkiApplicationMemberRole = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({
+ applicationId,
+ membershipId,
+ ...body
+ }: TUpdatePkiApplicationMemberRoleDTO) => {
+ const { data } = await apiRequest.patch<{ membership: TPkiApplicationMember }>(
+ `${BASE_URL}/${applicationId}/memberships/${membershipId}`,
+ body
+ );
+ return data.membership;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useRemovePkiApplicationMember = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, membershipId }: TRemovePkiApplicationMemberDTO) => {
+ const { data } = await apiRequest.delete<{
+ membershipId: string;
+ applicationId: string;
+ }>(`${BASE_URL}/${applicationId}/memberships/${membershipId}`);
+ return data;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+const enrollmentBase = (applicationId: string, profileId: string) =>
+ `${BASE_URL}/${applicationId}/profiles/${profileId}/enrollment`;
+
+export const useSetPkiApplicationApiEnrollment = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, profileId, ...body }: TSetApiEnrollmentDTO) => {
+ const { data } = await apiRequest.put(
+ `${enrollmentBase(applicationId, profileId)}/api`,
+ body
+ );
+ return data;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useClearPkiApplicationApiEnrollment = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, profileId }: TClearEnrollmentMethodDTO) => {
+ const { data } = await apiRequest.delete(`${enrollmentBase(applicationId, profileId)}/api`);
+ return data;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useSetPkiApplicationEstEnrollment = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, profileId, ...body }: TSetEstEnrollmentDTO) => {
+ const { data } = await apiRequest.put(
+ `${enrollmentBase(applicationId, profileId)}/est`,
+ body
+ );
+ return data;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useClearPkiApplicationEstEnrollment = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, profileId }: TClearEnrollmentMethodDTO) => {
+ const { data } = await apiRequest.delete(`${enrollmentBase(applicationId, profileId)}/est`);
+ return data;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useSetPkiApplicationAcmeEnrollment = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, profileId, ...body }: TSetAcmeEnrollmentDTO) => {
+ const { data } = await apiRequest.put(
+ `${enrollmentBase(applicationId, profileId)}/acme`,
+ body
+ );
+ return data;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useClearPkiApplicationAcmeEnrollment = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, profileId }: TClearEnrollmentMethodDTO) => {
+ const { data } = await apiRequest.delete(`${enrollmentBase(applicationId, profileId)}/acme`);
+ return data;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useRevealPkiApplicationAcmeEabSecret = () => {
+ return useMutation({
+ mutationFn: async ({ applicationId, profileId }: TClearEnrollmentMethodDTO) => {
+ const { data } = await apiRequest.post<TRevealAcmeEabSecretResponse>(
+ `${enrollmentBase(applicationId, profileId)}/acme/eab/reveal`
+ );
+ return data;
+ }
+ });
+};
+
+export const useRotatePkiApplicationAcmeEabSecret = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, profileId }: TClearEnrollmentMethodDTO) => {
+ const { data } = await apiRequest.post(
+ `${enrollmentBase(applicationId, profileId)}/acme/eab/rotate`
+ );
+ return data;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useSetPkiApplicationScepEnrollment = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, profileId, ...body }: TSetScepEnrollmentDTO) => {
+ const { data } = await apiRequest.put(
+ `${enrollmentBase(applicationId, profileId)}/scep`,
+ body
+ );
+ return data;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
+
+export const useClearPkiApplicationScepEnrollment = () => {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ applicationId, profileId }: TClearEnrollmentMethodDTO) => {
+ const { data } = await apiRequest.delete(`${enrollmentBase(applicationId, profileId)}/scep`);
+ return data;
+ },
+ onSuccess: () => invalidateAll(qc)
+ });
+};
diff --git a/frontend/src/hooks/api/pkiApplications/queries.ts b/frontend/src/hooks/api/pkiApplications/queries.ts
new file mode 100644
index 0000000000..903b3f6193
--- /dev/null
+++ b/frontend/src/hooks/api/pkiApplications/queries.ts
@@ -0,0 +1,137 @@
+import { useQuery, UseQueryOptions } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import {
+ TListPkiApplicationsResponse,
+ TPkiApplication,
+ TPkiApplicationEnrollmentState,
+ TPkiApplicationListItem,
+ TPkiApplicationMember,
+ TPkiApplicationProfile
+} from "./types";
+
+export const pkiApplicationKeys = {
+ all: ["pki-applications"] as const,
+ list: (search?: string) => [...pkiApplicationKeys.all, "list", { search }] as const,
+ byId: (applicationId: string) => [...pkiApplicationKeys.all, "by-id", { applicationId }] as const,
+ bySlug: (slug: string) => [...pkiApplicationKeys.all, "by-slug", { slug }] as const,
+ profiles: (applicationId: string) =>
+ [...pkiApplicationKeys.all, "profiles", { applicationId }] as const,
+ members: (applicationId: string) =>
+ [...pkiApplicationKeys.all, "members", { applicationId }] as const,
+ enrollment: (applicationId: string, profileId: string) =>
+ [...pkiApplicationKeys.all, "enrollment", { applicationId, profileId }] as const
+};
+
+const BASE_URL = "/api/v1/cert-manager/applications";
+
+export const useListPkiApplications = (
+ search?: string,
+ options?: Omit<
+ UseQueryOptions<
+ TListPkiApplicationsResponse,
+ unknown,
+ TPkiApplicationListItem[],
+ ReturnType<typeof pkiApplicationKeys.list>
+ >,
+ "queryKey" | "queryFn"
+ >
+) =>
+ useQuery({
+ queryKey: pkiApplicationKeys.list(search),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TListPkiApplicationsResponse>(BASE_URL, {
+ params: { search }
+ });
+ return data;
+ },
+ select: (data) => data.applications,
+ ...options
+ });
+
+export const useGetPkiApplication = (
+ applicationId: string,
+ options?: Omit<
+ UseQueryOptions<
+ { application: TPkiApplication },
+ unknown,
+ TPkiApplication,
+ ReturnType<typeof pkiApplicationKeys.byId>
+ >,
+ "queryKey" | "queryFn"
+ >
+) =>
+ useQuery({
+ queryKey: pkiApplicationKeys.byId(applicationId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ application: TPkiApplication }>(
+ `${BASE_URL}/${applicationId}`
+ );
+ return data;
+ },
+ enabled: Boolean(applicationId),
+ select: (data) => data.application,
+ ...options
+ });
+
+export const useGetPkiApplicationBySlug = (
+ slug: string,
+ options?: Omit<
+ UseQueryOptions<
+ { application: TPkiApplication },
+ unknown,
+ TPkiApplication,
+ ReturnType<typeof pkiApplicationKeys.bySlug>
+ >,
+ "queryKey" | "queryFn"
+ >
+) =>
+ useQuery({
+ queryKey: pkiApplicationKeys.bySlug(slug),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ application: TPkiApplication }>(
+ `${BASE_URL}/slug/${slug}`
+ );
+ return data;
+ },
+ enabled: Boolean(slug),
+ select: (data) => data.application,
+ ...options
+ });
+
+export const useListPkiApplicationProfiles = (applicationId: string) =>
+ useQuery({
+ queryKey: pkiApplicationKeys.profiles(applicationId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ profiles: TPkiApplicationProfile[] }>(
+ `${BASE_URL}/${applicationId}/profiles`
+ );
+ return data.profiles;
+ },
+ enabled: Boolean(applicationId)
+ });
+
+export const useListPkiApplicationMembers = (applicationId: string) =>
+ useQuery({
+ queryKey: pkiApplicationKeys.members(applicationId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ memberships: TPkiApplicationMember[] }>(
+ `${BASE_URL}/${applicationId}/memberships`
+ );
+ return data.memberships;
+ },
+ enabled: Boolean(applicationId)
+ });
+
+export const useGetPkiApplicationEnrollment = (applicationId: string, profileId: string) =>
+ useQuery({
+ queryKey: pkiApplicationKeys.enrollment(applicationId, profileId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TPkiApplicationEnrollmentState>(
+ `${BASE_URL}/${applicationId}/profiles/${profileId}/enrollment`
+ );
+ return data;
+ },
+ enabled: Boolean(applicationId && profileId)
+ });
diff --git a/frontend/src/hooks/api/pkiApplications/types.ts b/frontend/src/hooks/api/pkiApplications/types.ts
new file mode 100644
index 0000000000..3e44ce4c75
--- /dev/null
+++ b/frontend/src/hooks/api/pkiApplications/types.ts
@@ -0,0 +1,175 @@
+export type TPkiApplication = {
+ id: string;
+ projectId: string;
+ name: string;
+ slug: string;
+ description?: string | null;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type TPkiApplicationListItem = TPkiApplication & {
+ profileCount: number;
+ memberCount: number;
+ certificateCount: number;
+};
+
+export type TPkiApplicationProfile = {
+ applicationId: string;
+ profileId: string;
+ profileSlug: string;
+ profileDescription?: string | null;
+ estConfigId?: string | null;
+ apiConfigId?: string | null;
+ acmeConfigId?: string | null;
+ scepConfigId?: string | null;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type TPkiApplicationMemberDetails = {
+ name: string | null;
+ email?: string | null;
+ username?: string | null;
+ authMethod?: string | null;
+ slug?: string | null;
+};
+
+export type TPkiApplicationMember = {
+ membershipId: string;
+ applicationId: string;
+ actorUserId?: string | null;
+ actorIdentityId?: string | null;
+ actorGroupId?: string | null;
+ role: string;
+ customRoleId?: string | null;
+ createdAt: string;
+ updatedAt: string;
+ details?: TPkiApplicationMemberDetails | null;
+};
+
+export type ScepChallengeType = "static" | "dynamic";
+
+export type TPkiApplicationEnrollmentState = {
+ applicationId: string;
+ profileId: string;
+ api: { id: string; autoRenew: boolean; renewBeforeDays: number | null } | null;
+ est: { id: string; disableBootstrapCaValidation: boolean } | null;
+ acme: {
+ id: string;
+ skipDnsOwnershipVerification: boolean;
+ skipEabBinding: boolean;
+ } | null;
+ scep: {
+ id: string;
+ challengeType: ScepChallengeType;
+ includeCaCertInResponse: boolean;
+ allowCertBasedRenewal: boolean;
+ dynamicChallengeExpiryMinutes: number | null;
+ dynamicChallengeMaxPending: number | null;
+ } | null;
+ estConfigured: boolean;
+ acmeConfigured: boolean;
+ scepConfigured: boolean;
+};
+
+export type TCreatePkiApplicationDTO = {
+ name: string;
+ slug: string;
+ description?: string;
+ profileIds?: string[];
+};
+
+export type TUpdatePkiApplicationDTO = {
+ applicationId: string;
+ name?: string;
+ slug?: string;
+ description?: string | null;
+};
+
+export type TDeletePkiApplicationDTO = {
+ applicationId: string;
+};
+
+export type TAttachPkiApplicationProfilesDTO = {
+ applicationId: string;
+ profileIds: string[];
+};
+
+export type TDetachPkiApplicationProfileDTO = {
+ applicationId: string;
+ profileId: string;
+};
+
+export type TAddPkiApplicationMemberDTO = {
+ applicationId: string;
+ userId?: string;
+ identityId?: string;
+ groupId?: string;
+ role: string;
+};
+
+export type TUpdatePkiApplicationMemberRoleDTO = {
+ applicationId: string;
+ membershipId: string;
+ role: string;
+};
+
+export type TRemovePkiApplicationMemberDTO = {
+ applicationId: string;
+ membershipId: string;
+};
+
+export type TListPkiApplicationsResponse = {
+ applications: TPkiApplicationListItem[];
+ total: number;
+};
+
+export type TPkiApplicationResponse = {
+ application: TPkiApplication;
+};
+
+export type TSetApiEnrollmentDTO = {
+ applicationId: string;
+ profileId: string;
+ autoRenew: boolean;
+ renewBeforeDays?: number;
+};
+
+export type TClearEnrollmentMethodDTO = {
+ applicationId: string;
+ profileId: string;
+};
+
+export type TSetEstEnrollmentDTO = {
+ applicationId: string;
+ profileId: string;
+ passphrase: string;
+ disableBootstrapCaValidation?: boolean;
+ caChain?: string;
+};
+
+export type TSetAcmeEnrollmentDTO = {
+ applicationId: string;
+ profileId: string;
+ skipDnsOwnershipVerification?: boolean;
+ skipEabBinding?: boolean;
+};
+
+export type TRevealAcmeEabSecretResponse = {
+ applicationId: string;
+ profileId: string;
+ eabKid: string;
+ eabSecret: string;
+};
+
+export type TSetScepEnrollmentDTO = {
+ applicationId: string;
+ profileId: string;
+ challengeType?: ScepChallengeType;
+ challengePassword?: string;
+ includeCaCertInResponse?: boolean;
+ allowCertBasedRenewal?: boolean;
+ dynamicChallengeExpiryMinutes?: number;
+ dynamicChallengeMaxPending?: number;
+};
diff --git a/frontend/src/hooks/api/pkiCollections/mutations.tsx b/frontend/src/hooks/api/pkiCollections/mutations.tsx
index a06afcd091..f5cf4602fe 100644
--- a/frontend/src/hooks/api/pkiCollections/mutations.tsx
+++ b/frontend/src/hooks/api/pkiCollections/mutations.tsx
@@ -24,9 +24,9 @@ export const useCreatePkiCollection = () => {
);
return pkiCollection;
},
- onSuccess: (_, { projectId }) => {
+ onSuccess: (pkiCollection) => {
queryClient.invalidateQueries({
- queryKey: projectKeys.getProjectPkiCollections(projectId)
+ queryKey: projectKeys.getProjectPkiCollections(pkiCollection.projectId)
});
}
});
@@ -42,9 +42,9 @@ export const useUpdatePkiCollection = () => {
);
return pkiCollection;
},
- onSuccess: (_, { projectId, collectionId }) => {
+ onSuccess: (pkiCollection, { collectionId }) => {
queryClient.invalidateQueries({
- queryKey: projectKeys.getProjectPkiCollections(projectId)
+ queryKey: projectKeys.getProjectPkiCollections(pkiCollection.projectId)
});
queryClient.invalidateQueries({
queryKey: pkiCollectionKeys.getPkiCollectionById(collectionId)
@@ -62,9 +62,9 @@ export const useDeletePkiCollection = () => {
);
return pkiCollection;
},
- onSuccess: (_, { projectId, collectionId }) => {
+ onSuccess: (pkiCollection, { collectionId }) => {
queryClient.invalidateQueries({
- queryKey: projectKeys.getProjectPkiCollections(projectId)
+ queryKey: projectKeys.getProjectPkiCollections(pkiCollection.projectId)
});
queryClient.invalidateQueries({
queryKey: pkiCollectionKeys.getPkiCollectionById(collectionId)
diff --git a/frontend/src/hooks/api/pkiCollections/types.ts b/frontend/src/hooks/api/pkiCollections/types.ts
index 98a98d520b..97236a0760 100644
--- a/frontend/src/hooks/api/pkiCollections/types.ts
+++ b/frontend/src/hooks/api/pkiCollections/types.ts
@@ -8,21 +8,18 @@ export type TPkiCollection = {
};
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 = {
diff --git a/frontend/src/hooks/api/pkiSubscriber/mutations.tsx b/frontend/src/hooks/api/pkiSubscriber/mutations.tsx
index 57d086780a..efb083f6bd 100644
--- a/frontend/src/hooks/api/pkiSubscriber/mutations.tsx
+++ b/frontend/src/hooks/api/pkiSubscriber/mutations.tsx
@@ -26,8 +26,7 @@ export const useCreatePkiSubscriber = () => {
});
queryClient.invalidateQueries({
queryKey: pkiSubscriberKeys.getPkiSubscriber({
- subscriberName: name,
- projectId
+ subscriberName: name
})
});
}
@@ -50,8 +49,7 @@ export const useUpdatePkiSubscriber = () => {
});
queryClient.invalidateQueries({
queryKey: pkiSubscriberKeys.getPkiSubscriber({
- subscriberName: name,
- projectId
+ subscriberName: name
})
});
}
@@ -61,14 +59,9 @@ export const useUpdatePkiSubscriber = () => {
export const useDeletePkiSubscriber = () => {
const queryClient = useQueryClient();
return useMutation<TPkiSubscriber, object, TDeletePkiSubscriberDTO>({
- mutationFn: async ({ subscriberName, projectId }) => {
+ mutationFn: async ({ subscriberName }) => {
const { data: subscriber } = await apiRequest.delete(
- `/api/v1/pki/subscribers/${subscriberName}`,
- {
- data: {
- projectId
- }
- }
+ `/api/v1/pki/subscribers/${subscriberName}`
);
return subscriber;
},
@@ -78,8 +71,7 @@ export const useDeletePkiSubscriber = () => {
});
queryClient.invalidateQueries({
queryKey: pkiSubscriberKeys.getPkiSubscriber({
- subscriberName: name,
- projectId
+ subscriberName: name
})
});
}
@@ -89,20 +81,17 @@ export const useDeletePkiSubscriber = () => {
export const useIssuePkiSubscriberCert = () => {
const queryClient = useQueryClient();
return useMutation<TCreateCertificateResponse, object, TIssuePkiSubscriberCertDTO>({
- mutationFn: async ({ subscriberName, projectId }) => {
+ mutationFn: async ({ subscriberName }) => {
const { data } = await apiRequest.post(
`/api/v1/pki/subscribers/${subscriberName}/issue-certificate`,
- {
- projectId
- }
+ {}
);
return data;
},
- onSuccess: (_, { subscriberName, projectId }) => {
+ onSuccess: (_, { subscriberName }) => {
queryClient.invalidateQueries({
queryKey: pkiSubscriberKeys.forPkiSubscriberCertificates({
- subscriberName,
- projectId
+ subscriberName
})
});
}
@@ -111,12 +100,10 @@ export const useIssuePkiSubscriberCert = () => {
export const useOrderPkiSubscriberCert = () => {
return useMutation<{ message: string }, object, TIssuePkiSubscriberCertDTO>({
- mutationFn: async ({ subscriberName, projectId }) => {
+ mutationFn: async ({ subscriberName }) => {
const { data } = await apiRequest.post(
`/api/v1/pki/subscribers/${subscriberName}/order-certificate`,
- {
- projectId
- }
+ {}
);
return data;
}
diff --git a/frontend/src/hooks/api/pkiSubscriber/queries.tsx b/frontend/src/hooks/api/pkiSubscriber/queries.tsx
index ee67915526..f60c734a36 100644
--- a/frontend/src/hooks/api/pkiSubscriber/queries.tsx
+++ b/frontend/src/hooks/api/pkiSubscriber/queries.tsx
@@ -7,62 +7,43 @@ import { TCertificate } from "../certificates/types";
import { TPkiSubscriber } from "./types";
export const pkiSubscriberKeys = {
- getPkiSubscriber: ({
- subscriberName,
- projectId
- }: {
- subscriberName: string;
- projectId: string;
- }) => [{ subscriberName, projectId }, "pki-subscriber"] as const,
+ getPkiSubscriber: ({ subscriberName }: { subscriberName: string }) =>
+ [{ subscriberName }, "pki-subscriber"] as const,
allPkiSubscriberCertificates: () => ["pki-subscriber-certificates"] as const,
- forPkiSubscriberCertificates: ({
- subscriberName,
- projectId
- }: {
- subscriberName: string;
- projectId: string;
- }) => [...pkiSubscriberKeys.allPkiSubscriberCertificates(), subscriberName, projectId] as const,
+ forPkiSubscriberCertificates: ({ subscriberName }: { subscriberName: string }) =>
+ [...pkiSubscriberKeys.allPkiSubscriberCertificates(), subscriberName] as const,
specificPkiSubscriberCertificates: ({
subscriberName,
- projectId,
offset,
limit
}: {
subscriberName: string;
- projectId: string;
offset: number;
limit: number;
}) =>
[
- ...pkiSubscriberKeys.forPkiSubscriberCertificates({ subscriberName, projectId }),
- { offset, limit, projectId }
+ ...pkiSubscriberKeys.forPkiSubscriberCertificates({ subscriberName }),
+ { offset, limit }
] as const
};
export const useGetPkiSubscriber = (
{
- subscriberName,
- projectId
+ subscriberName
}: {
subscriberName: string;
- projectId: string;
},
options?: TReactQueryOptions["options"]
) => {
return useQuery({
- queryKey: pkiSubscriberKeys.getPkiSubscriber({ subscriberName, projectId }),
+ queryKey: pkiSubscriberKeys.getPkiSubscriber({ subscriberName }),
queryFn: async () => {
const { data: pkiSubscriber } = await apiRequest.get<TPkiSubscriber>(
- `/api/v1/pki/subscribers/${subscriberName}`,
- {
- params: {
- projectId
- }
- }
+ `/api/v1/pki/subscribers/${subscriberName}`
);
return pkiSubscriber;
},
- enabled: Boolean(subscriberName) && Boolean(projectId),
+ enabled: Boolean(subscriberName),
...options
});
};
@@ -70,12 +51,10 @@ export const useGetPkiSubscriber = (
export const useGetPkiSubscriberCertificates = (
{
subscriberName,
- projectId,
offset,
limit
}: {
subscriberName: string;
- projectId: string;
offset: number;
limit: number;
},
@@ -84,15 +63,13 @@ export const useGetPkiSubscriberCertificates = (
return useQuery({
queryKey: pkiSubscriberKeys.specificPkiSubscriberCertificates({
subscriberName,
- projectId,
offset,
limit
}),
queryFn: async () => {
const params = new URLSearchParams({
offset: String(offset),
- limit: String(limit),
- projectId
+ limit: String(limit)
});
const {
@@ -105,7 +82,7 @@ export const useGetPkiSubscriberCertificates = (
);
return { certificates, totalCount };
},
- enabled: Boolean(subscriberName) && Boolean(projectId),
+ enabled: Boolean(subscriberName),
...options
});
};
diff --git a/frontend/src/hooks/api/pkiSubscriber/types.ts b/frontend/src/hooks/api/pkiSubscriber/types.ts
index 239d56148e..8da56d0b5f 100644
--- a/frontend/src/hooks/api/pkiSubscriber/types.ts
+++ b/frontend/src/hooks/api/pkiSubscriber/types.ts
@@ -41,7 +41,6 @@ export type TPkiSubscriber = {
};
export type TCreatePkiSubscriberDTO = {
- projectId: string;
caId: string;
name: string;
commonName: string;
@@ -56,7 +55,6 @@ export type TCreatePkiSubscriberDTO = {
export type TUpdatePkiSubscriberDTO = {
subscriberName: string;
- projectId: string;
caId?: string;
name?: string;
commonName?: string;
@@ -72,15 +70,12 @@ export type TUpdatePkiSubscriberDTO = {
export type TDeletePkiSubscriberDTO = {
subscriberName: string;
- projectId: string;
};
export type TIssuePkiSubscriberCertDTO = {
subscriberName: string;
- projectId: string;
};
export type TOrderPkiSubscriberCertDTO = {
subscriberName: string;
- projectId: string;
};
diff --git a/frontend/src/hooks/api/pkiSyncs/types/common.ts b/frontend/src/hooks/api/pkiSyncs/types/common.ts
index 1da5180451..2e3113d667 100644
--- a/frontend/src/hooks/api/pkiSyncs/types/common.ts
+++ b/frontend/src/hooks/api/pkiSyncs/types/common.ts
@@ -30,6 +30,7 @@ export type TRootPkiSync = {
updatedAt: string;
isAutoSyncEnabled: boolean;
projectId: string;
+ applicationId?: string | null;
subscriberId?: string | null;
syncStatus: PkiSyncStatus | null;
lastSyncJobId: string | null;
diff --git a/frontend/src/hooks/api/pkiSyncs/types/index.ts b/frontend/src/hooks/api/pkiSyncs/types/index.ts
index a9362e0965..94de25a903 100644
--- a/frontend/src/hooks/api/pkiSyncs/types/index.ts
+++ b/frontend/src/hooks/api/pkiSyncs/types/index.ts
@@ -59,6 +59,7 @@ type TCreatePkiSyncDTOBase = {
subscriberId?: string | null;
certificateIds?: string[];
projectId: string;
+ applicationId?: string;
};
export type TCreatePkiSyncDTO = TCreatePkiSyncDTOBase & {
diff --git a/frontend/src/hooks/api/projectIdentityMembership/mutations.tsx b/frontend/src/hooks/api/projectIdentityMembership/mutations.tsx
index 54b9158de4..97d1b64133 100644
--- a/frontend/src/hooks/api/projectIdentityMembership/mutations.tsx
+++ b/frontend/src/hooks/api/projectIdentityMembership/mutations.tsx
@@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { identitiesKeys, projectKeys } from "@app/hooks/api";
+import { identityMembershipsBase } from "@app/hooks/api/certManagerAccess";
import { projectIdentityQuery } from "@app/hooks/api/projectIdentity";
import {
@@ -14,11 +15,16 @@ import {
export const useCreateProjectIdentityMembership = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ identityId, projectId, role }: TCreateProjectIdentityMembershipDTO) => {
+ mutationFn: async ({
+ identityId,
+ projectId,
+ projectType,
+ role
+ }: TCreateProjectIdentityMembershipDTO) => {
const {
data: { identityMembership }
} = await apiRequest.post<{ identityMembership: TProjectIdentityMembership }>(
- `/api/v1/projects/${projectId}/memberships/identities/${identityId}`,
+ `${identityMembershipsBase(projectType, projectId)}/${identityId}`,
{
role
}
@@ -43,13 +49,14 @@ export const useUpdateProjectIdentityMembership = () => {
return useMutation({
mutationFn: async ({
projectId,
+ projectType,
identityId,
...updates
}: TUpdateProjectIdentityMembershipDTO) => {
const {
data: { identityMembership }
} = await apiRequest.patch<{ identityMembership: TProjectIdentityMembership }>(
- `/api/v1/projects/${projectId}/memberships/identities/${identityId}`,
+ `${identityMembershipsBase(projectType, projectId)}/${identityId}`,
updates
);
return identityMembership;
@@ -72,11 +79,15 @@ export const useUpdateProjectIdentityMembership = () => {
export const useDeleteProjectIdentityMembership = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ identityId, projectId }: TDeleteProjectIdentityMembershipDTO) => {
+ mutationFn: async ({
+ identityId,
+ projectId,
+ projectType
+ }: TDeleteProjectIdentityMembershipDTO) => {
const {
data: { identityMembership }
} = await apiRequest.delete<{ identityMembership: TProjectIdentityMembership }>(
- `/api/v1/projects/${projectId}/memberships/identities/${identityId}`
+ `${identityMembershipsBase(projectType, projectId)}/${identityId}`
);
return identityMembership;
},
diff --git a/frontend/src/hooks/api/projectIdentityMembership/queries.ts b/frontend/src/hooks/api/projectIdentityMembership/queries.ts
index 27e8e60db7..366c3386e6 100644
--- a/frontend/src/hooks/api/projectIdentityMembership/queries.ts
+++ b/frontend/src/hooks/api/projectIdentityMembership/queries.ts
@@ -6,6 +6,7 @@ import {
TAvailableProjectIdentities,
TListAvailableProjectIdentitiesDTO
} from "@app/hooks/api";
+import { availableIdentitiesUrl, identityMembershipsBase } from "@app/hooks/api/certManagerAccess";
import { OrderByDirection } from "@app/hooks/api/generic/types";
import {
IdentityProjectMembershipV1,
@@ -23,7 +24,7 @@ export const projectIdentityMembershipQuery = {
queryFn: async () => {
const { data } = await apiRequest.get<{
identities: TAvailableProjectIdentities;
- }>(`/api/v1/projects/${params.projectId}/memberships/available-identities`, {
+ }>(availableIdentitiesUrl(params.projectType, params.projectId), {
params: {
offset: params.offset,
limit: params.limit,
@@ -40,6 +41,7 @@ export const projectIdentityMembershipQuery = {
export const useListProjectIdentityMemberships = (
{
projectId,
+ projectType,
offset = 0,
limit = 100,
orderBy = ProjectIdentityOrderBy.Name,
@@ -81,7 +83,7 @@ export const useListProjectIdentityMemberships = (
}
const { data } = await apiRequest.get<TProjectIdentityMembershipsListV2>(
- `/api/v1/projects/${projectId}/memberships/identities`,
+ identityMembershipsBase(projectType, projectId),
{ params }
);
return data;
@@ -106,7 +108,11 @@ export const useGetProjectIdentityMembership = (projectId: string, identityId: s
});
};
-export const useGetProjectIdentityMembershipV2 = (projectId: string, identityId: string) => {
+export const useGetProjectIdentityMembershipV2 = (
+ projectId: string,
+ identityId: string,
+ projectType?: string
+) => {
return useQuery({
enabled: Boolean(projectId && identityId),
queryKey: projectKeys.getProjectIdentityMembershipDetailsV2(projectId, identityId),
@@ -114,7 +120,7 @@ export const useGetProjectIdentityMembershipV2 = (projectId: string, identityId:
const {
data: { identityMembership }
} = await apiRequest.get<{ identityMembership: IdentityProjectMembershipV1 }>(
- `/api/v1/projects/${projectId}/memberships/identities/${identityId}`
+ `${identityMembershipsBase(projectType, projectId)}/${identityId}`
);
return identityMembership;
}
diff --git a/frontend/src/hooks/api/projectIdentityMembership/types.ts b/frontend/src/hooks/api/projectIdentityMembership/types.ts
index 0c01867596..4adafcb682 100644
--- a/frontend/src/hooks/api/projectIdentityMembership/types.ts
+++ b/frontend/src/hooks/api/projectIdentityMembership/types.ts
@@ -12,22 +12,26 @@ export type TProjectIdentityMembership = {
export type TCreateProjectIdentityMembershipDTO = {
identityId: string;
projectId: string;
+ projectType?: string;
role?: string;
};
export type TUpdateProjectIdentityMembershipDTO = {
identityId: string;
projectId: string;
+ projectType?: string;
roles: TRoles;
};
export type TDeleteProjectIdentityMembershipDTO = {
identityId: string;
projectId: string;
+ projectType?: string;
};
export type TListAvailableProjectIdentitiesDTO = {
projectId: string;
+ projectType?: string;
offset?: number;
limit?: number;
identityName?: string;
diff --git a/frontend/src/hooks/api/projects/mutations.tsx b/frontend/src/hooks/api/projects/mutations.tsx
index 1a0a6ed2f2..e9298dcea2 100644
--- a/frontend/src/hooks/api/projects/mutations.tsx
+++ b/frontend/src/hooks/api/projects/mutations.tsx
@@ -1,6 +1,7 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
+import { groupMembershipsBase } from "@app/hooks/api/certManagerAccess";
import { groupKeys } from "../groups/queries";
import { TGroupMembership } from "../groups/types";
@@ -18,15 +19,17 @@ export const useAddGroupToWorkspace = () => {
mutationFn: async ({
groupId,
projectId,
+ projectType,
role
}: {
groupId: string;
projectId: string;
+ projectType?: string;
role?: string;
}) => {
const {
data: { groupMembership }
- } = await apiRequest.post(`/api/v1/projects/${projectId}/memberships/groups/${groupId}`, {
+ } = await apiRequest.post(`${groupMembershipsBase(projectType, projectId)}/${groupId}`, {
role
});
@@ -44,9 +47,14 @@ export const useAddGroupToWorkspace = () => {
export const useUpdateGroupWorkspaceRole = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ groupId, projectId, roles }: TUpdateWorkspaceGroupRoleDTO) => {
+ mutationFn: async ({
+ groupId,
+ projectId,
+ projectType,
+ roles
+ }: TUpdateWorkspaceGroupRoleDTO) => {
const { data } = await apiRequest.patch<{ roles: TGroupMembership["roles"] }>(
- `/api/v1/projects/${projectId}/memberships/groups/${groupId}`,
+ `${groupMembershipsBase(projectType, projectId)}/${groupId}`,
{ roles }
);
@@ -68,15 +76,17 @@ export const useDeleteGroupFromWorkspace = () => {
return useMutation({
mutationFn: async ({
groupId,
- projectId
+ projectId,
+ projectType
}: {
groupId: string;
projectId: string;
+ projectType?: string;
username?: string;
}) => {
const {
data: { groupMembership }
- } = await apiRequest.delete(`/api/v1/projects/${projectId}/memberships/groups/${groupId}`);
+ } = await apiRequest.delete(`${groupMembershipsBase(projectType, projectId)}/${groupId}`);
return groupMembership;
},
onSuccess: (_, { projectId, username, groupId }) => {
diff --git a/frontend/src/hooks/api/projects/queries.tsx b/frontend/src/hooks/api/projects/queries.tsx
index 19e6772cdd..c21d6e2704 100644
--- a/frontend/src/hooks/api/projects/queries.tsx
+++ b/frontend/src/hooks/api/projects/queries.tsx
@@ -1,6 +1,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
+import { groupMembershipsBase, userMembershipsBase } from "@app/hooks/api/certManagerAccess";
import { CaStatus } from "../ca/enums";
import { TCertificateAuthority } from "../ca/types";
@@ -382,14 +383,18 @@ export const useGetWorkspaceUsers = (
});
};
-export const useGetWorkspaceUserDetails = (projectId: string, membershipId: string) => {
+export const useGetWorkspaceUserDetails = (
+ projectId: string,
+ membershipId: string,
+ projectType?: string
+) => {
return useQuery({
queryKey: projectKeys.getProjectUserDetails(projectId, membershipId),
queryFn: async () => {
const {
data: { membership }
} = await apiRequest.get<{ membership: TWorkspaceUser }>(
- `/api/v1/projects/${projectId}/memberships/${membershipId}`
+ `${userMembershipsBase(projectType, projectId)}/${membershipId}`
);
return membership;
},
@@ -403,15 +408,17 @@ export const useDeleteUserFromWorkspace = () => {
return useMutation({
mutationFn: async ({
usernames,
- projectId
+ projectId,
+ projectType
}: {
projectId: string;
+ projectType?: string;
usernames: string[];
orgId: string;
}) => {
const {
data: { deletedMembership }
- } = await apiRequest.delete(`/api/v1/projects/${projectId}/memberships`, {
+ } = await apiRequest.delete(userMembershipsBase(projectType, projectId), {
data: { usernames }
});
return deletedMembership;
@@ -428,11 +435,16 @@ export const useDeleteUserFromWorkspace = () => {
export const useUpdateUserWorkspaceRole = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ membershipId, roles, projectId }: TUpdateWorkspaceUserRoleDTO) => {
+ mutationFn: async ({
+ membershipId,
+ roles,
+ projectId,
+ projectType
+ }: TUpdateWorkspaceUserRoleDTO) => {
const {
data: { membership }
} = await apiRequest.patch<{ membership: { projectId: string } }>(
- `/api/v1/projects/${projectId}/memberships/${membershipId}`,
+ `${userMembershipsBase(projectType, projectId)}/${membershipId}`,
{
roles
}
@@ -448,7 +460,11 @@ export const useUpdateUserWorkspaceRole = () => {
});
};
-export const useGetWorkspaceGroupMembershipDetails = (projectId: string, groupId: string) => {
+export const useGetWorkspaceGroupMembershipDetails = (
+ projectId: string,
+ groupId: string,
+ projectType?: string
+) => {
return useQuery({
enabled: Boolean(projectId && groupId),
queryKey: projectKeys.getProjectGroupMembershipDetails(projectId, groupId),
@@ -456,21 +472,21 @@ export const useGetWorkspaceGroupMembershipDetails = (projectId: string, groupId
const {
data: { groupMembership }
} = await apiRequest.get<{ groupMembership: TGroupMembership }>(
- `/api/v1/projects/${projectId}/memberships/groups/${groupId}`
+ `${groupMembershipsBase(projectType, projectId)}/${groupId}`
);
return groupMembership;
}
});
};
-export const useListWorkspaceGroups = (projectId: string) => {
+export const useListWorkspaceGroups = (projectId: string, projectType?: string) => {
return useQuery({
queryKey: projectKeys.getProjectGroupMemberships(projectId),
queryFn: async () => {
const {
data: { groupMemberships }
} = await apiRequest.get<{ groupMemberships: TGroupMembership[] }>(
- `/api/v1/projects/${projectId}/memberships/groups`
+ groupMembershipsBase(projectType, projectId)
);
return groupMemberships;
},
diff --git a/frontend/src/hooks/api/projects/types.ts b/frontend/src/hooks/api/projects/types.ts
index 03bf67a3a0..6032b1bb53 100644
--- a/frontend/src/hooks/api/projects/types.ts
+++ b/frontend/src/hooks/api/projects/types.ts
@@ -126,6 +126,7 @@ export type DeleteEnvironmentDTO = { projectId: string; id: string };
export type TUpdateWorkspaceUserRoleDTO = {
membershipId: string;
projectId: string;
+ projectType?: string;
roles: (
| {
role: string;
@@ -144,6 +145,7 @@ export type TUpdateWorkspaceUserRoleDTO = {
export type TUpdateWorkspaceGroupRoleDTO = {
groupId: string;
projectId: string;
+ projectType?: string;
roles: (
| {
role: string;
@@ -161,6 +163,7 @@ export type TUpdateWorkspaceGroupRoleDTO = {
export type TListProjectIdentitiesDTO = {
projectId: string;
+ projectType?: string;
offset?: number;
limit?: number;
orderBy?: ProjectIdentityOrderBy;
diff --git a/frontend/src/hooks/api/roles/mutation.tsx b/frontend/src/hooks/api/roles/mutation.tsx
index 484e106607..6c1eff0a0c 100644
--- a/frontend/src/hooks/api/roles/mutation.tsx
+++ b/frontend/src/hooks/api/roles/mutation.tsx
@@ -1,6 +1,7 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
+import { rolesBase } from "@app/hooks/api/certManagerAccess";
import { roleQueryKeys } from "./queries";
import {
@@ -18,10 +19,10 @@ export const useCreateProjectRole = () => {
const queryClient = useQueryClient();
return useMutation<TProjectRole, object, TCreateProjectRoleDTO>({
- mutationFn: async ({ projectId, ...dto }: TCreateProjectRoleDTO) => {
+ mutationFn: async ({ projectId, projectType, ...dto }: TCreateProjectRoleDTO) => {
const {
data: { role }
- } = await apiRequest.post(`/api/v1/projects/${projectId}/roles`, dto);
+ } = await apiRequest.post(rolesBase(projectType, projectId), dto);
return role;
},
onSuccess: (_, { projectId }) => {
@@ -34,10 +35,10 @@ export const useUpdateProjectRole = () => {
const queryClient = useQueryClient();
return useMutation<TProjectRole, object, TUpdateProjectRoleDTO>({
- mutationFn: async ({ id, projectId, ...dto }: TUpdateProjectRoleDTO) => {
+ mutationFn: async ({ id, projectId, projectType, ...dto }: TUpdateProjectRoleDTO) => {
const {
data: { role }
- } = await apiRequest.patch(`/api/v1/projects/${projectId}/roles/${id}`, dto);
+ } = await apiRequest.patch(`${rolesBase(projectType, projectId)}/${id}`, dto);
return role;
},
onSuccess: (_, { projectId, slug }) => {
@@ -54,10 +55,10 @@ export const useUpdateProjectRole = () => {
export const useDeleteProjectRole = () => {
const queryClient = useQueryClient();
return useMutation<TProjectRole, object, TDeleteProjectRoleDTO>({
- mutationFn: async ({ projectId, id }: TDeleteProjectRoleDTO) => {
+ mutationFn: async ({ projectId, projectType, id }: TDeleteProjectRoleDTO) => {
const {
data: { role }
- } = await apiRequest.delete(`/api/v1/projects/${projectId}/roles/${id}`);
+ } = await apiRequest.delete(`${rolesBase(projectType, projectId)}/${id}`);
return role;
},
onSuccess: (_, { projectId }) => {
diff --git a/frontend/src/hooks/api/roles/queries.tsx b/frontend/src/hooks/api/roles/queries.tsx
index 536850cc20..30c54f205c 100644
--- a/frontend/src/hooks/api/roles/queries.tsx
+++ b/frontend/src/hooks/api/roles/queries.tsx
@@ -7,6 +7,7 @@ import picomatch from "picomatch";
import { apiRequest } from "@app/config/request";
import { OrgPermissionSet } from "@app/context/OrgPermissionContext/types";
import { ProjectPermissionSet } from "@app/context/ProjectPermissionContext/types";
+import { rolesBase } from "@app/hooks/api/certManagerAccess";
import { groupBy } from "@app/lib/fn/array";
import { omit } from "@app/lib/fn/object";
@@ -50,26 +51,30 @@ export const roleQueryKeys = {
["user-project-permissions", { projectId }] as const
};
-export const getProjectRoles = async (projectId: string) => {
+export const getProjectRoles = async (projectId: string, projectType?: string) => {
const { data } = await apiRequest.get<{ roles: Array<Omit<TProjectRole, "permissions">> }>(
- `/api/v1/projects/${projectId}/roles`
+ rolesBase(projectType, projectId)
);
return data.roles;
};
-export const useGetProjectRoles = (projectId: string) =>
+export const useGetProjectRoles = (projectId: string, projectType?: string) =>
useQuery({
queryKey: roleQueryKeys.getProjectRoles(projectId),
- queryFn: () => getProjectRoles(projectId),
+ queryFn: () => getProjectRoles(projectId, projectType),
enabled: Boolean(projectId)
});
-export const useGetProjectRoleBySlug = (projectId: string, roleSlug: string) =>
+export const useGetProjectRoleBySlug = (
+ projectId: string,
+ roleSlug: string,
+ projectType?: string
+) =>
useQuery({
queryKey: roleQueryKeys.getProjectRoleBySlug(projectId, roleSlug),
queryFn: async () => {
const { data } = await apiRequest.get<{ role: TProjectRole }>(
- `/api/v1/projects/${projectId}/roles/slug/${roleSlug}`
+ `${rolesBase(projectType, projectId)}/slug/${roleSlug}`
);
return data.role;
},
diff --git a/frontend/src/hooks/api/roles/types.ts b/frontend/src/hooks/api/roles/types.ts
index e94f133059..6f5476b505 100644
--- a/frontend/src/hooks/api/roles/types.ts
+++ b/frontend/src/hooks/api/roles/types.ts
@@ -75,6 +75,7 @@ export type TDeleteOrgRoleDTO = {
export type TCreateProjectRoleDTO = {
projectId: string;
+ projectType?: string;
name: string;
description?: string | null;
slug: string;
@@ -83,10 +84,12 @@ export type TCreateProjectRoleDTO = {
export type TUpdateProjectRoleDTO = {
projectId: string;
+ projectType?: string;
id: string;
} & Partial<Omit<TCreateProjectRoleDTO, "orgId">>;
export type TDeleteProjectRoleDTO = {
projectId: string;
+ projectType?: string;
id: string;
};
diff --git a/frontend/src/hooks/api/users/mutation.tsx b/frontend/src/hooks/api/users/mutation.tsx
index 621a2fc7e4..ddf696cde4 100644
--- a/frontend/src/hooks/api/users/mutation.tsx
+++ b/frontend/src/hooks/api/users/mutation.tsx
@@ -1,6 +1,7 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
+import { userMembershipsBase } from "@app/hooks/api/certManagerAccess";
import { projectKeys } from "../projects";
import { userKeys } from "./query-keys";
@@ -10,8 +11,8 @@ export const useAddUserToWsNonE2EE = () => {
const queryClient = useQueryClient();
return useMutation<object, object, AddUserToWsDTONonE2EE>({
- mutationFn: async ({ projectId, usernames, roleSlugs }) => {
- const { data } = await apiRequest.post(`/api/v1/projects/${projectId}/memberships`, {
+ mutationFn: async ({ projectId, projectType, usernames, roleSlugs }) => {
+ const { data } = await apiRequest.post(userMembershipsBase(projectType, projectId), {
usernames,
roleSlugs
});
diff --git a/frontend/src/hooks/api/users/types.ts b/frontend/src/hooks/api/users/types.ts
index 9bf0516253..edf3cc7cad 100644
--- a/frontend/src/hooks/api/users/types.ts
+++ b/frontend/src/hooks/api/users/types.ts
@@ -152,6 +152,7 @@ export type TWorkspaceUser = {
export type AddUserToWsDTONonE2EE = {
projectId: string;
+ projectType?: string;
usernames: string[];
roleSlugs?: string[];
orgId: string;
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/CertManagerNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/CertManagerNav.tsx
index dcc5aa4d49..6c80ef44ad 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/CertManagerNav.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/CertManagerNav.tsx
@@ -1,36 +1,28 @@
+import { useQuery } from "@tanstack/react-query";
import {
Bell,
- BookCheck,
- FileCheck,
+ Boxes,
FileKey,
FileText,
- Key,
+ GitCompare,
+ Inbox,
LayoutDashboard,
- Monitor,
PenTool,
- Plug,
Search,
Settings,
Shield,
ShieldCheck
} from "lucide-react";
-import { SidebarCollapsibleGroup, SidebarMenu } from "@app/components/v3";
-import { useProject, useSubscription } from "@app/context";
-import {
- useListWorkspaceCertificateTemplates,
- useListWorkspacePkiSubscribers
-} from "@app/hooks/api";
+import { SidebarCollapsibleGroup } from "@app/components/v3";
+import { useProject, useProjectPermission } from "@app/context";
+import { useListWorkspacePkiAlerts } from "@app/hooks/api";
+import { approvalPolicyQuery, ApprovalPolicyType } from "@app/hooks/api/approvalPolicies";
+import { useGetPkiAlertsV2 } from "@app/hooks/api/pkiAlertsV2";
+import { useListPkiSyncs } from "@app/hooks/api/pkiSyncs";
-import { ProjectNavLink, ProjectNavList } from "./ProjectNavLink";
-import {
- CERT_APPROVALS_SUBMENU,
- CERT_CERTIFICATES_SUBMENU,
- CERT_DISCOVERY_SUBMENU,
- CERT_INTEGRATIONS_SUBMENU,
- CERT_SETTINGS_SUBMENU,
- PROJECT_ACCESS_CONTROL_SUBMENU
-} from "./submenus";
+import { ProjectNavList } from "./ProjectNavLink";
+import { CERT_MANAGER_ACCESS_CONTROL_SUBMENU } from "./submenus";
import type { NavItem, Submenu } from "./types";
export const CertManagerNav = ({
@@ -38,59 +30,41 @@ export const CertManagerNav = ({
}: {
onSubmenuOpen: (submenu: Submenu) => void;
}) => {
+ const { hasProjectRole } = useProjectPermission();
const { currentProject } = useProject();
- const { subscription } = useSubscription();
- const { data: subscribers = [] } = useListWorkspacePkiSubscribers(currentProject?.id || "");
- const { data: templatesData } = useListWorkspaceCertificateTemplates({
- projectId: currentProject?.id || ""
+ const isCertManagerAdmin = hasProjectRole("admin");
+ const projectId = currentProject?.id ?? "";
+
+ const { data: v2AlertsData } = useGetPkiAlertsV2(
+ {},
+ { enabled: isCertManagerAdmin && Boolean(projectId) }
+ );
+ const { data: v1AlertsData } = useListWorkspacePkiAlerts({
+ projectId: isCertManagerAdmin ? projectId : ""
+ });
+ const { data: syncs } = useListPkiSyncs(projectId, {
+ enabled: isCertManagerAdmin && Boolean(projectId)
+ });
+ const { data: policies } = useQuery({
+ ...approvalPolicyQuery.list({ projectId, policyType: ApprovalPolicyType.CertRequest }),
+ enabled: isCertManagerAdmin && Boolean(projectId)
});
- const templates = templatesData?.certificateTemplates || [];
- const dashboardItem: NavItem = {
- label: "Dashboard",
- icon: LayoutDashboard,
- pathSuffix: "overview"
- };
+ const hasLegacyAlerts =
+ Boolean(v2AlertsData?.alerts?.some((a) => !a.applicationId)) ||
+ Boolean(v1AlertsData?.alerts?.length);
+ const hasLegacySyncs = Boolean(syncs?.some((s) => !s.applicationId));
+ const hasLegacyPolicies = Boolean(policies?.some((p) => !p.applicationId));
+ const hasAnyLegacy = hasLegacyAlerts || hasLegacySyncs || hasLegacyPolicies;
- const certInfraItems: NavItem[] = [
- {
- label: "Certificate Authorities",
- icon: ShieldCheck,
- pathSuffix: "certificate-authorities",
- activeMatch: /\/ca\//
- },
- {
- label: "Certificates",
- icon: FileKey,
- pathSuffix: "policies",
- submenu: CERT_CERTIFICATES_SUBMENU
- },
- {
- label: "Discovery",
- icon: Search,
- pathSuffix: "discovery",
- activeMatch: /\/discovery/,
- submenu: CERT_DISCOVERY_SUBMENU
- },
- { label: "Alerting", icon: Bell, pathSuffix: "alerting" },
- {
- label: "Approvals",
- icon: BookCheck,
- pathSuffix: "approvals",
- submenu: CERT_APPROVALS_SUBMENU
- },
- {
- label: "Subscribers (Legacy)",
- icon: Monitor,
- pathSuffix: "subscribers",
- hidden: !(subscription.pkiLegacyTemplates || subscribers.length > 0)
- },
- {
- label: "Certificate Templates (Legacy)",
- icon: FileKey,
- pathSuffix: "certificate-templates",
- hidden: !(subscription.pkiLegacyTemplates || templates.length > 0)
- }
+ const overviewItems: NavItem[] = [
+ { label: "Dashboard", icon: LayoutDashboard, pathSuffix: "overview" },
+ { label: "Inventory", icon: FileKey, pathSuffix: "inventory" },
+ { label: "Discovery", icon: Search, pathSuffix: "discovery", activeMatch: /\/discovery/ }
+ ];
+
+ const applicationItems: NavItem[] = [
+ { label: "Applications", icon: Boxes, pathSuffix: "applications" }
];
const codeSigningItems: NavItem[] = [
@@ -98,69 +72,75 @@ export const CertManagerNav = ({
label: "Signers",
icon: PenTool,
pathSuffix: "code-signing",
- activeMatch: /\/code-signing/,
- search: { selectedTab: "signers" },
- isDefaultSearch: true
- },
- {
- label: "Signing Requests",
- icon: FileCheck,
- pathSuffix: "code-signing",
- activeMatch: /\/code-signing/,
- search: { selectedTab: "signing-requests" }
- },
+ activeMatch: /\/code-signing/
+ }
+ ];
+
+ const workflowItems: NavItem[] = [{ label: "Requests", icon: Inbox, pathSuffix: "requests" }];
+
+ const complianceItems: NavItem[] = [
+ { label: "Audit Logs", icon: FileText, pathSuffix: "audit-logs" }
+ ];
+
+ const legacyItems: NavItem[] = [
+ { label: "Alerts", icon: Bell, pathSuffix: "alerting", hidden: !hasLegacyAlerts },
{
- label: "Signing Policies",
- icon: Shield,
- pathSuffix: "code-signing",
- activeMatch: /\/code-signing/,
- search: { selectedTab: "signing-policies" }
+ label: "Approval Policies",
+ icon: ShieldCheck,
+ pathSuffix: "approvals",
+ search: { legacy: "true", selectedTab: "policies" },
+ hidden: !hasLegacyPolicies
},
{
- label: "Grants",
- icon: Key,
- pathSuffix: "code-signing",
- activeMatch: /\/code-signing/,
- search: { selectedTab: "grants" }
+ label: "Certificate Syncs",
+ icon: GitCompare,
+ pathSuffix: "integrations",
+ search: { legacy: "true", selectedTab: "pki-syncs" },
+ hidden: !hasLegacySyncs
}
];
- const generalItems: NavItem[] = [
+ const configurationItems: NavItem[] = [
{
- label: "Integrations",
- icon: Plug,
- pathSuffix: "integrations",
- submenu: CERT_INTEGRATIONS_SUBMENU
- },
- {
- label: "Access Control",
+ label: "Access",
icon: Shield,
pathSuffix: "access-management",
activeMatch: /\/groups\/|\/identities\/|\/members\/|\/roles\//,
- submenu: PROJECT_ACCESS_CONTROL_SUBMENU
+ submenu: CERT_MANAGER_ACCESS_CONTROL_SUBMENU
},
- { label: "Audit Logs", icon: FileText, pathSuffix: "audit-logs" },
{
label: "Settings",
icon: Settings,
- pathSuffix: "settings",
- submenu: CERT_SETTINGS_SUBMENU
+ pathSuffix: "settings"
}
];
return (
<>
- <SidebarMenu>
- <ProjectNavLink item={dashboardItem} />
- </SidebarMenu>
- <SidebarCollapsibleGroup label="Certificate Infrastructure">
- <ProjectNavList items={certInfraItems} onSubmenuOpen={onSubmenuOpen} />
+ {isCertManagerAdmin ? (
+ <SidebarCollapsibleGroup label="General">
+ <ProjectNavList items={overviewItems} onSubmenuOpen={onSubmenuOpen} />
+ </SidebarCollapsibleGroup>
+ ) : null}
+ <SidebarCollapsibleGroup label="Applications">
+ <ProjectNavList items={applicationItems} onSubmenuOpen={onSubmenuOpen} />
</SidebarCollapsibleGroup>
<SidebarCollapsibleGroup label="Code Signing">
<ProjectNavList items={codeSigningItems} onSubmenuOpen={onSubmenuOpen} />
</SidebarCollapsibleGroup>
- <SidebarCollapsibleGroup label="General">
- <ProjectNavList items={generalItems} onSubmenuOpen={onSubmenuOpen} />
+ <SidebarCollapsibleGroup label="Workflows">
+ <ProjectNavList items={workflowItems} onSubmenuOpen={onSubmenuOpen} />
+ </SidebarCollapsibleGroup>
+ <SidebarCollapsibleGroup label="Compliance">
+ <ProjectNavList items={complianceItems} onSubmenuOpen={onSubmenuOpen} />
+ </SidebarCollapsibleGroup>
+ {isCertManagerAdmin && hasAnyLegacy ? (
+ <SidebarCollapsibleGroup label="Legacy">
+ <ProjectNavList items={legacyItems} onSubmenuOpen={onSubmenuOpen} />
+ </SidebarCollapsibleGroup>
+ ) : null}
+ <SidebarCollapsibleGroup label="Configuration">
+ <ProjectNavList items={configurationItems} onSubmenuOpen={onSubmenuOpen} />
</SidebarCollapsibleGroup>
</>
);
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/OrgNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/OrgNav.tsx
index 2dfd4567c0..c32db77ab4 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/OrgNav.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/OrgNav.tsx
@@ -22,6 +22,7 @@ import {
SubOrgIcon
} from "@app/components/v3";
import { useOrganization, useSubscription } from "@app/context";
+import { useCertManagerInstanceState } from "@app/hooks/api/certManagerInstance";
import {
getOrgSettingsSubmenu,
@@ -37,8 +38,10 @@ import type { OrgNavItem, Submenu } from "./types";
const OrgNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submenu) => void }) => {
const { currentOrg, isRootOrganization, isSubOrganization } = useOrganization();
const { subscription } = useSubscription();
+ const { data: certManagerInstance } = useCertManagerInstanceState();
const { pathname } = useLocation();
const orgId = currentOrg.id;
+ const hasMultipleCertManagerInstances = (certManagerInstance?.projects.length ?? 0) >= 2;
const items: OrgNavItem[] = [
{
@@ -99,7 +102,8 @@ const OrgNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submenu) => void }
isActive: pathname.startsWith(`/organizations/${orgId}/settings`),
submenu: getOrgSettingsSubmenu({
isSubOrganization,
- hasSubOrganization: Boolean(subscription?.subOrganization)
+ hasSubOrganization: Boolean(subscription?.subOrganization),
+ hasMultipleCertManagerInstances
})
}
];
@@ -147,9 +151,11 @@ const OrgNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: Submenu) => void }
export const OrgNavWrapper = () => {
const { currentOrg, isSubOrganization } = useOrganization();
const { subscription } = useSubscription();
+ const { data: certManagerInstance } = useCertManagerInstanceState();
const { pathname } = useLocation();
const navigate = useNavigate();
const orgId = currentOrg.id;
+ const hasMultipleCertManagerInstances = (certManagerInstance?.projects.length ?? 0) >= 2;
const isOnAccessControl =
pathname.startsWith(`/organizations/${orgId}/access-management`) ||
@@ -163,7 +169,8 @@ export const OrgNavWrapper = () => {
if (isOnSettings)
return getOrgSettingsSubmenu({
isSubOrganization,
- hasSubOrganization: Boolean(subscription?.subOrganization)
+ hasSubOrganization: Boolean(subscription?.subOrganization),
+ hasMultipleCertManagerInstances
});
if (isOnSecretSharing) return getSecretSharingSubmenu({ isSubOrganization });
if (isOnNetworking) return NETWORKING_SUBMENU;
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNav.tsx
index 7203d2a48f..5b2008006b 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNav.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNav.tsx
@@ -19,7 +19,6 @@ import {
CERT_CERTIFICATES_SUBMENU,
CERT_DISCOVERY_SUBMENU,
CERT_INTEGRATIONS_SUBMENU,
- CERT_SETTINGS_SUBMENU,
INTEGRATIONS_SUBMENU,
MCP_SUBMENU,
PAM_APPROVALS_SUBMENU,
@@ -52,8 +51,12 @@ const PROJECT_NAV_COMPONENT: Record<
export const ProjectNav = () => {
const { currentProject } = useProject();
const { currentOrg, isSubOrganization } = useOrganization();
- const { pathname } = useLocation();
+ const { pathname, search: locationSearch } = useLocation();
const navigate = useNavigate();
+ const isLegacyView = (locationSearch as { legacy?: string })?.legacy === "true";
+ const hasApplicationContext = Boolean(
+ (locationSearch as { applicationName?: string })?.applicationName
+ );
const { submenu: smApprovalsSubmenu, pendingRequestsCount: smPendingCount } =
useApprovalSubmenu();
const projectLabel = isSubOrganization ? "Sub-Organization" : "Organization";
@@ -75,6 +78,7 @@ export const ProjectNav = () => {
const isOnCertApprovals = isCertManager && pathname.includes("/approvals");
const getInitialProjectSubmenu = (): Submenu | null => {
+ if (isLegacyView || hasApplicationContext) return null;
if (isOnAccessControl)
return currentProject.type === ProjectType.SecretManager
? SECRET_MANAGER_ACCESS_CONTROL_SUBMENU
@@ -84,7 +88,6 @@ export const ProjectNav = () => {
if (isOnIntegrations && isCertManager) return CERT_INTEGRATIONS_SUBMENU;
if (isOnProjectSettings && currentProject.type === ProjectType.SecretManager)
return SM_SETTINGS_SUBMENU;
- if (isOnProjectSettings && isCertManager) return CERT_SETTINGS_SUBMENU;
if (isOnProjectSettings && currentProject.type === ProjectType.SecretScanning)
return SECRET_SCANNING_SETTINGS_SUBMENU;
if (isOnProjectSettings && currentProject.type === ProjectType.PAM) return PAM_SETTINGS_SUBMENU;
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/submenus.ts b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/submenus.ts
index b814da5e15..9db38df91a 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/submenus.ts
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/submenus.ts
@@ -27,7 +27,6 @@ import {
Shield,
ShieldCheck,
ShieldUser,
- Trash2,
User,
Users,
Video
@@ -83,6 +82,24 @@ export const SECRET_MANAGER_ACCESS_CONTROL_SUBMENU: Submenu = {
]
};
+export const CERT_MANAGER_ACCESS_CONTROL_SUBMENU: Submenu = {
+ title: "Access Control",
+ pathSuffix: "access-management",
+ defaultTab: "members",
+ activeMatch: /\/members\/|\/groups\/|\/identities\/|\/roles\//,
+ items: [
+ { label: "Users", icon: User, tab: "members", activeMatch: /\/members\// },
+ { label: "Groups", icon: Users, tab: "groups", activeMatch: /\/groups\// },
+ {
+ label: "Machine Identities",
+ icon: HardDrive,
+ tab: "identities",
+ activeMatch: /\/identities\//
+ },
+ { label: "Roles", icon: IdCardLanyard, tab: "roles", activeMatch: /\/roles\// }
+ ]
+};
+
export const SM_SETTINGS_SUBMENU: Submenu = {
title: "Settings",
pathSuffix: "settings",
@@ -112,10 +129,12 @@ export const INTEGRATIONS_SUBMENU: Submenu = {
export const getOrgSettingsSubmenu = ({
isSubOrganization,
- hasSubOrganization
+ hasSubOrganization,
+ hasMultipleCertManagerInstances
}: {
isSubOrganization: boolean;
hasSubOrganization: boolean;
+ hasMultipleCertManagerInstances: boolean;
}): Submenu => ({
title: "Settings",
pathSuffix: "settings",
@@ -135,6 +154,9 @@ export const getOrgSettingsSubmenu = ({
{ label: "External Migrations", icon: Database, tab: "tab-external-migrations" },
{ label: "Project Templates", icon: FolderCog, tab: "project-templates" },
{ label: "Product Enforcements", icon: ClipboardList, tab: "product-enforcements" },
+ ...(hasMultipleCertManagerInstances
+ ? [{ label: "Certificate Manager", icon: ShieldCheck, tab: "cert-manager" }]
+ : []),
...(!isSubOrganization && hasSubOrganization
? [{ label: "Sub Organizations", icon: SubOrgIcon, tab: "tab-sub-organizations" }]
: [])
@@ -200,16 +222,6 @@ export const CERT_APPROVALS_SUBMENU: Submenu = {
]
};
-export const CERT_SETTINGS_SUBMENU: Submenu = {
- title: "Settings",
- pathSuffix: "settings",
- defaultTab: "general",
- items: [
- { label: "General", icon: Cog, tab: "general" },
- { label: "Certificate Cleanup", icon: Trash2, tab: "certificate-cleanup" }
- ]
-};
-
export const CERT_INTEGRATIONS_SUBMENU: Submenu = {
title: "Integrations",
pathSuffix: "integrations",
diff --git a/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx b/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx
index 50a89587f4..1a4338a59d 100644
--- a/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx
+++ b/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx
@@ -1,15 +1,19 @@
-import { Outlet } from "@tanstack/react-router";
+import { Outlet, useRouterState } from "@tanstack/react-router";
import { useProjectPermission } from "@app/context";
import { AssumePrivilegeModeBanner } from "../ProjectLayout/components/AssumePrivilegeModeBanner";
+import { CertManagerInstanceBanner } from "./components/CertManagerInstanceBanner";
export const PkiManagerLayout = () => {
const { assumedPrivilegeDetails } = useProjectPermission();
+ const pathname = useRouterState({ select: (s) => s.location.pathname });
+ const isDashboard = /\/cert-manager\/[^/]+\/overview\/?$/.test(pathname);
return (
<div className="flex h-full w-full flex-col overflow-x-hidden">
{assumedPrivilegeDetails && <AssumePrivilegeModeBanner />}
+ {isDashboard && <CertManagerInstanceBanner />}
<div className="flex-1 overflow-x-hidden overflow-y-auto bg-bunker-800 px-12 pt-10 pb-4">
<Outlet />
</div>
diff --git a/frontend/src/layouts/PkiManagerLayout/components/ActiveInstanceModal.tsx b/frontend/src/layouts/PkiManagerLayout/components/ActiveInstanceModal.tsx
new file mode 100644
index 0000000000..20a3181d65
--- /dev/null
+++ b/frontend/src/layouts/PkiManagerLayout/components/ActiveInstanceModal.tsx
@@ -0,0 +1,136 @@
+import { useState } from "react";
+
+import { createNotification } from "@app/components/notifications";
+import { Spinner } from "@app/components/v2";
+import {
+ Badge,
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import {
+ useCertManagerLegacyInstances,
+ useSetCertManagerActiveProject
+} from "@app/hooks/api/certManagerInstance";
+import { UsePopUpState } from "@app/hooks/usePopUp";
+
+type Props = {
+ popUp: UsePopUpState<["activeInstance"]>;
+ handlePopUpToggle: (popUpName: keyof UsePopUpState<["activeInstance"]>, state?: boolean) => void;
+};
+
+export const ActiveInstanceModal = ({ popUp, handlePopUpToggle }: Props) => {
+ const { data, isPending } = useCertManagerLegacyInstances();
+ const setActive = useSetCertManagerActiveProject();
+ const [pendingId, setPendingId] = useState<string | null>(null);
+
+ const onPick = async (projectId: string, name: string) => {
+ setPendingId(projectId);
+ try {
+ await setActive.mutateAsync(projectId);
+ createNotification({
+ type: "success",
+ text: `${name} is now the active Cert Manager instance`
+ });
+ handlePopUpToggle("activeInstance", false);
+ } catch (err) {
+ const detail = err instanceof Error ? err.message : "Failed to switch active instance.";
+ createNotification({ type: "error", text: detail });
+ } finally {
+ setPendingId(null);
+ }
+ };
+
+ const renderInstances = () => {
+ if (isPending || !data) {
+ return (
+ <div className="flex items-center justify-center p-8">
+ <Spinner />
+ </div>
+ );
+ }
+ if (data.instances.length === 0) {
+ return (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>No Cert Manager instances</EmptyTitle>
+ <EmptyDescription>
+ Create a Cert Manager project from the organization to get started.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+ }
+ return (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ <TableHead className="text-right">Certificates</TableHead>
+ <TableHead className="text-right">Syncs</TableHead>
+ <TableHead className="text-right">Alerts</TableHead>
+ <TableHead className="text-right">Action</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {data.instances.map((i) => (
+ <TableRow key={i.id}>
+ <TableCell isTruncatable>
+ <div className="font-medium text-foreground">{i.name}</div>
+ <div className="font-mono text-xs text-accent">{i.slug}</div>
+ </TableCell>
+ <TableCell className="text-right">{i.certificateCount}</TableCell>
+ <TableCell className="text-right">{i.syncCount}</TableCell>
+ <TableCell className="text-right">{i.alertCount}</TableCell>
+ <TableCell className="text-right">
+ {i.isActive ? (
+ <Badge variant="success">Active</Badge>
+ ) : (
+ <Button
+ size="xs"
+ variant="outline"
+ isPending={pendingId === i.id}
+ onClick={() => onPick(i.id, i.name)}
+ >
+ Set as active
+ </Button>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ );
+ };
+
+ return (
+ <Dialog
+ open={popUp?.activeInstance?.isOpen}
+ onOpenChange={(o) => handlePopUpToggle("activeInstance", o)}
+ >
+ <DialogContent className="max-w-3xl">
+ <DialogHeader>
+ <DialogTitle>Manage Cert Manager instances</DialogTitle>
+ <DialogDescription>
+ Switch the active Cert Manager instance for this organization. New API requests without
+ a projectId resolve to the active instance.
+ </DialogDescription>
+ </DialogHeader>
+ {renderInstances()}
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/layouts/PkiManagerLayout/components/CertManagerInstanceBanner.tsx b/frontend/src/layouts/PkiManagerLayout/components/CertManagerInstanceBanner.tsx
new file mode 100644
index 0000000000..07b1dc5b78
--- /dev/null
+++ b/frontend/src/layouts/PkiManagerLayout/components/CertManagerInstanceBanner.tsx
@@ -0,0 +1,65 @@
+import { useParams } from "@tanstack/react-router";
+import { InfoIcon } from "lucide-react";
+
+import { Button } from "@app/components/v3";
+import { useOrgPermission } from "@app/context";
+import {
+ OrgPermissionCertManagerActions,
+ OrgPermissionSubjects
+} from "@app/context/OrgPermissionContext/types";
+import { useCertManagerInstanceState } from "@app/hooks/api/certManagerInstance";
+import { usePopUp } from "@app/hooks/usePopUp";
+
+import { ActiveInstanceModal } from "./ActiveInstanceModal";
+
+export const CertManagerInstanceBanner = () => {
+ const { projectId } = useParams({ strict: false });
+ const { data, isPending } = useCertManagerInstanceState();
+ const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["activeInstance"] as const);
+ const { permission } = useOrgPermission();
+ const canManage = permission.can(
+ OrgPermissionCertManagerActions.ManageInstance,
+ OrgPermissionSubjects.CertManager
+ );
+
+ if (isPending || !data || !data.isMultiInstance) return null;
+
+ const activeProject = data.projects.find((p) => p.id === data.activeProjectId);
+ const otherCount = Math.max(0, data.projects.length - 1);
+ const isViewingActive = activeProject?.id === projectId;
+
+ return (
+ <>
+ <div className="flex items-start gap-3 border-b border-mineshaft-600 bg-mineshaft-800 px-12 py-3 text-sm text-mineshaft-200">
+ <InfoIcon size={16} className="mt-0.5 text-warning" />
+ <div className="flex-1">
+ {isViewingActive ? (
+ <>
+ You&apos;re viewing the active instance
+ {activeProject ? (
+ <span className="text-mineshaft-100"> — {activeProject.name}</span>
+ ) : null}
+ . Your org has <span className="text-mineshaft-100">{otherCount} other</span> Cert
+ Manager
+ {otherCount === 1 ? " instance" : " instances"} from the legacy multi-project model.
+ </>
+ ) : (
+ <>
+ This is a legacy Cert Manager instance. The active instance is{" "}
+ <span className="text-mineshaft-100">{activeProject?.name ?? "not set"}</span>; new
+ API requests without a <code>projectId</code> resolve there.
+ </>
+ )}
+ <span className="ml-1">We&apos;re moving Cert Manager to a single-instance model.</span>
+ </div>
+ {canManage && (
+ <Button size="xs" variant="outline" onClick={() => handlePopUpOpen("activeInstance")}>
+ Manage instances
+ </Button>
+ )}
+ </div>
+
+ <ActiveInstanceModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
+ </>
+ );
+};
diff --git a/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx b/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx
index 29e0ef59c5..a122f2195d 100644
--- a/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx
+++ b/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx
@@ -108,6 +108,15 @@ const ProjectSelectInner = () => {
window.location.assign(urlInstance);
};
+ if (currentWorkspace.type === ProjectType.CertificateManager) {
+ return (
+ <div className="mr-2 flex min-w-16 items-center gap-2 pr-1 pl-1 text-sm text-white">
+ <ProjectIcon className="size-[14px] shrink-0 text-project" />
+ <span className="truncate">Certificate Manager</span>
+ </div>
+ );
+ }
+
return (
<div className="mr-2 flex min-w-16 items-center gap-1 pr-1 pl-1">
<Popover open={open} onOpenChange={setOpen}>
diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertModal.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertModal.tsx
index af5bcb7aed..cf1a74f791 100644
--- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertModal.tsx
+++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertModal.tsx
@@ -128,7 +128,6 @@ export const PkiAlertModal = ({ popUp, handlePopUpToggle }: Props) => {
alertId: alert.id,
pkiCollectionId,
name,
- projectId,
alertBeforeDays,
emails: emailArray
});
@@ -136,7 +135,6 @@ export const PkiAlertModal = ({ popUp, handlePopUpToggle }: Props) => {
// create
await createPkiAlert({
name,
- projectId,
pkiCollectionId,
alertBeforeDays,
emails: emailArray
diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsSection.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsSection.tsx
index 1529dfc199..bb862c923f 100644
--- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsSection.tsx
+++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsSection.tsx
@@ -1,10 +1,6 @@
-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, useProject } from "@app/context";
+import { DeleteActionModal } from "@app/components/v2";
+import { useProject } from "@app/context";
import { useDeletePkiAlert } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -25,8 +21,7 @@ export const PkiAlertsSection = () => {
if (!projectId) return;
await deletePkiAlert({
- alertId,
- projectId
+ alertId
});
createNotification({
@@ -39,24 +34,16 @@ export const PkiAlertsSection = () => {
return (
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <div className="mb-4 flex justify-between">
- <p className="text-xl font-medium text-mineshaft-100">Alerts</p>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={ProjectPermissionSub.PkiAlerts}
- >
- {(isAllowed) => (
- <Button
- colorSchema="primary"
- type="submit"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={() => handlePopUpOpen("pkiAlert")}
- isDisabled={!isAllowed}
- >
- Create
- </Button>
- )}
- </ProjectPermissionCan>
+ <div className="mb-4 flex items-center justify-between">
+ <div className="flex items-center gap-x-2">
+ <p className="text-xl font-medium text-mineshaft-100">Alerts</p>
+ <span className="rounded bg-mineshaft-600 px-2 py-0.5 text-xs tracking-wide text-mineshaft-200 uppercase">
+ Legacy
+ </span>
+ </div>
+ <p className="text-xs text-bunker-300">
+ Create new alerts inside a Cert Manager Application.
+ </p>
</div>
<PkiAlertsTable handlePopUpOpen={handlePopUpOpen} />
<PkiAlertModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionModal.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionModal.tsx
index e996f191c1..80eff15b27 100644
--- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionModal.tsx
+++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionModal.tsx
@@ -70,15 +70,13 @@ export const PkiCollectionModal = ({ popUp, handlePopUpToggle }: Props) => {
await updatePkiCollection({
collectionId: pkiCollection.id,
name,
- description,
- projectId
+ description
});
} else {
// create
const { id: collectionId } = await createPkiCollection({
name,
- description,
- projectId
+ description
});
navigate({
diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionSection.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionSection.tsx
index fa9cf7bea3..c61a6444d1 100644
--- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionSection.tsx
+++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionSection.tsx
@@ -25,8 +25,7 @@ export const PkiCollectionSection = () => {
if (!projectId) return;
await deletePkiCollection({
- collectionId,
- projectId
+ collectionId
});
createNotification({
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/ApplicationDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/ApplicationDetailsByIDPage.tsx
new file mode 100644
index 0000000000..a38655098f
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/ApplicationDetailsByIDPage.tsx
@@ -0,0 +1,129 @@
+import { Helmet } from "react-helmet";
+import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
+
+import { PageHeader, Spinner, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
+import {
+ useGetPkiApplicationBySlug,
+ useListPkiApplicationMembers,
+ useListPkiApplicationProfiles
+} from "@app/hooks/api/pkiApplications";
+import { ProjectType } from "@app/hooks/api/projects/types";
+
+import { ApplicationCertificatesTab } from "./components/ApplicationCertificatesTab";
+import { ApplicationMembersTab } from "./components/ApplicationMembersTab";
+import { ApplicationOverviewTab } from "./components/ApplicationOverviewTab";
+import { ApplicationRequestsTab } from "./components/ApplicationRequestsTab";
+import { ApplicationSettingsTab } from "./components/ApplicationSettingsTab";
+import { ApplicationSyncsTab } from "./components/ApplicationSyncsTab";
+
+export const ApplicationDetailsByIDPage = () => {
+ const params = useParams({ strict: false }) as {
+ applicationName?: string;
+ projectId?: string;
+ orgId?: string;
+ };
+ const { applicationName, projectId, orgId } = params;
+ const search = useSearch({ strict: false }) as { selectedTab?: string };
+ const navigate = useNavigate();
+
+ const { data: application, isPending } = useGetPkiApplicationBySlug(applicationName ?? "");
+ const { data: profiles = [] } = useListPkiApplicationProfiles(application?.id ?? "");
+ const { data: members = [] } = useListPkiApplicationMembers(application?.id ?? "");
+
+ const selectedTab = search.selectedTab ?? "overview";
+
+ if (isPending) {
+ return (
+ <div className="flex items-center justify-center p-12 text-muted">
+ <Spinner />
+ </div>
+ );
+ }
+
+ if (!application) {
+ return <div className="p-12 text-muted">Application not found.</div>;
+ }
+
+ return (
+ <>
+ <Helmet>
+ <title>{application.name}</title>
+ </Helmet>
+ <div className="h-full bg-bunker-800">
+ <div className="mx-auto flex flex-col text-white">
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <PageHeader
+ scope={ProjectType.CertificateManager}
+ title={application.name}
+ description={application.description ?? undefined}
+ />
+
+ <Tabs
+ value={selectedTab}
+ onValueChange={(v) =>
+ navigate({
+ to: `/organizations/${orgId ?? ""}/projects/cert-manager/${projectId ?? ""}/applications/${application.slug}`,
+ search: { selectedTab: v } as never
+ } as never)
+ }
+ >
+ <TabList>
+ <Tab variant="project" value="overview">
+ Overview
+ </Tab>
+ <Tab variant="project" value="certificates">
+ Certificates
+ </Tab>
+ <Tab variant="project" value="requests">
+ Requests
+ </Tab>
+ <Tab variant="project" value="syncs">
+ Certificate Syncs
+ </Tab>
+ <Tab variant="project" value="members">
+ Members
+ </Tab>
+ <Tab variant="project" value="settings">
+ Settings
+ </Tab>
+ </TabList>
+ <TabPanel value="overview">
+ <ApplicationOverviewTab
+ application={application}
+ members={members}
+ projectId={projectId ?? ""}
+ />
+ </TabPanel>
+ <TabPanel value="certificates">
+ <ApplicationCertificatesTab
+ applicationId={application.id}
+ projectId={projectId ?? ""}
+ />
+ </TabPanel>
+ <TabPanel value="requests">
+ <ApplicationRequestsTab profiles={profiles} />
+ </TabPanel>
+ <TabPanel value="syncs">
+ <ApplicationSyncsTab
+ applicationId={application.id}
+ applicationName={application.slug}
+ projectId={projectId ?? ""}
+ />
+ </TabPanel>
+ <TabPanel value="members">
+ <ApplicationMembersTab
+ members={members}
+ applicationId={application.id}
+ projectId={projectId ?? ""}
+ />
+ </TabPanel>
+ <TabPanel value="settings">
+ <ApplicationSettingsTab application={application} profiles={profiles} />
+ </TabPanel>
+ </Tabs>
+ </div>
+ </div>
+ </div>
+ </>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx
new file mode 100644
index 0000000000..dd5ac037d2
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx
@@ -0,0 +1,297 @@
+import { useMemo, useState } from "react";
+import { HardDriveIcon, SearchIcon, UserIcon, UsersIcon } from "lucide-react";
+import { twMerge } from "tailwind-merge";
+
+import { createNotification } from "@app/components/notifications";
+import { Spinner } from "@app/components/v2";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import {
+ useGetWorkspaceUsers,
+ useListProjectIdentityMemberships,
+ useListWorkspaceGroups
+} from "@app/hooks/api";
+import { TPkiApplicationMember, useAddPkiApplicationMember } from "@app/hooks/api/pkiApplications";
+
+type ActorType = "user" | "identity" | "group";
+
+type Props = {
+ applicationId: string;
+ projectId: string;
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+ existingMembers: TPkiApplicationMember[];
+};
+
+const PLACEHOLDER: Record<ActorType, string> = {
+ user: "Search users by name or email…",
+ identity: "Search identities by name…",
+ group: "Search groups by name…"
+};
+
+export const AddApplicationMemberModal = ({
+ applicationId,
+ projectId,
+ isOpen,
+ onOpenChange,
+ existingMembers
+}: Props) => {
+ const [type, setType] = useState<ActorType>("user");
+ const [search, setSearch] = useState("");
+ const [selectedActorId, setSelectedActorId] = useState<string | null>(null);
+ const [role, setRole] = useState("operator");
+ const addMember = useAddPkiApplicationMember();
+
+ const usersQuery = useGetWorkspaceUsers(projectId);
+ const identitiesQuery = useListProjectIdentityMemberships({ projectId, limit: 100 });
+ const groupsQuery = useListWorkspaceGroups(projectId);
+
+ const taken = useMemo(() => {
+ const set = new Set<string>();
+ existingMembers.forEach((m) => {
+ if (m.actorUserId) set.add(`user:${m.actorUserId}`);
+ if (m.actorIdentityId) set.add(`identity:${m.actorIdentityId}`);
+ if (m.actorGroupId) set.add(`group:${m.actorGroupId}`);
+ });
+ return set;
+ }, [existingMembers]);
+
+ const items: { id: string; primary: string; secondary?: string }[] = useMemo(() => {
+ const norm = search.trim().toLowerCase();
+
+ if (type === "user") {
+ const users = usersQuery.data ?? [];
+ return users
+ .filter((u) => !taken.has(`user:${u.user.id}`))
+ .map((u) => ({
+ id: u.user.id,
+ primary:
+ [u.user.firstName, u.user.lastName].filter(Boolean).join(" ").trim() ||
+ u.user.username ||
+ u.user.email ||
+ u.user.id,
+ secondary: u.user.email ?? u.user.username ?? undefined
+ }))
+ .filter(
+ (i) =>
+ !norm ||
+ i.primary.toLowerCase().includes(norm) ||
+ (i.secondary?.toLowerCase().includes(norm) ?? false)
+ );
+ }
+
+ if (type === "identity") {
+ const memberships = identitiesQuery.data?.identityMemberships ?? [];
+ return memberships
+ .filter((im) => !taken.has(`identity:${im.identity.id}`))
+ .map((im) => ({
+ id: im.identity.id,
+ primary: im.identity.name,
+ secondary: im.identity.authMethods?.[0] ?? undefined
+ }))
+ .filter((i) => !norm || i.primary.toLowerCase().includes(norm));
+ }
+
+ const groups = groupsQuery.data ?? [];
+ return groups
+ .filter((gm) => !taken.has(`group:${gm.group.id}`))
+ .map((gm) => ({
+ id: gm.group.id,
+ primary: gm.group.name,
+ secondary: gm.group.slug
+ }))
+ .filter(
+ (i) =>
+ !norm ||
+ i.primary.toLowerCase().includes(norm) ||
+ (i.secondary?.toLowerCase().includes(norm) ?? false)
+ );
+ }, [type, search, taken, usersQuery.data, identitiesQuery.data, groupsQuery.data]);
+
+ const isLoadingByType: Record<ActorType, boolean> = {
+ user: usersQuery.isPending,
+ identity: identitiesQuery.isPending,
+ group: groupsQuery.isPending
+ };
+ const isLoading = isLoadingByType[type];
+
+ const reset = () => {
+ setType("user");
+ setSearch("");
+ setSelectedActorId(null);
+ setRole("operator");
+ };
+
+ const handleClose = (open: boolean) => {
+ if (!open) reset();
+ onOpenChange(open);
+ };
+
+ const handleTypeChange = (next: ActorType) => {
+ setType(next);
+ setSelectedActorId(null);
+ setSearch("");
+ };
+
+ const handleSubmit = async () => {
+ if (!selectedActorId) return;
+ try {
+ await addMember.mutateAsync({
+ applicationId,
+ role,
+ userId: type === "user" ? selectedActorId : undefined,
+ identityId: type === "identity" ? selectedActorId : undefined,
+ groupId: type === "group" ? selectedActorId : undefined
+ });
+ createNotification({ type: "success", text: "Member added" });
+ handleClose(false);
+ } catch (err) {
+ const detail = err instanceof Error ? err.message : "Failed to add member.";
+ createNotification({ type: "error", text: detail });
+ }
+ };
+
+ const TYPE_OPTIONS: { value: ActorType; label: string; icon: typeof UserIcon }[] = [
+ { value: "user", label: "Users", icon: UserIcon },
+ { value: "identity", label: "Machine Identities", icon: HardDriveIcon },
+ { value: "group", label: "Groups", icon: UsersIcon }
+ ];
+
+ return (
+ <Dialog open={isOpen} onOpenChange={handleClose}>
+ <DialogContent className="max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Add Member</DialogTitle>
+ <DialogDescription>
+ Grant access to this Application. Only project members are eligible.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-3">
+ <div className="flex gap-1 rounded-md border border-mineshaft-600 bg-mineshaft-800 p-1">
+ {TYPE_OPTIONS.map((opt) => {
+ const Icon = opt.icon;
+ const active = type === opt.value;
+ return (
+ <button
+ key={opt.value}
+ type="button"
+ onClick={() => handleTypeChange(opt.value)}
+ className={twMerge(
+ "flex flex-1 items-center justify-center gap-2 rounded px-3 py-1.5 text-sm transition-colors",
+ active
+ ? "bg-mineshaft-500 text-foreground"
+ : "text-accent hover:bg-mineshaft-600 hover:text-foreground"
+ )}
+ >
+ <Icon size={14} />
+ {opt.label}
+ </button>
+ );
+ })}
+ </div>
+
+ <InputGroup>
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder={PLACEHOLDER[type]}
+ />
+ </InputGroup>
+
+ <div className="max-h-72 overflow-y-auto rounded-md border border-border bg-background">
+ {isLoading && (
+ <div className="flex items-center justify-center p-6">
+ <Spinner />
+ </div>
+ )}
+ {!isLoading && items.length === 0 && (
+ <Empty>
+ <EmptyHeader>
+ <EmptyTitle>Nothing to add</EmptyTitle>
+ <EmptyDescription>
+ Every eligible {type} is already a member of this Application.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ )}
+ {!isLoading && items.length > 0 && (
+ <ul>
+ {items.map((item) => (
+ <li key={item.id}>
+ <button
+ type="button"
+ onClick={() => setSelectedActorId(item.id)}
+ className={`flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-sm transition-colors ${
+ selectedActorId === item.id
+ ? "bg-container-hover text-foreground"
+ : "text-foreground hover:bg-container"
+ }`}
+ >
+ <div className="min-w-0">
+ <div className="truncate">{item.primary}</div>
+ {item.secondary ? (
+ <div className="truncate text-xs text-accent">{item.secondary}</div>
+ ) : null}
+ </div>
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+
+ <div className="flex items-center gap-2">
+ <span className="text-sm text-accent">Role:</span>
+ <Select value={role} onValueChange={setRole}>
+ <SelectTrigger className="w-40">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="admin">Admin</SelectItem>
+ <SelectItem value="operator">Operator</SelectItem>
+ <SelectItem value="auditor">Auditor</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => handleClose(false)}>
+ Cancel
+ </Button>
+ <Button
+ variant="project"
+ isDisabled={!selectedActorId || addMember.isPending}
+ isPending={addMember.isPending}
+ onClick={handleSubmit}
+ >
+ Add Member
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationCertificatesTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationCertificatesTab.tsx
new file mode 100644
index 0000000000..d5146239b6
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationCertificatesTab.tsx
@@ -0,0 +1,121 @@
+import { useQuery } from "@tanstack/react-query";
+
+import { Spinner } from "@app/components/v2";
+import {
+ Badge,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { apiRequest } from "@app/config/request";
+
+type Props = { applicationId: string; projectId: string };
+
+type ApplicationCertificate = {
+ id: string;
+ commonName: string;
+ status: string;
+ notBefore: string;
+ notAfter: string;
+ profileName?: string | null;
+};
+
+type SearchResponse = {
+ certificates: ApplicationCertificate[];
+ totalCount: number;
+};
+
+const statusVariant = (status: string): "success" | "danger" | "warning" | "neutral" => {
+ if (status === "active") return "success";
+ if (status === "revoked") return "danger";
+ if (status === "expired") return "warning";
+ return "neutral";
+};
+
+export const ApplicationCertificatesTab = ({ applicationId, projectId }: Props) => {
+ const { data, isPending } = useQuery({
+ queryKey: ["application-certs", { projectId, applicationId }] as const,
+ queryFn: async () => {
+ const { data: body } = await apiRequest.post<SearchResponse>(
+ `/api/v1/projects/${projectId}/certificates/search`,
+ { offset: 0, limit: 50, applicationId, sortBy: "notAfter", sortOrder: "desc" }
+ );
+ return body;
+ },
+ enabled: Boolean(projectId && applicationId)
+ });
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Certificates</CardTitle>
+ <CardDescription>
+ Active and historical certificates issued through this Application&apos;s profiles.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ {isPending && (
+ <div className="flex items-center justify-center p-8">
+ <Spinner />
+ </div>
+ )}
+ {!isPending && (!data || data.certificates.length === 0) && (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>No certificates yet</EmptyTitle>
+ <EmptyDescription>
+ Certificates issued through this Application will appear here.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ )}
+ {!isPending && data && data.certificates.length > 0 && (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Common Name</TableHead>
+ <TableHead>Profile</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead>Issued</TableHead>
+ <TableHead>Expires</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {data.certificates.map((c) => (
+ <TableRow key={c.id}>
+ <TableCell isTruncatable className="font-mono">
+ {c.commonName}
+ </TableCell>
+ <TableCell className="font-mono text-xs">{c.profileName ?? "—"}</TableCell>
+ <TableCell>
+ <Badge variant={statusVariant(c.status)} className="capitalize">
+ {c.status}
+ </Badge>
+ </TableCell>
+ <TableCell className="text-accent">
+ {new Date(c.notBefore).toLocaleDateString()}
+ </TableCell>
+ <TableCell className="text-accent">
+ {new Date(c.notAfter).toLocaleDateString()}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationMembersTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationMembersTab.tsx
new file mode 100644
index 0000000000..17a25b9b00
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationMembersTab.tsx
@@ -0,0 +1,222 @@
+import { useState } from "react";
+import { MoreHorizontalIcon, Trash2Icon, UserPlusIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { DeleteActionModal } from "@app/components/v2";
+import {
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import {
+ TPkiApplicationMember,
+ useRemovePkiApplicationMember,
+ useUpdatePkiApplicationMemberRole
+} from "@app/hooks/api/pkiApplications";
+import { usePopUp } from "@app/hooks/usePopUp";
+
+import { AddApplicationMemberModal } from "./AddApplicationMemberModal";
+
+type Props = {
+ members: TPkiApplicationMember[];
+ applicationId: string;
+ projectId: string;
+};
+
+type ActorType = "user" | "identity" | "group";
+
+const memberType = (m: TPkiApplicationMember): { label: string; type: ActorType | null } => {
+ if (m.actorUserId) return { label: "User", type: "user" };
+ if (m.actorIdentityId) return { label: "Machine", type: "identity" };
+ if (m.actorGroupId) return { label: "Group", type: "group" };
+ return { label: "—", type: null };
+};
+
+const displayPrimary = (m: TPkiApplicationMember): string => {
+ if (m.details?.name?.trim()) return m.details.name;
+ if (m.details?.username?.trim()) return m.details.username;
+ if (m.details?.email?.trim()) return m.details.email;
+ if (m.details?.slug?.trim()) return m.details.slug;
+ return m.actorUserId ?? m.actorIdentityId ?? m.actorGroupId ?? "—";
+};
+
+const displaySecondary = (m: TPkiApplicationMember): string | null => {
+ if (m.actorUserId) return m.details?.email ?? m.details?.username ?? null;
+ if (m.actorIdentityId) return m.details?.authMethod ?? null;
+ if (m.actorGroupId) return m.details?.slug ?? null;
+ return null;
+};
+
+export const ApplicationMembersTab = ({ members, applicationId, projectId }: Props) => {
+ const updateRole = useUpdatePkiApplicationMemberRole();
+ const removeMember = useRemovePkiApplicationMember();
+ const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([
+ "removeMember"
+ ] as const);
+ const [isAddOpen, setIsAddOpen] = useState(false);
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>Members</CardTitle>
+ <CardDescription>
+ Users, machine identities, and groups granted access to this Application.
+ </CardDescription>
+ <CardAction>
+ <Button size="sm" variant="project" onClick={() => setIsAddOpen(true)}>
+ <UserPlusIcon />
+ Add Member
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ {members.length === 0 ? (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>No members yet</EmptyTitle>
+ <EmptyDescription>
+ Add a user, identity, or group to grant access to this Application.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Member</TableHead>
+ <TableHead>Type</TableHead>
+ <TableHead>Role</TableHead>
+ <TableHead>Added</TableHead>
+ <TableHead className="w-5" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {members.map((m) => {
+ const { label } = memberType(m);
+ const secondary = displaySecondary(m);
+ return (
+ <TableRow key={m.membershipId} className="[&>td]:py-3">
+ <TableCell isTruncatable>
+ <div className="text-foreground">{displayPrimary(m)}</div>
+ {secondary ? <div className="text-xs text-accent">{secondary}</div> : null}
+ </TableCell>
+ <TableCell>
+ <Badge variant="neutral">{label}</Badge>
+ </TableCell>
+ <TableCell>
+ <Select
+ value={m.role}
+ onValueChange={async (role) => {
+ try {
+ await updateRole.mutateAsync({
+ applicationId,
+ membershipId: m.membershipId,
+ role
+ });
+ createNotification({ type: "success", text: "Role updated" });
+ } catch (err) {
+ const detail =
+ err instanceof Error ? err.message : "Failed to update role.";
+ createNotification({ type: "error", text: detail });
+ }
+ }}
+ >
+ <SelectTrigger className="w-32">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="admin">Admin</SelectItem>
+ <SelectItem value="operator">Operator</SelectItem>
+ <SelectItem value="auditor">Auditor</SelectItem>
+ </SelectContent>
+ </Select>
+ </TableCell>
+ <TableCell className="text-accent">
+ {new Date(m.createdAt).toLocaleDateString()}
+ </TableCell>
+ <TableCell>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="xs">
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="min-w-40" align="end" sideOffset={2}>
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() => handlePopUpOpen("removeMember", m)}
+ >
+ <Trash2Icon />
+ Remove Member
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+
+ <AddApplicationMemberModal
+ applicationId={applicationId}
+ projectId={projectId}
+ isOpen={isAddOpen}
+ onOpenChange={setIsAddOpen}
+ existingMembers={members}
+ />
+
+ <DeleteActionModal
+ isOpen={popUp.removeMember.isOpen}
+ title="Remove member?"
+ subTitle="The member loses access to this Application immediately. They keep their other project memberships."
+ onChange={(o) => handlePopUpToggle("removeMember", o)}
+ deleteKey="confirm"
+ onDeleteApproved={async () => {
+ const m = popUp.removeMember.data as TPkiApplicationMember | undefined;
+ if (!m) return;
+ try {
+ await removeMember.mutateAsync({
+ applicationId,
+ membershipId: m.membershipId
+ });
+ createNotification({ type: "success", text: "Member removed" });
+ handlePopUpClose("removeMember");
+ } catch (err) {
+ const detail = err instanceof Error ? err.message : "Failed to remove member.";
+ createNotification({ type: "error", text: detail });
+ }
+ }}
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationOverviewTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationOverviewTab.tsx
new file mode 100644
index 0000000000..3b4ad2b897
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationOverviewTab.tsx
@@ -0,0 +1,155 @@
+import { useQuery } from "@tanstack/react-query";
+import { FileCheckIcon, FileClockIcon, HourglassIcon, UsersIcon } from "lucide-react";
+
+import { Card, CardContent, Skeleton } from "@app/components/v3";
+import { apiRequest } from "@app/config/request";
+import { TPkiApplication, TPkiApplicationMember } from "@app/hooks/api/pkiApplications";
+
+type Props = {
+ application: TPkiApplication;
+ members: TPkiApplicationMember[];
+ projectId: string;
+};
+
+type StatTone = "success" | "warning" | "danger" | "neutral";
+
+type StatCardProps = {
+ label: string;
+ value: number | undefined;
+ isLoading: boolean;
+ hint?: string;
+ icon: React.ComponentType<{ className?: string }>;
+ tone: StatTone;
+};
+
+const TONE_BG: Record<StatTone, string> = {
+ success: "bg-success/10 border-success/20",
+ warning: "bg-warning/10 border-warning/20",
+ danger: "bg-danger/10 border-danger/20",
+ neutral: "bg-neutral/10 border-neutral/20"
+};
+
+const TONE_ICON: Record<StatTone, string> = {
+ success: "text-success",
+ warning: "text-warning",
+ danger: "text-danger",
+ neutral: "text-neutral"
+};
+
+const StatCard = ({ label, value, isLoading, hint, icon: Icon, tone }: StatCardProps) => (
+ <Card className="h-auto min-w-[180px] flex-1 gap-0 p-0">
+ <CardContent className="flex h-full flex-col p-4">
+ <div className="flex items-start justify-between">
+ <span className="text-base font-semibold text-foreground">{label}</span>
+ <div
+ className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border ${TONE_BG[tone]}`}
+ >
+ <Icon className={`h-[18px] w-[18px] ${TONE_ICON[tone]}`} />
+ </div>
+ </div>
+ <div className="mt-auto pt-6">
+ <div className="flex items-baseline gap-2">
+ {isLoading ? (
+ <Skeleton className="h-8 w-12" />
+ ) : (
+ <span className="text-3xl font-semibold text-foreground">{value ?? 0}</span>
+ )}
+ {hint ? <span className="text-xs text-muted">{hint}</span> : null}
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+);
+
+export const ApplicationOverviewTab = ({ application, members, projectId }: Props) => {
+ const { data: activeCerts, isPending: isActivePending } = useQuery({
+ queryKey: [
+ "application-overview-active",
+ { projectId, applicationId: application.id }
+ ] as const,
+ queryFn: async () => {
+ const { data } = await apiRequest.post<{ totalCount: number }>(
+ `/api/v1/projects/${projectId}/certificates/search`,
+ { offset: 0, limit: 1, applicationId: application.id, status: "active" }
+ );
+ return data.totalCount;
+ },
+ enabled: Boolean(projectId && application.id)
+ });
+
+ const expiringCutoff = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();
+ const { data: expiringCount, isPending: isExpiringPending } = useQuery({
+ queryKey: [
+ "application-overview-expiring",
+ { projectId, applicationId: application.id }
+ ] as const,
+ queryFn: async () => {
+ const { data } = await apiRequest.post<{ totalCount: number }>(
+ `/api/v1/projects/${projectId}/certificates/search`,
+ {
+ offset: 0,
+ limit: 1,
+ applicationId: application.id,
+ status: "active",
+ notAfterTo: expiringCutoff
+ }
+ );
+ return data.totalCount;
+ },
+ enabled: Boolean(projectId && application.id)
+ });
+
+ const { data: pendingApprovals, isPending: isPendingApprovalsPending } = useQuery({
+ queryKey: [
+ "application-overview-pending",
+ { projectId, applicationId: application.id }
+ ] as const,
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ requests: Array<{ status: string }> }>(
+ "/api/v1/cert-request-policies/requests",
+ { params: { projectId, applicationId: application.id } }
+ );
+ return data.requests.filter((r) => r.status === "pending").length;
+ },
+ enabled: Boolean(projectId && application.id)
+ });
+
+ return (
+ <div className="space-y-4">
+ <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
+ <StatCard
+ label="Active certificates"
+ value={activeCerts}
+ isLoading={isActivePending}
+ hint="Issued via this Application"
+ icon={FileCheckIcon}
+ tone="success"
+ />
+ <StatCard
+ label="Expiring in 30d"
+ value={expiringCount}
+ isLoading={isExpiringPending}
+ hint="Active, expiring within 30 days"
+ icon={FileClockIcon}
+ tone={expiringCount && expiringCount > 0 ? "warning" : "neutral"}
+ />
+ <StatCard
+ label="Pending approvals"
+ value={pendingApprovals}
+ isLoading={isPendingApprovalsPending}
+ hint="Gated by an Application policy"
+ icon={HourglassIcon}
+ tone={pendingApprovals && pendingApprovals > 0 ? "warning" : "neutral"}
+ />
+ <StatCard
+ label="Members"
+ value={members.length}
+ isLoading={false}
+ hint="Users, identities, and groups"
+ icon={UsersIcon}
+ tone="neutral"
+ />
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationRequestsTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationRequestsTab.tsx
new file mode 100644
index 0000000000..6036dc7bab
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationRequestsTab.tsx
@@ -0,0 +1,238 @@
+import { useMemo, useState } from "react";
+import { SearchIcon } from "lucide-react";
+
+import { Spinner, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
+import {
+ Badge,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { useDebounce } from "@app/hooks";
+import {
+ CertificateRequestStatus,
+ TListCertificateRequestsParams,
+ useListCertificateRequests
+} from "@app/hooks/api/certificates";
+import { TPkiApplicationProfile } from "@app/hooks/api/pkiApplications";
+
+type Props = {
+ profiles: TPkiApplicationProfile[];
+};
+
+type StatusTab = "pending" | "issued" | "rejected" | "all";
+
+type BadgeVariant = "neutral" | "success" | "warning" | "danger" | "info";
+
+const TABS: { key: StatusTab; label: string; statuses: CertificateRequestStatus[] | null }[] = [
+ {
+ key: "pending",
+ label: "Pending",
+ statuses: [
+ CertificateRequestStatus.PENDING_APPROVAL,
+ CertificateRequestStatus.PENDING,
+ CertificateRequestStatus.PENDING_VALIDATION
+ ]
+ },
+ { key: "issued", label: "Issued", statuses: [CertificateRequestStatus.ISSUED] },
+ {
+ key: "rejected",
+ label: "Rejected",
+ statuses: [CertificateRequestStatus.REJECTED, CertificateRequestStatus.FAILED]
+ },
+ { key: "all", label: "All", statuses: null }
+];
+
+const STATUS_BADGE: Record<CertificateRequestStatus, { label: string; variant: BadgeVariant }> = {
+ [CertificateRequestStatus.PENDING_APPROVAL]: {
+ label: "Approval required",
+ variant: "warning"
+ },
+ [CertificateRequestStatus.PENDING]: { label: "Pending", variant: "neutral" },
+ [CertificateRequestStatus.PENDING_VALIDATION]: { label: "Validating", variant: "info" },
+ [CertificateRequestStatus.ISSUED]: { label: "Issued", variant: "success" },
+ [CertificateRequestStatus.FAILED]: { label: "Failed", variant: "danger" },
+ [CertificateRequestStatus.REJECTED]: { label: "Rejected", variant: "danger" }
+};
+
+const formatRelative = (iso: string): string => {
+ const diffMs = Date.now() - new Date(iso).getTime();
+ const minutes = Math.round(diffMs / 60000);
+ if (minutes < 1) return "just now";
+ if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
+ const hours = Math.round(minutes / 60);
+ if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
+ const days = Math.round(hours / 24);
+ return `${days} day${days === 1 ? "" : "s"} ago`;
+};
+
+export const ApplicationRequestsTab = ({ profiles }: Props) => {
+ const [activeTab, setActiveTab] = useState<StatusTab>("pending");
+ const [pendingSearch, setPendingSearch] = useState("");
+ const [debouncedSearch] = useDebounce(pendingSearch, 400);
+
+ const profileIds = useMemo(() => profiles.map((p) => p.profileId), [profiles]);
+
+ const tab = TABS.find((t) => t.key === activeTab) ?? TABS[0];
+
+ const queryParams: TListCertificateRequestsParams = useMemo(
+ () => ({
+ offset: 0,
+ limit: 100,
+ search: debouncedSearch || undefined,
+ profileIds: profileIds.length > 0 ? profileIds : undefined
+ }),
+ [debouncedSearch, profileIds]
+ );
+
+ const { data, isPending } = useListCertificateRequests(queryParams);
+
+ const filtered = useMemo(() => {
+ const all = data?.certificateRequests ?? [];
+ if (!tab.statuses) return all;
+ return all.filter((r) => tab.statuses!.includes(r.status as CertificateRequestStatus));
+ }, [data, tab]);
+
+ const counts = useMemo(() => {
+ const all = data?.certificateRequests ?? [];
+ const result: Record<StatusTab, number> = {
+ pending: 0,
+ issued: 0,
+ rejected: 0,
+ all: all.length
+ };
+ all.forEach((r) => {
+ const s = r.status as CertificateRequestStatus;
+ if (
+ s === CertificateRequestStatus.PENDING_APPROVAL ||
+ s === CertificateRequestStatus.PENDING ||
+ s === CertificateRequestStatus.PENDING_VALIDATION
+ ) {
+ result.pending += 1;
+ } else if (s === CertificateRequestStatus.ISSUED) {
+ result.issued += 1;
+ } else if (s === CertificateRequestStatus.REJECTED || s === CertificateRequestStatus.FAILED) {
+ result.rejected += 1;
+ }
+ });
+ return result;
+ }, [data]);
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Certificate Requests</CardTitle>
+ <CardDescription>
+ Issuance requests for this Application. Requests gated by an approval policy land here for
+ review before issuance.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as StatusTab)}>
+ <TabList>
+ {TABS.map((t) => (
+ <Tab
+ key={t.key}
+ value={t.key}
+ variant="project"
+ data-testid={`requests-tab-${t.key}`}
+ >
+ {t.label} ({counts[t.key]})
+ </Tab>
+ ))}
+ </TabList>
+
+ {TABS.map((t) => (
+ <TabPanel key={t.key} value={t.key}>
+ <div className="mt-4 mb-4">
+ <InputGroup>
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={pendingSearch}
+ onChange={(e) => setPendingSearch(e.target.value)}
+ placeholder="Search by SAN or CN…"
+ data-testid="requests-search"
+ />
+ </InputGroup>
+ </div>
+
+ {isPending && !data && (
+ <div className="flex items-center justify-center p-8">
+ <Spinner />
+ </div>
+ )}
+ {(!isPending || data) && filtered.length === 0 && (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>
+ {activeTab === "pending" ? "No requests pending" : "No requests"}
+ </EmptyTitle>
+ <EmptyDescription>
+ Certificate issuance requests scoped to this Application&apos;s profiles will
+ appear here.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ )}
+ {(!isPending || data) && filtered.length > 0 && (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Common Name / SAN</TableHead>
+ <TableHead>Profile</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead>Requested</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {filtered.map((r) => {
+ const badge =
+ STATUS_BADGE[r.status as CertificateRequestStatus] ??
+ ({ label: r.status, variant: "neutral" } as const);
+ return (
+ <TableRow key={r.id}>
+ <TableCell isTruncatable>
+ <div className="font-mono text-foreground">{r.commonName ?? "—"}</div>
+ {r.altNames ? (
+ <div className="font-mono text-xs text-accent">{r.altNames}</div>
+ ) : null}
+ </TableCell>
+ <TableCell className="font-mono text-xs">
+ {r.profileName ?? "—"}
+ </TableCell>
+ <TableCell>
+ <Badge variant={badge.variant}>{badge.label}</Badge>
+ </TableCell>
+ <TableCell className="text-accent">
+ {formatRelative(r.createdAt)}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ )}
+ </TabPanel>
+ ))}
+ </Tabs>
+ </CardContent>
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx
new file mode 100644
index 0000000000..f552212b30
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx
@@ -0,0 +1,489 @@
+import { useMemo, useState } from "react";
+import { faPlus } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { MoreHorizontalIcon, PlusIcon, SettingsIcon, Trash2Icon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button as V2Button,
+ DeleteActionModal,
+ FilterableSelect,
+ Skeleton as V2Skeleton,
+ Table as V2Table,
+ TableContainer,
+ TBody,
+ Td,
+ Th,
+ THead,
+ Tr
+} from "@app/components/v2";
+import {
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { usePopUp } from "@app/hooks";
+import {
+ ApprovalPolicyType,
+ TApprovalPolicy,
+ useDeleteApprovalPolicy
+} from "@app/hooks/api/approvalPolicies";
+import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";
+import { TPkiAlertV2, useDeletePkiAlertV2, useGetPkiAlertsV2 } from "@app/hooks/api/pkiAlertsV2";
+import {
+ TPkiApplication,
+ TPkiApplicationProfile,
+ useAttachPkiApplicationProfiles,
+ useDetachPkiApplicationProfile
+} from "@app/hooks/api/pkiApplications";
+import { PoliciesTable } from "@app/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PoliciesTable";
+import { PolicyModal } from "@app/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicyModal";
+import { CreatePkiAlertV2Modal } from "@app/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal";
+import { PkiAlertV2Row } from "@app/views/PkiAlertsV2Page/components/PkiAlertV2Row";
+import { ViewPkiAlertV2Modal } from "@app/views/PkiAlertsV2Page/components/ViewPkiAlertV2Modal";
+
+import { ConfigureEnrollmentModal } from "./ConfigureEnrollmentModal";
+
+type Props = { application: TPkiApplication; profiles: TPkiApplicationProfile[] };
+
+const methodBadges = (p: TPkiApplicationProfile) => {
+ const methods: string[] = [];
+ if (p.apiConfigId) methods.push("API");
+ if (p.estConfigId) methods.push("EST");
+ if (p.acmeConfigId) methods.push("ACME");
+ if (p.scepConfigId) methods.push("SCEP");
+ return methods;
+};
+
+export const ApplicationSettingsTab = ({ application, profiles }: Props) => {
+ const [isAttachOpen, setIsAttachOpen] = useState(false);
+ const [profilesToAttach, setProfilesToAttach] = useState<{ value: string; label: string }[]>([]);
+ const [profileToDetach, setProfileToDetach] = useState<TPkiApplicationProfile | null>(null);
+ const [profileToConfigure, setProfileToConfigure] = useState<TPkiApplicationProfile | null>(null);
+
+ const { data: profileList } = useListCertificateProfiles({ limit: 100 });
+ const attachMutation = useAttachPkiApplicationProfiles();
+ const detachMutation = useDetachPkiApplicationProfile();
+
+ const { popUp, handlePopUpToggle, handlePopUpOpen, handlePopUpClose } = usePopUp([
+ "policy",
+ "deletePolicy"
+ ] as const);
+ const deletePolicy = useDeleteApprovalPolicy();
+
+ const { data: alertsData, isLoading: isAlertsLoading } = useGetPkiAlertsV2({
+ applicationId: application.id,
+ limit: 100
+ });
+ const alerts = alertsData?.alerts ?? [];
+ const [alertModal, setAlertModal] = useState<{ isOpen: boolean; alertId?: string }>({
+ isOpen: false
+ });
+ const [viewAlertModal, setViewAlertModal] = useState<{ isOpen: boolean; alertId?: string }>({
+ isOpen: false
+ });
+ const [deleteAlertModal, setDeleteAlertModal] = useState<{
+ isOpen: boolean;
+ alertId?: string;
+ name?: string;
+ }>({ isOpen: false });
+ const { mutateAsync: deleteAlert } = useDeletePkiAlertV2();
+
+ const handleDeleteAlert = async () => {
+ if (!deleteAlertModal.alertId) return;
+ try {
+ await deleteAlert({
+ alertId: deleteAlertModal.alertId,
+ applicationId: application.id
+ });
+ setDeleteAlertModal({ isOpen: false });
+ createNotification({ type: "success", text: "Alert deleted" });
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to delete alert"
+ });
+ }
+ };
+
+ const handleDeletePolicy = async () => {
+ const p = popUp.deletePolicy.data as { policyId: string } | undefined;
+ if (!p?.policyId) return;
+ try {
+ await deletePolicy.mutateAsync({
+ policyType: ApprovalPolicyType.CertRequest,
+ policyId: p.policyId
+ });
+ createNotification({ type: "success", text: "Policy deleted" });
+ handlePopUpClose("deletePolicy");
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to delete policy"
+ });
+ }
+ };
+
+ const attachedIds = useMemo(() => new Set(profiles.map((p) => p.profileId)), [profiles]);
+ const availableProfiles = useMemo(
+ () =>
+ (profileList?.certificateProfiles ?? [])
+ .filter((p) => !attachedIds.has(p.id))
+ .map((p) => ({ value: p.id, label: p.slug })),
+ [profileList, attachedIds]
+ );
+
+ const handleAttach = async () => {
+ if (profilesToAttach.length === 0) return;
+ try {
+ await attachMutation.mutateAsync({
+ applicationId: application.id,
+ profileIds: profilesToAttach.map((p) => p.value)
+ });
+ createNotification({ type: "success", text: "Profile(s) attached" });
+ setProfilesToAttach([]);
+ setIsAttachOpen(false);
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to attach profile(s)"
+ });
+ }
+ };
+
+ const handleDetach = async () => {
+ if (!profileToDetach) return;
+ try {
+ await detachMutation.mutateAsync({
+ applicationId: application.id,
+ profileId: profileToDetach.profileId
+ });
+ createNotification({ type: "success", text: "Profile detached" });
+ setProfileToDetach(null);
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: err instanceof Error ? err.message : "Failed to detach profile"
+ });
+ }
+ };
+
+ return (
+ <div className="space-y-4">
+ <Card>
+ <CardHeader>
+ <CardTitle>General</CardTitle>
+ <CardDescription>Edit core metadata for this Application.</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <dl className="grid grid-cols-1 gap-3 text-sm md:grid-cols-2">
+ <div>
+ <dt className="text-xs text-accent">Name</dt>
+ <dd className="text-foreground">{application.name}</dd>
+ </div>
+ <div>
+ <dt className="text-xs text-accent">Slug</dt>
+ <dd className="font-mono text-foreground">{application.slug}</dd>
+ </div>
+ <div className="col-span-full">
+ <dt className="text-xs text-accent">Description</dt>
+ <dd className="text-foreground">{application.description ?? "—"}</dd>
+ </div>
+ </dl>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Enrollment Methods</CardTitle>
+ <CardDescription>
+ Profiles this Application can issue from, and the methods (API · EST · ACME · SCEP)
+ configured on each.
+ </CardDescription>
+ <CardAction>
+ <Button
+ size="sm"
+ variant="project"
+ onClick={() => setIsAttachOpen(true)}
+ isDisabled={availableProfiles.length === 0}
+ >
+ <PlusIcon />
+ Attach Profile
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ {profiles.length === 0 ? (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>No profiles attached</EmptyTitle>
+ <EmptyDescription>Attach a profile to enable issuance.</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Profile</TableHead>
+ <TableHead>Methods</TableHead>
+ <TableHead className="w-5" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {profiles.map((p) => {
+ const methods = methodBadges(p);
+ return (
+ <TableRow key={p.profileId}>
+ <TableCell isTruncatable className="font-mono">
+ {p.profileSlug}
+ </TableCell>
+ <TableCell>
+ {methods.length === 0 ? (
+ <span className="text-xs text-accent">None</span>
+ ) : (
+ <div className="flex flex-wrap gap-1.5">
+ {methods.map((m) => (
+ <Badge key={m} variant="neutral">
+ {m}
+ </Badge>
+ ))}
+ </div>
+ )}
+ </TableCell>
+ <TableCell>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="xs">
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="min-w-44" align="end" sideOffset={2}>
+ <DropdownMenuItem onClick={() => setProfileToConfigure(p)}>
+ <SettingsIcon />
+ Configure method
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="danger"
+ onClick={() => setProfileToDetach(p)}
+ >
+ <Trash2Icon />
+ Detach Profile
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Approval Policies</CardTitle>
+ <CardDescription>
+ Approval workflows that gate certificate operations against this Application.
+ </CardDescription>
+ <CardAction>
+ <V2Button
+ variant="outline_bg"
+ leftIcon={<FontAwesomeIcon icon={faPlus} />}
+ onClick={() => handlePopUpOpen("policy")}
+ >
+ Create Policy
+ </V2Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ <PoliciesTable handlePopUpOpen={handlePopUpOpen} applicationId={application.id} />
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Alerting</CardTitle>
+ <CardDescription>
+ Alert rules for certificate events scoped to {application.name}.
+ </CardDescription>
+ <CardAction>
+ <V2Button
+ variant="outline_bg"
+ leftIcon={<FontAwesomeIcon icon={faPlus} />}
+ onClick={() => setAlertModal({ isOpen: true })}
+ >
+ Create Alert
+ </V2Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ <TableContainer>
+ <V2Table>
+ <THead>
+ <Tr>
+ <Th>Name</Th>
+ <Th>Event Type</Th>
+ <Th>Status</Th>
+ <Th>Alert Before</Th>
+ <Th>Last Run</Th>
+ <Th className="text-right">Actions</Th>
+ </Tr>
+ </THead>
+ <TBody>
+ {isAlertsLoading &&
+ Array.from({ length: 3 }, (_, idx) => (
+ <Tr key={`alert-skeleton-${idx + 1}`}>
+ {Array.from({ length: 6 }, (__, cellIdx) => (
+ <Td key={`alert-skeleton-cell-${cellIdx + 1}`}>
+ <V2Skeleton className="h-4 w-24" />
+ </Td>
+ ))}
+ </Tr>
+ ))}
+ {!isAlertsLoading && alerts.length === 0 && (
+ <Tr>
+ <Td colSpan={6} className="py-8 text-center text-mineshaft-400">
+ No PKI alerts configured yet.
+ </Td>
+ </Tr>
+ )}
+ {!isAlertsLoading &&
+ alerts.map((a: TPkiAlertV2) => (
+ <PkiAlertV2Row
+ key={a.id}
+ alert={a}
+ onView={() => setViewAlertModal({ isOpen: true, alertId: a.id })}
+ onEdit={() => setAlertModal({ isOpen: true, alertId: a.id })}
+ onDelete={() =>
+ setDeleteAlertModal({ isOpen: true, alertId: a.id, name: a.name })
+ }
+ />
+ ))}
+ </TBody>
+ </V2Table>
+ </TableContainer>
+ </CardContent>
+ </Card>
+
+ <PolicyModal
+ popUp={popUp}
+ handlePopUpToggle={handlePopUpToggle}
+ applicationId={application.id}
+ />
+ <DeleteActionModal
+ isOpen={popUp.deletePolicy.isOpen}
+ deleteKey="delete"
+ title={`Delete approval policy ${(popUp.deletePolicy.data as TApprovalPolicy | undefined)?.name ?? ""}?`}
+ onChange={(isOpen) => handlePopUpToggle("deletePolicy", isOpen)}
+ onDeleteApproved={handleDeletePolicy}
+ />
+ <CreatePkiAlertV2Modal
+ isOpen={alertModal.isOpen}
+ onOpenChange={(isOpen) => setAlertModal({ isOpen, alertId: undefined })}
+ applicationId={application.id}
+ alertId={alertModal.alertId}
+ />
+ <ViewPkiAlertV2Modal
+ isOpen={viewAlertModal.isOpen}
+ onOpenChange={(isOpen) => setViewAlertModal({ isOpen, alertId: undefined })}
+ alertId={viewAlertModal.alertId}
+ />
+ <DeleteActionModal
+ isOpen={deleteAlertModal.isOpen}
+ deleteKey="delete"
+ title={`Delete PKI Alert "${deleteAlertModal.name ?? ""}"`}
+ onChange={(isOpen) => setDeleteAlertModal({ isOpen, alertId: undefined, name: undefined })}
+ onDeleteApproved={handleDeleteAlert}
+ />
+
+ <Dialog
+ open={isAttachOpen}
+ onOpenChange={(open) => {
+ setIsAttachOpen(open);
+ if (!open) setProfilesToAttach([]);
+ }}
+ >
+ <DialogContent className="max-w-md overflow-visible">
+ <DialogHeader>
+ <DialogTitle>Attach Profiles</DialogTitle>
+ <DialogDescription>
+ Select one or more profiles to attach to this Application.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="py-2">
+ <FilterableSelect
+ isMulti
+ value={profilesToAttach}
+ onChange={(val) =>
+ setProfilesToAttach((val ?? []) as { value: string; label: string }[])
+ }
+ options={availableProfiles}
+ placeholder="Select profiles..."
+ />
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setIsAttachOpen(false)}>
+ Cancel
+ </Button>
+ <Button
+ variant="project"
+ onClick={handleAttach}
+ isDisabled={profilesToAttach.length === 0 || attachMutation.isPending}
+ isPending={attachMutation.isPending}
+ >
+ Attach
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <DeleteActionModal
+ isOpen={Boolean(profileToDetach)}
+ title={`Detach profile ${profileToDetach?.profileSlug ?? ""}?`}
+ subTitle="This Application will no longer be able to issue from this Profile. Existing certificates remain."
+ deleteKey="confirm"
+ onChange={(open) => {
+ if (!open) setProfileToDetach(null);
+ }}
+ onDeleteApproved={handleDetach}
+ />
+
+ <ConfigureEnrollmentModal
+ isOpen={Boolean(profileToConfigure)}
+ onOpenChange={(open) => {
+ if (!open) setProfileToConfigure(null);
+ }}
+ applicationId={application.id}
+ profile={profileToConfigure}
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSyncsTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSyncsTab.tsx
new file mode 100644
index 0000000000..fcdb3a4808
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSyncsTab.tsx
@@ -0,0 +1,65 @@
+import { useMemo, useState } from "react";
+import { PlusIcon } from "lucide-react";
+
+import { CreatePkiSyncModal } from "@app/components/pki-syncs";
+import { Spinner } from "@app/components/v2";
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle
+} from "@app/components/v3";
+import { useListPkiSyncs } from "@app/hooks/api/pkiSyncs";
+
+import { PkiSyncsTable } from "../../IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable";
+
+type Props = { applicationId: string; applicationName: string; projectId: string };
+
+export const ApplicationSyncsTab = ({ applicationId, applicationName, projectId }: Props) => {
+ const [isAddSyncOpen, setIsAddSyncOpen] = useState(false);
+
+ const { data, isPending } = useListPkiSyncs(projectId, {
+ enabled: Boolean(projectId),
+ refetchInterval: 30000
+ });
+
+ const applicationSyncs = useMemo(
+ () => (data ?? []).filter((sync) => sync.applicationId === applicationId),
+ [data, applicationId]
+ );
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Certificate Syncs</CardTitle>
+ <CardDescription>
+ Sync certificates issued by this Application out to AWS ACM, Cloudflare, Azure Key Vault,
+ and other destinations.
+ </CardDescription>
+ <CardAction>
+ <Button variant="project" onClick={() => setIsAddSyncOpen(true)}>
+ <PlusIcon />
+ Add Sync
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ {isPending ? (
+ <div className="flex items-center justify-center p-8">
+ <Spinner />
+ </div>
+ ) : (
+ <PkiSyncsTable pkiSyncs={applicationSyncs} applicationName={applicationName} />
+ )}
+ </CardContent>
+ <CreatePkiSyncModal
+ isOpen={isAddSyncOpen}
+ onOpenChange={setIsAddSyncOpen}
+ applicationId={applicationId}
+ />
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx
new file mode 100644
index 0000000000..e31418400c
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx
@@ -0,0 +1,795 @@
+import { useEffect, useState } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { faCheck, faCopy } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ FormControl,
+ FormLabel,
+ IconButton,
+ Input,
+ Spinner,
+ Switch,
+ Tab,
+ TabList,
+ TabPanel,
+ Tabs,
+ TextArea
+} from "@app/components/v2";
+import {
+ Badge,
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { useToggle } from "@app/hooks";
+import { useGetPkiApplicationEnrollment } from "@app/hooks/api/pkiApplications";
+import {
+ useClearPkiApplicationAcmeEnrollment,
+ useClearPkiApplicationApiEnrollment,
+ useClearPkiApplicationEstEnrollment,
+ useClearPkiApplicationScepEnrollment,
+ useRevealPkiApplicationAcmeEabSecret,
+ useRotatePkiApplicationAcmeEabSecret,
+ useSetPkiApplicationAcmeEnrollment,
+ useSetPkiApplicationApiEnrollment,
+ useSetPkiApplicationEstEnrollment,
+ useSetPkiApplicationScepEnrollment
+} from "@app/hooks/api/pkiApplications/mutations";
+import { ScepChallengeType, TPkiApplicationProfile } from "@app/hooks/api/pkiApplications/types";
+
+const COPY_RESET_MS = 1000;
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (open: boolean) => void;
+ applicationId: string;
+ profile: TPkiApplicationProfile | null;
+};
+
+const errorText = (err: unknown, fallback: string) =>
+ err instanceof Error ? err.message : fallback;
+
+const CopyableField = ({ label, value }: { label: string; value: string }) => {
+ const [copied, setCopied] = useToggle(false);
+ return (
+ <div>
+ <FormLabel label={label} />
+ <div className="flex gap-2">
+ <Input value={value} disabled />
+ <IconButton
+ ariaLabel={`copy ${label}`}
+ variant="outline_bg"
+ colorSchema="secondary"
+ className="w-10"
+ onClick={() => {
+ navigator.clipboard.writeText(value);
+ setCopied.on();
+ setTimeout(() => setCopied.off(), COPY_RESET_MS);
+ }}
+ >
+ <FontAwesomeIcon icon={copied ? faCheck : faCopy} />
+ </IconButton>
+ </div>
+ </div>
+ );
+};
+
+type ApiForm = { autoRenew: boolean; renewBeforeDays?: number };
+
+const ApiPanel = ({
+ applicationId,
+ profileId,
+ enabled,
+ initial
+}: {
+ applicationId: string;
+ profileId: string;
+ enabled: boolean;
+ initial: { autoRenew: boolean; renewBeforeDays: number | null } | null;
+}) => {
+ const setMutation = useSetPkiApplicationApiEnrollment();
+ const clearMutation = useClearPkiApplicationApiEnrollment();
+ const { control, handleSubmit, watch, reset } = useForm<ApiForm>({
+ defaultValues: {
+ autoRenew: initial?.autoRenew ?? false,
+ renewBeforeDays: initial?.renewBeforeDays ?? undefined
+ }
+ });
+
+ useEffect(() => {
+ reset({
+ autoRenew: initial?.autoRenew ?? false,
+ renewBeforeDays: initial?.renewBeforeDays ?? undefined
+ });
+ }, [initial?.autoRenew, initial?.renewBeforeDays, reset]);
+
+ const autoRenew = watch("autoRenew");
+
+ const onSave = handleSubmit(async (values) => {
+ try {
+ await setMutation.mutateAsync({
+ applicationId,
+ profileId,
+ autoRenew: values.autoRenew,
+ renewBeforeDays: values.autoRenew ? values.renewBeforeDays : undefined
+ });
+ createNotification({ type: "success", text: "API enrollment saved" });
+ } catch (err) {
+ createNotification({ type: "error", text: errorText(err, "Failed to save API enrollment") });
+ }
+ });
+
+ const onDisable = async () => {
+ try {
+ await clearMutation.mutateAsync({ applicationId, profileId });
+ createNotification({ type: "success", text: "API enrollment disabled" });
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: errorText(err, "Failed to disable API enrollment")
+ });
+ }
+ };
+
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-mineshaft-300">
+ API enrollment lets clients request certificates by calling the project API with this
+ profile.
+ </p>
+ <Controller
+ control={control}
+ name="autoRenew"
+ render={({ field }) => (
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <FormLabel label="Auto-renew" />
+ <p className="text-xs text-mineshaft-400">
+ Automatically renew certificates issued via this profile before they expire.
+ </p>
+ </div>
+ <Switch id="api-auto-renew" isChecked={field.value} onCheckedChange={field.onChange} />
+ </div>
+ )}
+ />
+ {autoRenew && (
+ <Controller
+ control={control}
+ name="renewBeforeDays"
+ rules={{ min: 1, max: 365 }}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Renew before (days)"
+ isError={Boolean(error)}
+ errorText="Must be between 1 and 365"
+ helperText="How many days before expiry to trigger renewal."
+ >
+ <Input
+ type="number"
+ min={1}
+ max={365}
+ value={field.value ?? ""}
+ onChange={(e) =>
+ field.onChange(e.target.value === "" ? undefined : Number(e.target.value))
+ }
+ placeholder="30"
+ />
+ </FormControl>
+ )}
+ />
+ )}
+ <div className="flex justify-end gap-2 pt-2">
+ {enabled && (
+ <Button variant="outline" onClick={onDisable} isPending={clearMutation.isPending}>
+ Disable
+ </Button>
+ )}
+ <Button variant="project" onClick={onSave} isPending={setMutation.isPending}>
+ {enabled ? "Save" : "Enable"}
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+type EstForm = { passphrase: string; disableBootstrapCaValidation: boolean; caChain?: string };
+
+const EstPanel = ({
+ applicationId,
+ profileId,
+ enabled,
+ initial
+}: {
+ applicationId: string;
+ profileId: string;
+ enabled: boolean;
+ initial: { disableBootstrapCaValidation: boolean } | null;
+}) => {
+ const setMutation = useSetPkiApplicationEstEnrollment();
+ const clearMutation = useClearPkiApplicationEstEnrollment();
+ const { control, handleSubmit, reset } = useForm<EstForm>({
+ defaultValues: {
+ passphrase: "",
+ disableBootstrapCaValidation: initial?.disableBootstrapCaValidation ?? false,
+ caChain: ""
+ }
+ });
+
+ useEffect(() => {
+ reset({
+ passphrase: "",
+ disableBootstrapCaValidation: initial?.disableBootstrapCaValidation ?? false,
+ caChain: ""
+ });
+ }, [initial?.disableBootstrapCaValidation, reset]);
+
+ const onSave = handleSubmit(async (values) => {
+ try {
+ await setMutation.mutateAsync({
+ applicationId,
+ profileId,
+ passphrase: values.passphrase,
+ disableBootstrapCaValidation: values.disableBootstrapCaValidation,
+ caChain: values.caChain || undefined
+ });
+ createNotification({ type: "success", text: "EST enrollment saved" });
+ } catch (err) {
+ createNotification({ type: "error", text: errorText(err, "Failed to save EST enrollment") });
+ }
+ });
+
+ const onDisable = async () => {
+ try {
+ await clearMutation.mutateAsync({ applicationId, profileId });
+ createNotification({ type: "success", text: "EST enrollment disabled" });
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: errorText(err, "Failed to disable EST enrollment")
+ });
+ }
+ };
+
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-mineshaft-300">
+ EST clients will authenticate to this profile with the passphrase below.
+ </p>
+ <Controller
+ control={control}
+ name="passphrase"
+ rules={{ required: !enabled, minLength: 8 }}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label={enabled ? "New passphrase (leave blank to keep current)" : "Passphrase"}
+ isError={Boolean(error)}
+ errorText="Minimum 8 characters"
+ >
+ <Input type="password" {...field} placeholder="••••••••" />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="caChain"
+ render={({ field }) => (
+ <FormControl
+ label="CA chain (optional)"
+ helperText="PEM-encoded chain returned by the EST endpoint."
+ >
+ <TextArea {...field} rows={3} placeholder="-----BEGIN CERTIFICATE-----..." />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="disableBootstrapCaValidation"
+ render={({ field }) => (
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <FormLabel label="Disable bootstrap CA validation" />
+ <p className="text-xs text-mineshaft-400">
+ Allow EST clients to skip server certificate validation during enrollment.
+ </p>
+ </div>
+ <Switch
+ id="est-disable-bootstrap"
+ isChecked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </div>
+ )}
+ />
+ <div className="flex justify-end gap-2 pt-2">
+ {enabled && (
+ <Button variant="outline" onClick={onDisable} isPending={clearMutation.isPending}>
+ Disable
+ </Button>
+ )}
+ <Button variant="project" onClick={onSave} isPending={setMutation.isPending}>
+ {enabled ? "Save" : "Enable"}
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+type AcmeForm = { skipDnsOwnershipVerification: boolean; skipEabBinding: boolean };
+
+const AcmePanel = ({
+ applicationId,
+ profileId,
+ enabled,
+ initial
+}: {
+ applicationId: string;
+ profileId: string;
+ enabled: boolean;
+ initial: { skipDnsOwnershipVerification: boolean; skipEabBinding: boolean } | null;
+}) => {
+ const setMutation = useSetPkiApplicationAcmeEnrollment();
+ const clearMutation = useClearPkiApplicationAcmeEnrollment();
+ const revealMutation = useRevealPkiApplicationAcmeEabSecret();
+ const rotateMutation = useRotatePkiApplicationAcmeEabSecret();
+ const [credentials, setCredentials] = useState<{ eabKid: string; eabSecret: string } | null>(
+ null
+ );
+ const { control, handleSubmit, watch, setValue, reset } = useForm<AcmeForm>({
+ defaultValues: {
+ skipDnsOwnershipVerification: initial?.skipDnsOwnershipVerification ?? false,
+ skipEabBinding: initial?.skipEabBinding ?? false
+ }
+ });
+
+ useEffect(() => {
+ reset({
+ skipDnsOwnershipVerification: initial?.skipDnsOwnershipVerification ?? false,
+ skipEabBinding: initial?.skipEabBinding ?? false
+ });
+ }, [initial?.skipDnsOwnershipVerification, initial?.skipEabBinding, reset]);
+
+ const skipDns = watch("skipDnsOwnershipVerification");
+ const skipEab = watch("skipEabBinding");
+
+ const onSave = handleSubmit(async (values) => {
+ if (values.skipDnsOwnershipVerification && values.skipEabBinding) {
+ createNotification({
+ type: "error",
+ text: "Pick at most one of: skip DNS ownership verification, skip EAB binding."
+ });
+ return;
+ }
+ try {
+ await setMutation.mutateAsync({ applicationId, profileId, ...values });
+ createNotification({ type: "success", text: "ACME enrollment saved" });
+ } catch (err) {
+ createNotification({ type: "error", text: errorText(err, "Failed to save ACME enrollment") });
+ }
+ });
+
+ const onDisable = async () => {
+ try {
+ await clearMutation.mutateAsync({ applicationId, profileId });
+ setCredentials(null);
+ createNotification({ type: "success", text: "ACME enrollment disabled" });
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: errorText(err, "Failed to disable ACME enrollment")
+ });
+ }
+ };
+
+ const onReveal = async () => {
+ try {
+ const data = await revealMutation.mutateAsync({ applicationId, profileId });
+ setCredentials({ eabKid: data.eabKid, eabSecret: data.eabSecret });
+ } catch (err) {
+ createNotification({ type: "error", text: errorText(err, "Failed to reveal EAB secret") });
+ }
+ };
+
+ const onRotate = async () => {
+ try {
+ await rotateMutation.mutateAsync({ applicationId, profileId });
+ const data = await revealMutation.mutateAsync({ applicationId, profileId });
+ setCredentials({ eabKid: data.eabKid, eabSecret: data.eabSecret });
+ createNotification({ type: "success", text: "ACME EAB secret rotated" });
+ } catch (err) {
+ createNotification({ type: "error", text: errorText(err, "Failed to rotate EAB secret") });
+ }
+ };
+
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-mineshaft-300">
+ ACME clients use the EAB credentials below to register an account against this profile.
+ </p>
+ <p className="text-xs text-mineshaft-400">
+ Pick at most one of the two options below — they are mutually exclusive.
+ </p>
+ <Controller
+ control={control}
+ name="skipDnsOwnershipVerification"
+ render={({ field }) => (
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <FormLabel label="Skip DNS ownership verification" />
+ <p className="text-xs text-mineshaft-400">
+ Skip DNS-01 / HTTP-01 challenge enforcement. Use only inside trusted networks.
+ </p>
+ </div>
+ <Switch
+ id="acme-skip-dns"
+ isChecked={field.value}
+ onCheckedChange={(v) => {
+ field.onChange(v);
+ if (v) setValue("skipEabBinding", false);
+ }}
+ isDisabled={skipEab}
+ />
+ </div>
+ )}
+ />
+ <Controller
+ control={control}
+ name="skipEabBinding"
+ render={({ field }) => (
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <FormLabel label="Skip EAB binding" />
+ <p className="text-xs text-mineshaft-400">
+ Allow accounts to register without an EAB key. Recommended off in production.
+ </p>
+ </div>
+ <Switch
+ id="acme-skip-eab"
+ isChecked={field.value}
+ onCheckedChange={(v) => {
+ field.onChange(v);
+ if (v) setValue("skipDnsOwnershipVerification", false);
+ }}
+ isDisabled={skipDns}
+ />
+ </div>
+ )}
+ />
+ {enabled && (
+ <div className="flex gap-2">
+ <Button variant="outline" onClick={onReveal} isPending={revealMutation.isPending}>
+ Reveal EAB credentials
+ </Button>
+ <Button variant="outline" onClick={onRotate} isPending={rotateMutation.isPending}>
+ Rotate EAB secret
+ </Button>
+ </div>
+ )}
+ {credentials && (
+ <div className="space-y-3 rounded-md border border-mineshaft-600 bg-mineshaft-800 p-3">
+ <CopyableField label="EAB KID" value={credentials.eabKid} />
+ <CopyableField label="EAB Secret" value={credentials.eabSecret} />
+ </div>
+ )}
+ <div className="flex justify-end gap-2 pt-2">
+ {enabled && (
+ <Button variant="outline" onClick={onDisable} isPending={clearMutation.isPending}>
+ Disable
+ </Button>
+ )}
+ <Button variant="project" onClick={onSave} isPending={setMutation.isPending}>
+ {enabled ? "Save" : "Enable"}
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+const ScepPanel = ({
+ applicationId,
+ profileId,
+ enabled,
+ initial
+}: {
+ applicationId: string;
+ profileId: string;
+ enabled: boolean;
+ initial: {
+ challengeType: ScepChallengeType;
+ includeCaCertInResponse: boolean;
+ allowCertBasedRenewal: boolean;
+ dynamicChallengeExpiryMinutes: number | null;
+ dynamicChallengeMaxPending: number | null;
+ } | null;
+}) => {
+ const setMutation = useSetPkiApplicationScepEnrollment();
+ const clearMutation = useClearPkiApplicationScepEnrollment();
+ const { control, handleSubmit, watch, reset } = useForm<{
+ challengeType: ScepChallengeType;
+ challengePassword?: string;
+ includeCaCertInResponse: boolean;
+ allowCertBasedRenewal: boolean;
+ dynamicChallengeExpiryMinutes?: number;
+ dynamicChallengeMaxPending?: number;
+ }>({
+ defaultValues: {
+ challengeType: initial?.challengeType ?? "static",
+ challengePassword: "",
+ includeCaCertInResponse: initial?.includeCaCertInResponse ?? true,
+ allowCertBasedRenewal: initial?.allowCertBasedRenewal ?? true,
+ dynamicChallengeExpiryMinutes: initial?.dynamicChallengeExpiryMinutes ?? 60,
+ dynamicChallengeMaxPending: initial?.dynamicChallengeMaxPending ?? 100
+ }
+ });
+
+ useEffect(() => {
+ reset({
+ challengeType: initial?.challengeType ?? "static",
+ challengePassword: "",
+ includeCaCertInResponse: initial?.includeCaCertInResponse ?? true,
+ allowCertBasedRenewal: initial?.allowCertBasedRenewal ?? true,
+ dynamicChallengeExpiryMinutes: initial?.dynamicChallengeExpiryMinutes ?? 60,
+ dynamicChallengeMaxPending: initial?.dynamicChallengeMaxPending ?? 100
+ });
+ }, [
+ initial?.challengeType,
+ initial?.includeCaCertInResponse,
+ initial?.allowCertBasedRenewal,
+ initial?.dynamicChallengeExpiryMinutes,
+ initial?.dynamicChallengeMaxPending,
+ reset
+ ]);
+
+ const challengeType = watch("challengeType");
+
+ const onSave = handleSubmit(async (values) => {
+ try {
+ await setMutation.mutateAsync({ applicationId, profileId, ...values });
+ createNotification({ type: "success", text: "SCEP enrollment saved" });
+ } catch (err) {
+ createNotification({ type: "error", text: errorText(err, "Failed to save SCEP enrollment") });
+ }
+ });
+
+ const onDisable = async () => {
+ try {
+ await clearMutation.mutateAsync({ applicationId, profileId });
+ createNotification({ type: "success", text: "SCEP enrollment disabled" });
+ } catch (err) {
+ createNotification({
+ type: "error",
+ text: errorText(err, "Failed to disable SCEP enrollment")
+ });
+ }
+ };
+
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-mineshaft-300">
+ SCEP clients enroll by presenting a challenge password. Use static for shared passwords,
+ dynamic for one-time per-client challenges.
+ </p>
+ <Controller
+ control={control}
+ name="challengeType"
+ render={({ field }) => (
+ <FormControl label="Challenge type">
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="static">Static password</SelectItem>
+ <SelectItem value="dynamic">Dynamic (per-client)</SelectItem>
+ </SelectContent>
+ </Select>
+ </FormControl>
+ )}
+ />
+ {challengeType === "static" && (
+ <Controller
+ control={control}
+ name="challengePassword"
+ rules={{ required: !enabled }}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label={
+ enabled
+ ? "New challenge password (leave blank to keep current)"
+ : "Challenge password"
+ }
+ isError={Boolean(error)}
+ errorText="Required"
+ >
+ <Input type="password" {...field} placeholder="••••••••" />
+ </FormControl>
+ )}
+ />
+ )}
+ {challengeType === "dynamic" && (
+ <div className="grid grid-cols-2 gap-4">
+ <Controller
+ control={control}
+ name="dynamicChallengeExpiryMinutes"
+ render={({ field }) => (
+ <FormControl label="Challenge expiry (minutes)">
+ <Input
+ type="number"
+ min={5}
+ max={1440}
+ value={field.value ?? ""}
+ onChange={(e) =>
+ field.onChange(e.target.value === "" ? undefined : Number(e.target.value))
+ }
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="dynamicChallengeMaxPending"
+ render={({ field }) => (
+ <FormControl label="Max pending challenges">
+ <Input
+ type="number"
+ min={1}
+ max={1000}
+ value={field.value ?? ""}
+ onChange={(e) =>
+ field.onChange(e.target.value === "" ? undefined : Number(e.target.value))
+ }
+ />
+ </FormControl>
+ )}
+ />
+ </div>
+ )}
+ <Controller
+ control={control}
+ name="includeCaCertInResponse"
+ render={({ field }) => (
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <FormLabel label="Include CA cert in response" />
+ <p className="text-xs text-mineshaft-400">
+ Return the issuing CA certificate inline alongside the issued cert.
+ </p>
+ </div>
+ <Switch id="scep-include-ca" isChecked={field.value} onCheckedChange={field.onChange} />
+ </div>
+ )}
+ />
+ <Controller
+ control={control}
+ name="allowCertBasedRenewal"
+ render={({ field }) => (
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <FormLabel label="Allow cert-based renewal" />
+ <p className="text-xs text-mineshaft-400">
+ Let clients renew using their existing certificate as authentication.
+ </p>
+ </div>
+ <Switch
+ id="scep-cert-renewal"
+ isChecked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </div>
+ )}
+ />
+ <div className="flex justify-end gap-2 pt-2">
+ {enabled && (
+ <Button variant="outline" onClick={onDisable} isPending={clearMutation.isPending}>
+ Disable
+ </Button>
+ )}
+ <Button variant="project" onClick={onSave} isPending={setMutation.isPending}>
+ {enabled ? "Save" : "Enable"}
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+export const ConfigureEnrollmentModal = ({
+ isOpen,
+ onOpenChange,
+ applicationId,
+ profile
+}: Props) => {
+ const profileId = profile?.profileId ?? "";
+ const { data, isLoading } = useGetPkiApplicationEnrollment(applicationId, profileId);
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-2xl overflow-visible">
+ <DialogHeader>
+ <DialogTitle>
+ Configure issuance · <span className="font-mono">{profile?.profileSlug ?? ""}</span>
+ </DialogTitle>
+ <DialogDescription>
+ Enable an enrollment method to allow clients to request certificates from this Profile
+ through this Application.
+ </DialogDescription>
+ </DialogHeader>
+
+ {!profile || isLoading ? (
+ <div className="flex items-center justify-center py-8">
+ <Spinner size="sm" />
+ </div>
+ ) : (
+ <Tabs defaultValue="api">
+ <TabList>
+ <Tab value="api">
+ <span className="inline-flex items-center gap-2">
+ API
+ {data?.api ? <Badge variant="success">on</Badge> : null}
+ </span>
+ </Tab>
+ <Tab value="est">
+ <span className="inline-flex items-center gap-2">
+ EST
+ {data?.estConfigured ? <Badge variant="success">on</Badge> : null}
+ </span>
+ </Tab>
+ <Tab value="acme">
+ <span className="inline-flex items-center gap-2">
+ ACME
+ {data?.acmeConfigured ? <Badge variant="success">on</Badge> : null}
+ </span>
+ </Tab>
+ <Tab value="scep">
+ <span className="inline-flex items-center gap-2">
+ SCEP
+ {data?.scepConfigured ? <Badge variant="success">on</Badge> : null}
+ </span>
+ </Tab>
+ </TabList>
+ <TabPanel value="api">
+ <ApiPanel
+ applicationId={applicationId}
+ profileId={profileId}
+ enabled={Boolean(data?.api)}
+ initial={data?.api ?? null}
+ />
+ </TabPanel>
+ <TabPanel value="est">
+ <EstPanel
+ applicationId={applicationId}
+ profileId={profileId}
+ enabled={Boolean(data?.estConfigured)}
+ initial={data?.est ?? null}
+ />
+ </TabPanel>
+ <TabPanel value="acme">
+ <AcmePanel
+ applicationId={applicationId}
+ profileId={profileId}
+ enabled={Boolean(data?.acmeConfigured)}
+ initial={data?.acme ?? null}
+ />
+ </TabPanel>
+ <TabPanel value="scep">
+ <ScepPanel
+ applicationId={applicationId}
+ profileId={profileId}
+ enabled={Boolean(data?.scepConfigured)}
+ initial={data?.scep ?? null}
+ />
+ </TabPanel>
+ </Tabs>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/route.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/route.tsx
new file mode 100644
index 0000000000..8bae1eb854
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/route.tsx
@@ -0,0 +1,29 @@
+import { createFileRoute, stripSearchParams } from "@tanstack/react-router";
+import { zodValidator } from "@tanstack/zod-adapter";
+import { z } from "zod";
+
+import { ApplicationDetailsByIDPage } from "./ApplicationDetailsByIDPage";
+
+const ApplicationTabSchema = z.enum([
+ "overview",
+ "certificates",
+ "requests",
+ "syncs",
+ "members",
+ "settings"
+]);
+
+const SearchSchema = z.object({
+ selectedTab: ApplicationTabSchema.optional()
+});
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/$applicationName"
+)({
+ component: ApplicationDetailsByIDPage,
+ validateSearch: zodValidator(SearchSchema),
+ search: { middlewares: [stripSearchParams({ selectedTab: "overview" })] },
+ beforeLoad: ({ context }) => ({
+ breadcrumbs: [...context.breadcrumbs, { label: "Applications" }, { label: "Application" }]
+ })
+});
diff --git a/frontend/src/pages/cert-manager/ApplicationsPage/ApplicationsPage.tsx b/frontend/src/pages/cert-manager/ApplicationsPage/ApplicationsPage.tsx
new file mode 100644
index 0000000000..8ca40322b2
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationsPage/ApplicationsPage.tsx
@@ -0,0 +1,200 @@
+import { Helmet } from "react-helmet";
+import { useNavigate, useParams } from "@tanstack/react-router";
+import { Hexagon, MoreHorizontalIcon, PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { DeleteActionModal, PageHeader, Spinner } from "@app/components/v2";
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import {
+ TPkiApplication,
+ useDeletePkiApplication,
+ useListPkiApplications
+} from "@app/hooks/api/pkiApplications";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import { usePopUp } from "@app/hooks/usePopUp";
+
+import { PkiApplicationModal } from "./components/PkiApplicationModal";
+
+export const ApplicationsPage = () => {
+ const { projectId, orgId } = useParams({ strict: false });
+ const navigate = useNavigate();
+ const { data: applications, isPending } = useListPkiApplications();
+ const deleteApp = useDeletePkiApplication();
+
+ const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([
+ "application",
+ "deleteApplication"
+ ] as const);
+
+ const renderApplications = () => {
+ if (isPending) {
+ return (
+ <div className="flex items-center justify-center p-8">
+ <Spinner />
+ </div>
+ );
+ }
+ if (!applications || applications.length === 0) {
+ return (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>No applications yet</EmptyTitle>
+ <EmptyDescription>
+ Create an Application to attach Profiles and grant access to a team.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+ }
+ return (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ <TableHead>Description</TableHead>
+ <TableHead>Profiles</TableHead>
+ <TableHead>Members</TableHead>
+ <TableHead>Certificates</TableHead>
+ <TableHead>Created</TableHead>
+ <TableHead className="w-5" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {applications.map((app) => (
+ <TableRow
+ key={app.id}
+ className="cursor-pointer"
+ onClick={() =>
+ navigate({
+ to: `/organizations/${orgId ?? ""}/projects/cert-manager/${projectId ?? ""}/applications/${app.slug}` as never
+ } as never)
+ }
+ >
+ <TableCell isTruncatable>
+ <div className="flex items-center gap-x-2 font-mono">
+ <Hexagon className="size-5 shrink-0 text-primary" strokeWidth={1.75} />
+ <span>{app.name}</span>
+ </div>
+ </TableCell>
+ <TableCell isTruncatable className="text-accent">
+ {app.description?.length ? app.description : "—"}
+ </TableCell>
+ <TableCell>{app.profileCount}</TableCell>
+ <TableCell>{app.memberCount}</TableCell>
+ <TableCell>{app.certificateCount}</TableCell>
+ <TableCell className="text-accent">
+ {new Date(app.createdAt).toLocaleDateString()}
+ </TableCell>
+ <TableCell>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="xs" onClick={(e) => e.stopPropagation()}>
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="min-w-40" align="end" sideOffset={2}>
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePopUpOpen("application", app);
+ }}
+ >
+ <PencilIcon />
+ Edit Application
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="danger"
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePopUpOpen("deleteApplication", app);
+ }}
+ >
+ <Trash2Icon />
+ Delete Application
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ );
+ };
+
+ return (
+ <>
+ <Helmet>
+ <title>Applications</title>
+ </Helmet>
+ <div className="h-full bg-bunker-800">
+ <div className="mx-auto flex flex-col text-white">
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <PageHeader
+ scope={ProjectType.CertificateManager}
+ title="Applications"
+ description="Applications attach one or more Profiles and a team. Each Application has its own members, roles, certificates, alerts, and approval policies."
+ />
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Applications</CardTitle>
+ <CardAction>
+ <Button variant="project" onClick={() => handlePopUpOpen("application")}>
+ <PlusIcon />
+ Create Application
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>{renderApplications()}</CardContent>
+ </Card>
+ </div>
+ </div>
+ </div>
+
+ <PkiApplicationModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
+
+ <DeleteActionModal
+ isOpen={popUp.deleteApplication.isOpen}
+ title={`Delete ${(popUp.deleteApplication.data as TPkiApplication | undefined)?.name ?? "Application"}?`}
+ subTitle="This unattaches all Profiles, app-scoped syncs/alerts, and revokes app-only memberships. Issued certificates remain in the project but lose their Application tag."
+ onChange={(isOpen) => handlePopUpToggle("deleteApplication", isOpen)}
+ deleteKey="confirm"
+ onDeleteApproved={async () => {
+ const app = popUp.deleteApplication.data as TPkiApplication | undefined;
+ if (!app) return;
+ try {
+ await deleteApp.mutateAsync({ applicationId: app.id });
+ createNotification({ type: "success", text: `Deleted ${app.name}` });
+ handlePopUpClose("deleteApplication");
+ } catch (err) {
+ const detail = err instanceof Error ? err.message : "Failed to delete Application.";
+ createNotification({ type: "error", text: detail });
+ }
+ }}
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/ApplicationsPage/components/PkiApplicationModal.tsx b/frontend/src/pages/cert-manager/ApplicationsPage/components/PkiApplicationModal.tsx
new file mode 100644
index 0000000000..2521a04174
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationsPage/components/PkiApplicationModal.tsx
@@ -0,0 +1,161 @@
+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,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldError,
+ FieldLabel,
+ Input,
+ TextArea
+} from "@app/components/v3";
+import {
+ TPkiApplication,
+ useCreatePkiApplication,
+ useUpdatePkiApplication
+} from "@app/hooks/api/pkiApplications";
+import { UsePopUpState } from "@app/hooks/usePopUp";
+
+const SLUG_REGEX = /^[a-z0-9-]+$/;
+
+const schema = z.object({
+ name: z
+ .string()
+ .trim()
+ .min(1, "Name is required")
+ .max(64)
+ .regex(SLUG_REGEX, "Name must contain only lowercase letters, numbers, and hyphens"),
+ description: z.string().trim().max(256).optional()
+});
+
+type FormData = z.infer<typeof schema>;
+
+type Props = {
+ popUp: UsePopUpState<["application"]>;
+ handlePopUpToggle: (popUpName: keyof UsePopUpState<["application"]>, state?: boolean) => void;
+};
+
+export const PkiApplicationModal = ({ popUp, handlePopUpToggle }: Props) => {
+ const editing = (popUp?.application?.data as TPkiApplication | undefined) ?? null;
+ const create = useCreatePkiApplication();
+ const update = useUpdatePkiApplication();
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ formState: { isSubmitting }
+ } = useForm<FormData>({
+ resolver: zodResolver(schema),
+ defaultValues: { name: "", description: "" }
+ });
+
+ useEffect(() => {
+ if (editing) {
+ reset({
+ name: editing.name,
+ description: editing.description ?? ""
+ });
+ } else {
+ reset({ name: "", description: "" });
+ }
+ }, [editing, reset]);
+
+ const onSubmit = async (data: FormData) => {
+ try {
+ if (editing) {
+ await update.mutateAsync({
+ applicationId: editing.id,
+ name: data.name,
+ slug: data.name,
+ description: data.description?.length ? data.description : null
+ });
+ createNotification({ type: "success", text: "Application updated" });
+ } else {
+ await create.mutateAsync({
+ name: data.name,
+ slug: data.name,
+ description: data.description
+ });
+ createNotification({ type: "success", text: "Application created" });
+ }
+ handlePopUpToggle("application", false);
+ } catch (err) {
+ const detail = err instanceof Error ? err.message : "Failed to save application.";
+ createNotification({ type: "error", text: detail });
+ }
+ };
+
+ return (
+ <Dialog
+ open={popUp?.application?.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("application", isOpen)}
+ >
+ <DialogContent className="max-w-lg">
+ <DialogHeader>
+ <DialogTitle>{editing ? "Edit Application" : "Create Application"}</DialogTitle>
+ <DialogDescription>
+ {editing
+ ? "Update the Application's metadata. Changing the name will invalidate any deep links."
+ : "Applications attach Profiles and a team. Members and certs are scoped to the Application. The name is used as the identifier (Terraform, agents) so use a slug-style value."}
+ </DialogDescription>
+ </DialogHeader>
+
+ <form onSubmit={handleSubmit(onSubmit)} className="space-y-3">
+ <Controller
+ control={control}
+ name="name"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Name</FieldLabel>
+ <FieldContent>
+ <Input {...field} placeholder="payments-service" />
+ </FieldContent>
+ {error ? <FieldError>{error.message}</FieldError> : null}
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="description"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Description</FieldLabel>
+ <FieldContent>
+ <TextArea
+ {...field}
+ placeholder="Issues and rotates certificates for the payments stack."
+ />
+ </FieldContent>
+ {error ? <FieldError>{error.message}</FieldError> : null}
+ </Field>
+ )}
+ />
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => handlePopUpToggle("application", false)}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" variant="project" isPending={isSubmitting}>
+ {editing ? "Save Changes" : "Create Application"}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/ApplicationsPage/route.tsx b/frontend/src/pages/cert-manager/ApplicationsPage/route.tsx
new file mode 100644
index 0000000000..4ccad9e8b1
--- /dev/null
+++ b/frontend/src/pages/cert-manager/ApplicationsPage/route.tsx
@@ -0,0 +1,12 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { ApplicationsPage } from "./ApplicationsPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/"
+)({
+ component: ApplicationsPage,
+ beforeLoad: ({ context }) => ({
+ breadcrumbs: [...context.breadcrumbs, { label: "Applications" }]
+ })
+});
diff --git a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/CertificateDetailsSection.tsx b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/CertificateDetailsSection.tsx
index b2e345a9ef..af64edb92f 100644
--- a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/CertificateDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/CertificateDetailsSection.tsx
@@ -62,10 +62,7 @@ export const CertificateDetailsSection = ({ request }: Props) => {
});
// Fetch the actual certificate request record to get all fields (including subject info and basic constraints)
- const { data: certRequestDetails } = useGetCertificateRequest(
- requestData.certificateRequestId,
- currentProject?.slug || ""
- );
+ const { data: certRequestDetails } = useGetCertificateRequest(requestData.certificateRequestId);
const isInternalCa = profile?.certificateAuthority && !profile.certificateAuthority.isExternal;
const caId = profile?.certificateAuthority?.id;
diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/PolicyTab.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/PolicyTab.tsx
index 8d85c18db5..1d2727541e 100644
--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/PolicyTab.tsx
+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/PolicyTab.tsx
@@ -1,9 +1,6 @@
-import { faPlus } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-
import { createNotification } from "@app/components/notifications";
import { PermissionDeniedBanner } from "@app/components/permissions";
-import { Button, DeleteActionModal } from "@app/components/v2";
+import { DeleteActionModal } from "@app/components/v2";
import { useProject, useProjectPermission } from "@app/context";
import { usePopUp } from "@app/hooks";
import { ApprovalPolicyType, useDeleteApprovalPolicy } from "@app/hooks/api/approvalPolicies";
@@ -49,25 +46,16 @@ export const PolicyTab = () => {
return (
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <div className="mb-4 flex items-center">
+ <div className="mb-4 flex items-start">
<div className="flex-1">
<div className="flex items-center gap-x-2">
<p className="text-xl font-medium text-mineshaft-100">Certificate Approval Policies</p>
</div>
<p className="text-sm text-bunker-300">
- Define policies that require approval before certificates can be issued from specific
- profiles
+ Existing project-level policies remain editable. Create new approval policies inside a
+ Cert Manager Application.
</p>
</div>
-
- <Button
- variant="outline_bg"
- type="submit"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={() => handlePopUpOpen("policy")}
- >
- Create Policy
- </Button>
</div>
<PoliciesTable handlePopUpOpen={handlePopUpOpen} />
diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PoliciesTable.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PoliciesTable.tsx
index 44bef9d6c5..2ee0022748 100644
--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PoliciesTable.tsx
+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PoliciesTable.tsx
@@ -40,16 +40,18 @@ type Props = {
popUpName: keyof UsePopUpState<["policy", "deletePolicy"]>,
data?: { policyId: string; policy?: TApprovalPolicy }
) => void;
+ applicationId?: string;
};
-export const PoliciesTable = ({ handlePopUpOpen }: Props) => {
+export const PoliciesTable = ({ handlePopUpOpen, applicationId }: Props) => {
const { currentProject } = useProject();
const projectId = currentProject?.id || "";
const { data: policies = [], isPending: isPoliciesLoading } = useQuery(
approvalPolicyQuery.list({
policyType: ApprovalPolicyType.CertRequest,
- projectId
+ projectId,
+ applicationId
})
);
@@ -84,7 +86,14 @@ export const PoliciesTable = ({ handlePopUpOpen }: Props) => {
return (
<Tr key={policy.id} className="group">
<Td>
- <div className="text-sm font-medium text-mineshaft-100">{policy.name}</div>
+ <div className="flex items-center gap-x-2">
+ <span className="text-sm font-medium text-mineshaft-100">{policy.name}</span>
+ {!policy.applicationId && (
+ <span className="rounded bg-mineshaft-600 px-2 py-0.5 text-[10px] tracking-wide text-mineshaft-200 uppercase">
+ Legacy
+ </span>
+ )}
+ </div>
</Td>
<Td>
<div className="flex flex-wrap items-center gap-1">
diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicyModal.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicyModal.tsx
index 1e393d269e..bea58ae83c 100644
--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicyModal.tsx
+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicyModal.tsx
@@ -23,6 +23,7 @@ import { PolicyFormSchema, TPolicyForm } from "./PolicySchema";
type Props = {
popUp: UsePopUpState<["policy"]>;
handlePopUpToggle: (popUpName: keyof UsePopUpState<["policy"]>, state?: boolean) => void;
+ applicationId?: string;
};
const FORM_STEPS: { name: string; key: string; fields: (keyof TPolicyForm)[] }[] = [
@@ -35,7 +36,7 @@ const FORM_STEPS: { name: string; key: string; fields: (keyof TPolicyForm)[] }[]
{ name: "Review", key: "review", fields: [] }
];
-export const PolicyModal = ({ popUp, handlePopUpToggle }: Props) => {
+export const PolicyModal = ({ popUp, handlePopUpToggle, applicationId }: Props) => {
const { currentProject } = useProject();
const isOpen = popUp?.policy?.isOpen;
const policyData = popUp?.policy?.data as
@@ -120,6 +121,7 @@ export const PolicyModal = ({ popUp, handlePopUpToggle }: Props) => {
await createPolicy({
policyType: ApprovalPolicyType.CertRequest,
projectId: currentProject.id,
+ ...(applicationId && { applicationId }),
...data
});
createNotification({
@@ -214,7 +216,7 @@ export const PolicyModal = ({ popUp, handlePopUpToggle }: Props) => {
</Tab.List>
<Tab.Panels>
<Tab.Panel>
- <PolicyDetailsStep />
+ <PolicyDetailsStep applicationId={applicationId} />
</Tab.Panel>
<Tab.Panel>
<PolicyApprovalSteps />
diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicySteps/PolicyDetailsStep.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicySteps/PolicyDetailsStep.tsx
index 209dbb352d..dc3b502d10 100644
--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicySteps/PolicyDetailsStep.tsx
+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/PolicyTab/components/PolicySteps/PolicyDetailsStep.tsx
@@ -3,8 +3,8 @@ import { Controller, useFormContext } from "react-hook-form";
import { TtlFormLabel } from "@app/components/features";
import { Checkbox, FilterableSelect, FormControl, Input } from "@app/components/v2";
-import { useProject } from "@app/context";
import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";
+import { useListPkiApplicationProfiles } from "@app/hooks/api/pkiApplications";
import { TPolicyForm } from "../PolicySchema";
@@ -13,22 +13,29 @@ type ProfileOption = {
value: string;
};
-export const PolicyDetailsStep = () => {
+type Props = {
+ applicationId?: string;
+};
+
+export const PolicyDetailsStep = ({ applicationId }: Props) => {
const { control } = useFormContext<TPolicyForm>();
- const { currentProject } = useProject();
- const { data: profilesData, isPending: isProfilesLoading } = useListCertificateProfiles({
- projectId: currentProject?.id || ""
- });
+ const { data: profilesData, isPending: isProfilesLoading } = useListCertificateProfiles({});
+ const { data: appProfiles = [], isPending: isAppProfilesLoading } = useListPkiApplicationProfiles(
+ applicationId ?? ""
+ );
const profileOptions: ProfileOption[] = useMemo(() => {
+ if (applicationId) {
+ return appProfiles.map((p) => ({ label: p.profileSlug, value: p.profileSlug }));
+ }
return (
profilesData?.certificateProfiles?.map((profile) => ({
label: profile.slug,
value: profile.slug
})) || []
);
- }, [profilesData?.certificateProfiles]);
+ }, [applicationId, appProfiles, profilesData?.certificateProfiles]);
return (
<div className="flex flex-col gap-4">
@@ -90,7 +97,7 @@ export const PolicyDetailsStep = () => {
>
<FilterableSelect
isMulti
- isLoading={isProfilesLoading}
+ isLoading={applicationId ? isAppProfilesLoading : isProfilesLoading}
options={profileOptions}
value={profileField.value.map((slug) => ({ label: slug, value: slug }))}
onChange={(selected) => {
diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/route.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/route.tsx
index bbbab5deac..f01a2d82ae 100644
--- a/frontend/src/pages/cert-manager/ApprovalsPage/route.tsx
+++ b/frontend/src/pages/cert-manager/ApprovalsPage/route.tsx
@@ -6,7 +6,8 @@ import { ApprovalsPage } from "./ApprovalsPage";
const ApprovalsSearchSchema = z.object({
selectedTab: z.string().optional().default("requests"),
- section: z.enum(["certificates", "code-signing"]).optional().default("certificates")
+ section: z.enum(["certificates", "code-signing"]).optional().default("certificates"),
+ legacy: z.enum(["true"]).optional()
});
export const Route = createFileRoute(
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
index dc4ae393ea..0ae3731460 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
@@ -70,7 +70,6 @@ const Page = () => {
await deleteCa({
id: data.id,
- projectId: currentProject.id,
type: CaType.INTERNAL
});
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
index b2945ca2d1..8ba8c41f17 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
@@ -133,7 +133,7 @@ export const CaDetailsSection = ({ caId }: Props) => {
queryClient.invalidateQueries({ queryKey: caKeys.getCaCerts(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCert(caId) });
queryClient.invalidateQueries({
- queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL, currentProject.id)
+ queryKey: caKeys.listCasByTypeAndProjectId(CaType.INTERNAL)
});
}
}, [autoRenewal?.lastRenewalStatus, caId, currentProject.id, queryClient]);
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDistributionPointsSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDistributionPointsSection.tsx
index 3a5110b508..41933d43f0 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDistributionPointsSection.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDistributionPointsSection.tsx
@@ -113,7 +113,6 @@ export const CaDistributionPointsSection = ({ caId }: Props) => {
await updateCa({
id: ca.id,
type: CaType.INTERNAL,
- projectId: ca.projectId,
configuration: {
crlDistributionPointUrls: crlDistributionPointUrls.map(({ value }) => value)
} as TInternalCertificateAuthority["configuration"]
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx
index 85866c5f01..267cd92aa7 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx
@@ -12,7 +12,6 @@ import {
Select,
SelectItem
} from "@app/components/v2";
-import { useProject } from "@app/context";
import {
CaRenewalType,
CaSigningConfigType,
@@ -79,9 +78,6 @@ type Props = {
};
export const CaRenewalModal = ({ popUp, handlePopUpToggle }: Props) => {
- const { currentProject } = useProject();
- const projectSlug = currentProject?.slug || "";
-
const popUpData = popUp?.renewCa?.data as {
caId: string;
};
@@ -97,10 +93,8 @@ export const CaRenewalModal = ({ popUp, handlePopUpToggle }: Props) => {
const { mutateAsync: renewCa } = useRenewCa();
const { mutateAsync: installVenafiCert, isPending: isVenafiRenewing } =
- useInstallCaCertificateVenafi(currentProject.id);
- const { mutateAsync: installAdcsCert, isPending: isAdcsRenewing } = useInstallCaCertificateAdcs(
- currentProject.id
- );
+ useInstallCaCertificateVenafi();
+ const { mutateAsync: installAdcsCert, isPending: isAdcsRenewing } = useInstallCaCertificateAdcs();
const {
control,
@@ -116,11 +110,10 @@ export const CaRenewalModal = ({ popUp, handlePopUpToggle }: Props) => {
});
const onFormSubmit = async ({ type, notAfter }: FormData) => {
- if (!projectSlug || !popUpData.caId) return;
+ if (!popUpData.caId) return;
try {
await renewCa({
- projectSlug,
caId: popUpData.caId,
notAfter,
type
diff --git a/frontend/src/pages/cert-manager/CertManagerAccessPage/CertManagerAccessPage.tsx b/frontend/src/pages/cert-manager/CertManagerAccessPage/CertManagerAccessPage.tsx
new file mode 100644
index 0000000000..4654f305fc
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertManagerAccessPage/CertManagerAccessPage.tsx
@@ -0,0 +1,150 @@
+import { Helmet } from "react-helmet";
+import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
+
+import { EmptyState, PageHeader, Spinner, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
+import { useOrganization } from "@app/context";
+import { useGetOrgUsers } from "@app/hooks/api";
+import { ProjectType } from "@app/hooks/api/projects/types";
+
+const CERT_MANAGER_ORG_ROLES = new Set<string>([
+ "cert-manager-admin",
+ "cert-manager-guest",
+ "admin"
+]);
+
+const roleLabel = (role: string) => {
+ if (role === "cert-manager-admin") return "Admin";
+ if (role === "cert-manager-guest") return "Member";
+ if (role === "admin") return "Admin (org)";
+ if (role === "custom") return "Member";
+ return role;
+};
+
+export const CertManagerAccessPage = () => {
+ const { orgId, projectId } = useParams({ strict: false });
+ const search = useSearch({ strict: false }) as { selectedTab?: string };
+ const navigate = useNavigate();
+ const { currentOrg } = useOrganization();
+ const { data: orgUsers, isPending } = useGetOrgUsers(currentOrg?.id ?? "");
+
+ const selectedTab = search.selectedTab ?? "users";
+
+ const certManagerUsers = (orgUsers ?? []).filter((u) =>
+ CERT_MANAGER_ORG_ROLES.has(u.role as string)
+ );
+
+ const renderUsersPanel = () => {
+ if (isPending) {
+ return (
+ <div className="flex items-center justify-center p-6">
+ <Spinner />
+ </div>
+ );
+ }
+ if (certManagerUsers.length === 0) {
+ return (
+ <EmptyState title="No members yet">
+ Assign the <span className="font-mono">cert-manager-admin</span> or{" "}
+ <span className="font-mono">cert-manager-guest</span> role to an org member from Org
+ Access Control.
+ </EmptyState>
+ );
+ }
+ return (
+ <table className="w-full text-left text-sm text-mineshaft-200">
+ <thead className="border-b border-mineshaft-600 text-mineshaft-300">
+ <tr>
+ <th className="py-2">Name</th>
+ <th className="py-2">Email</th>
+ <th className="py-2 text-right">Role</th>
+ </tr>
+ </thead>
+ <tbody>
+ {certManagerUsers.map((u) => (
+ <tr key={u.id} className="border-b border-mineshaft-700 last:border-0">
+ <td className="py-3">
+ <div className="font-medium">
+ {u.user.firstName} {u.user.lastName}
+ </div>
+ <div className="font-mono text-xs text-mineshaft-400">{u.user.username}</div>
+ </td>
+ <td className="py-3 text-mineshaft-300">{u.user.email ?? u.inviteEmail ?? "—"}</td>
+ <td className="py-3 text-right">
+ <span
+ className={`rounded px-2 py-1 text-xs ${
+ (u.role as string) === "cert-manager-admin" || u.role === "admin"
+ ? "bg-green-700/40 text-green-300"
+ : "bg-mineshaft-700 text-mineshaft-200"
+ }`}
+ >
+ {roleLabel(u.role)}
+ </span>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ );
+ };
+
+ return (
+ <>
+ <Helmet>
+ <title>Access Control</title>
+ </Helmet>
+ <div className="h-full bg-bunker-800">
+ <div className="mx-auto flex flex-col text-white">
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <PageHeader
+ scope={ProjectType.CertificateManager}
+ title="Access Control"
+ description="Admins can manage Settings, CAs, Profiles, and create Applications. Admins of an Application — and access to issued certificates — are managed inside each Application's Access Control."
+ />
+
+ <Tabs
+ value={selectedTab}
+ onValueChange={(v) =>
+ navigate({
+ to: `/organizations/${orgId ?? ""}/projects/cert-manager/${projectId ?? ""}/cert-manager-access`,
+ search: { selectedTab: v } as never
+ } as never)
+ }
+ >
+ <TabList>
+ <Tab variant="project" value="users">
+ Users
+ </Tab>
+ <Tab variant="project" value="groups">
+ Groups
+ </Tab>
+ <Tab variant="project" value="identities">
+ Machine Identities
+ </Tab>
+ </TabList>
+
+ <TabPanel value="users">
+ <div className="rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4">
+ <h3 className="mb-3 text-base font-medium text-mineshaft-100">Users</h3>
+ {renderUsersPanel()}
+ </div>
+ </TabPanel>
+ <TabPanel value="groups">
+ <div className="rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4 text-sm text-mineshaft-300">
+ Groups assigned the cert-manager-admin or cert-manager-guest org role appear here.
+ Application-level group memberships live inside each Application&apos;s Access
+ Control tab.
+ </div>
+ </TabPanel>
+ <TabPanel value="identities">
+ <div className="rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4 text-sm text-mineshaft-300">
+ Machine identities assigned the cert-manager-admin role appear here. These
+ identities can manage the Cert Manager surface programmatically.
+ </div>
+ </TabPanel>
+ </Tabs>
+ </div>
+ </div>
+ </div>
+ </>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertManagerAccessPage/route.tsx b/frontend/src/pages/cert-manager/CertManagerAccessPage/route.tsx
new file mode 100644
index 0000000000..65a01dcfd5
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertManagerAccessPage/route.tsx
@@ -0,0 +1,20 @@
+import { createFileRoute, stripSearchParams } from "@tanstack/react-router";
+import { zodValidator } from "@tanstack/zod-adapter";
+import { z } from "zod";
+
+import { CertManagerAccessPage } from "./CertManagerAccessPage";
+
+const SearchSchema = z.object({
+ selectedTab: z.enum(["users", "groups", "identities"]).optional()
+});
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/cert-manager-access"
+)({
+ component: CertManagerAccessPage,
+ validateSearch: zodValidator(SearchSchema),
+ search: { middlewares: [stripSearchParams({ selectedTab: "users" })] },
+ beforeLoad: ({ context }) => ({
+ breadcrumbs: [...context.breadcrumbs, { label: "Admins" }]
+ })
+});
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsCaInstallForm.tsx
index c1e965f5a8..2748044bac 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsCaInstallForm.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/AdcsCaInstallForm.tsx
@@ -76,7 +76,7 @@ export const AdcsCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
const { data: existingSigningConfig } = useGetCaSigningConfig(caId, { enabled: !!caId });
const { mutateAsync: createSigningConfig } = useCreateCaSigningConfig();
const { mutateAsync: updateSigningConfig } = useUpdateCaSigningConfig();
- const { mutateAsync: installAdcsCert } = useInstallCaCertificateAdcs(currentProject.id);
+ const { mutateAsync: installAdcsCert } = useInstallCaCertificateAdcs();
const onFormSubmit = async ({
appConnectionId,
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/ExternalCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/ExternalCaInstallForm.tsx
index 8a7e9690ec..d08ee2b549 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/ExternalCaInstallForm.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/ExternalCaInstallForm.tsx
@@ -8,7 +8,6 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, IconButton, TextArea, Tooltip } from "@app/components/v2";
-import { useProject } from "@app/context";
import { useTimedReset } from "@app/hooks";
import { useGetCaCsr, useImportCaCertificate } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -26,7 +25,6 @@ type Props = {
};
export const ExternalCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
- const { currentProject } = useProject();
const [copyTextCaCsr, isCopyingCaCsr, setCopyTextCaCsr] = useTimedReset<string>({
initialState: "Copy to clipboard"
});
@@ -41,18 +39,17 @@ export const ExternalCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
});
const { data: csr } = useGetCaCsr(caId);
- const { mutateAsync: importCaCertificate } = useImportCaCertificate(currentProject.id);
+ const { mutateAsync: importCaCertificate } = useImportCaCertificate();
useEffect(() => {
reset();
}, []);
const onFormSubmit = async ({ certificate, certificateChain }: FormData) => {
- if (!csr || !caId || !currentProject?.slug) return;
+ if (!csr || !caId) return;
await importCaCertificate({
caId,
- projectSlug: currentProject?.slug,
certificate,
certificateChain
});
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/VenafiCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/VenafiCaInstallForm.tsx
index 27714054a0..97b575653c 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/VenafiCaInstallForm.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/VenafiCaInstallForm.tsx
@@ -93,7 +93,7 @@ export const VenafiCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
const { data: existingSigningConfig } = useGetCaSigningConfig(caId, { enabled: !!caId });
const { mutateAsync: createSigningConfig } = useCreateCaSigningConfig();
const { mutateAsync: updateSigningConfig } = useUpdateCaSigningConfig();
- const { mutateAsync: installVenafiCert } = useInstallCaCertificateVenafi(currentProject.id);
+ const { mutateAsync: installVenafiCert } = useInstallCaCertificateVenafi();
const onFormSubmit = async ({
appConnectionId,
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaModal.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaModal.tsx
index 40a30647ea..08c989d124 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaModal.tsx
@@ -224,7 +224,6 @@ export const CaModal = ({ popUp, handlePopUpToggle }: Props) => {
} else {
// create
await createMutateAsync({
- projectId: currentProject.id,
name,
type,
status,
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx
index 4b5e38bdf8..660aadd836 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx
@@ -34,7 +34,7 @@ export const CaSection = () => {
const onRemoveCaSubmit = async (id: string) => {
if (!currentProject?.slug) return;
- await deleteCa({ id, projectId: currentProject.id, type: CaType.INTERNAL });
+ await deleteCa({ id, type: CaType.INTERNAL });
createNotification({
text: "Successfully deleted CA",
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaTable.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaTable.tsx
index 41634e128f..52e3d4a40c 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaTable.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaTable.tsx
@@ -56,7 +56,7 @@ export const CaTable = ({ handlePopUpOpen }: Props) => {
const { currentOrg } = useOrganization();
const { currentProject } = useProject();
const { permission } = useProjectPermission();
- const { data, isPending } = useListCasByTypeAndProjectId(CaType.INTERNAL, currentProject.id);
+ const { data, isPending } = useListCasByTypeAndProjectId(CaType.INTERNAL);
const cas = data as TInternalCertificateAuthority[];
return (
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx
index e41826288e..bfe1fd5f97 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx
@@ -639,7 +639,6 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
if (ca) {
await updateMutateAsync({
id: ca.id,
- projectId: currentProject.id,
name,
type,
status,
@@ -647,7 +646,6 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
});
} else {
await createMutateAsync({
- projectId: currentProject.id,
name,
type,
status,
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx
index ca9e695ba2..e1a50de5ec 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx
@@ -30,7 +30,7 @@ export const ExternalCaSection = () => {
const onRemoveCaSubmit = async (id: string, type: CaType) => {
if (!currentProject?.id) return;
- await deleteCa({ id, type, projectId: currentProject.id });
+ await deleteCa({ id, type });
createNotification({
text: "Successfully deleted CA",
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaTable.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaTable.tsx
index 5ace299114..5438d289d6 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaTable.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaTable.tsx
@@ -30,7 +30,6 @@ import { Badge } from "@app/components/v3";
import {
ProjectPermissionCertificateAuthorityActions,
ProjectPermissionSub,
- useProject,
useProjectPermission
} from "@app/context";
import { CaStatus, CaType, useListExternalCasByProjectId } from "@app/hooks/api";
@@ -54,9 +53,8 @@ type Props = {
};
export const ExternalCaTable = ({ handlePopUpOpen }: Props) => {
- const { currentProject } = useProject();
const { permission } = useProjectPermission();
- const { data, isPending } = useListExternalCasByProjectId(currentProject.id);
+ const { data, isPending } = useListExternalCasByProjectId();
return (
<div>
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/index.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/index.tsx
index 1f23813bce..8776e00fba 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/index.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/index.tsx
@@ -1 +1,2 @@
export { CaSection } from "./CaSection";
+export { ExternalCaSection } from "./ExternalCaSection";
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
index e6b12e58ef..3dd93827ce 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/CertificateDetailsByIDPage.tsx
@@ -73,7 +73,7 @@ const Page = () => {
const { mutateAsync: deleteCert } = useDeleteCert();
const { mutateAsync: downloadCertPkcs12 } = useDownloadCertPkcs12();
const { mutateAsync: updateRenewalConfig } = useUpdateRenewalConfig();
- const { data: caData } = useListCasByProjectId(currentProject?.id ?? "");
+ const { data: caData } = useListCasByProjectId();
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
"deleteCertificate",
@@ -93,8 +93,7 @@ const Page = () => {
if (!currentProject?.id || !certificate) return;
await deleteCert({
- id: certificate.id,
- projectId: currentProject.id
+ id: certificate.id
});
createNotification({
@@ -104,7 +103,7 @@ const Page = () => {
handlePopUpClose("deleteCertificate");
navigate({
- to: "/organizations/$orgId/projects/cert-manager/$projectId/policies",
+ to: "/organizations/$orgId/projects/cert-manager/$projectId/inventory",
params: {
orgId: currentOrg.id,
projectId
@@ -139,7 +138,6 @@ const Page = () => {
try {
await downloadCertPkcs12({
certificateId: certId,
- projectSlug: currentProject.slug,
password: options.pkcs12.password,
alias: options.pkcs12.alias
});
@@ -175,11 +173,10 @@ const Page = () => {
!caType || caSupportsCapability(caType, CaCapability.REVOKE_CERTIFICATES);
const handleDisableAutoRenewal = async () => {
- if (!currentProject?.slug || !certificate) return;
+ if (!certificate) return;
await updateRenewalConfig({
certificateId: certificate.id,
- projectSlug: currentProject.slug,
enableAutoRenewal: false
});
@@ -206,7 +203,7 @@ const Page = () => {
isAllowed ? (
<div className="mx-auto mb-6 w-full max-w-8xl">
<Link
- to="/organizations/$orgId/projects/cert-manager/$projectId/policies"
+ to="/organizations/$orgId/projects/cert-manager/$projectId/inventory"
params={{
orgId: currentOrg.id,
projectId
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateMetadataSection.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateMetadataSection.tsx
index 3233481dc3..8de67786b1 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateMetadataSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/components/CertificateMetadataSection.tsx
@@ -76,7 +76,6 @@ export const CertificateMetadataSection = ({ certificateId }: Props) => {
try {
await updateMetadata({
certificateId,
- projectId: currentProject.id,
metadata: formData.metadata || []
});
createNotification({
diff --git a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/route.tsx b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/route.tsx
index 9026238e2f..7075d709d3 100644
--- a/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/route.tsx
+++ b/frontend/src/pages/cert-manager/CertificateDetailsByIDPage/route.tsx
@@ -13,7 +13,7 @@ export const Route = createFileRoute(
{
label: "Certificates",
link: linkOptions({
- to: "/organizations/$orgId/projects/cert-manager/$projectId/policies",
+ to: "/organizations/$orgId/projects/cert-manager/$projectId/inventory",
params: {
orgId: params.orgId,
projectId: params.projectId
diff --git a/frontend/src/pages/cert-manager/CertificateRequestsPage/components/CertificateRequestsSection.tsx b/frontend/src/pages/cert-manager/CertificateRequestsPage/components/CertificateRequestsSection.tsx
index 7cab36eac8..84aa73d3c0 100644
--- a/frontend/src/pages/cert-manager/CertificateRequestsPage/components/CertificateRequestsSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateRequestsPage/components/CertificateRequestsSection.tsx
@@ -24,11 +24,7 @@ import {
THead,
Tr
} from "@app/components/v2";
-import {
- ProjectPermissionCertificateProfileActions,
- ProjectPermissionSub,
- useProject
-} from "@app/context";
+import { ProjectPermissionCertificateProfileActions, ProjectPermissionSub } from "@app/context";
import { useDebounce, usePopUp } from "@app/hooks";
import { useListCertificateProfiles } from "@app/hooks/api/certificateProfiles";
import {
@@ -57,8 +53,6 @@ type Props = {
};
export const CertificateRequestsSection = ({ onViewCertificateFromRequest }: Props) => {
- const { currentProject } = useProject();
-
const [pendingSearch, setPendingSearch] = useState("");
const [pendingProfileIds, setPendingProfileIds] = useState<string[]>([]);
const [pendingFilters, setPendingFilters] = useState<CertificateRequestFilters>({});
@@ -80,7 +74,6 @@ export const CertificateRequestsSection = ({ onViewCertificateFromRequest }: Pro
}, [debouncedSearch]);
const { data: profilesData } = useListCertificateProfiles({
- projectId: currentProject?.id ?? "",
limit: 100
});
@@ -97,7 +90,6 @@ export const CertificateRequestsSection = ({ onViewCertificateFromRequest }: Pro
const queryParams: TListCertificateRequestsParams = useMemo(
() => ({
- projectSlug: currentProject?.slug || "",
offset: (currentPage - 1) * perPage,
limit: perPage,
sortBy: "createdAt",
@@ -108,7 +100,6 @@ export const CertificateRequestsSection = ({ onViewCertificateFromRequest }: Pro
...(activeMetadataFilters && { metadataFilter: activeMetadataFilters })
}),
[
- currentProject?.slug,
currentPage,
perPage,
debouncedSearch,
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
index d0434b79ad..51061957cc 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
@@ -71,11 +71,7 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle }: Props) => {
chainPem,
collectionId
}: FormData) => {
- if (!currentProject?.slug) return;
-
const { serialNumber, certificate, certificateChain, privateKey } = await importCertificate({
- projectSlug: currentProject.slug,
-
certificatePem,
privateKeyPem,
chainPem,
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
index 8b95de648f..22c32d6c7a 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx
@@ -147,7 +147,6 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
const { data: cert } = useGetCert(sanitizedSerialNumber);
const { data: profilesData } = useListCertificateProfiles({
- projectId: currentProject?.id || "",
enrollmentType: EnrollmentType.API,
includeConfigs: true
});
@@ -313,8 +312,6 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
const metadataEntries = formData.metadata?.filter((m) => m.key);
const response = await issueCertificate({
profileId: formProfileId,
- projectSlug: currentProject.slug,
- projectId: currentProject.id,
csr: formData.csr,
attributes: { ttl },
...(metadataEntries?.length && { metadata: metadataEntries })
@@ -338,8 +335,6 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId }
const managedMetadataEntries = formMetadata?.filter((m) => m.key);
const request: any = {
profileId: formProfileId,
- projectSlug: currentProject.slug,
- projectId: currentProject.id,
attributes: {
ttl,
signatureAlgorithm: signatureAlgorithm || "",
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManageRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManageRenewalModal.tsx
index 96eb2654a2..b042fde45a 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManageRenewalModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManageRenewalModal.tsx
@@ -173,8 +173,7 @@ export const CertificateManageRenewalModal = ({ popUp, handlePopUpToggle }: Prop
await updateRenewalConfig({
certificateId: certificateData.certificateId,
- renewBeforeDays: data.renewBeforeDays,
- projectSlug: currentProject.slug
+ renewBeforeDays: data.renewBeforeDays
});
createNotification({
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateModal.tsx
index 42db2911c3..7aea634c52 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateModal.tsx
@@ -189,12 +189,11 @@ export const CertificateModal = ({ popUp, handlePopUpToggle, preselectedTemplate
keyUsages,
extendedKeyUsages
}: FormData) => {
- if (!currentProject?.slug) return;
+ if (!currentProject?.id) return;
const { serialNumber, certificate, certificateChain, privateKey } = await createCertificate({
caId: !selectedCertTemplate ? caId : undefined,
certificateTemplateId: selectedCertTemplate ? selectedCertTemplateId : undefined,
- projectSlug: currentProject.slug,
pkiCollectionId: collectionId,
commonName,
subjectAltNames,
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalConfigModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalConfigModal.tsx
index 0391518665..46e06bcdb7 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalConfigModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalConfigModal.tsx
@@ -71,8 +71,7 @@ export const CertificateRenewalConfigModal = ({ popUp, handlePopUpToggle }: Prop
await updateRenewalConfig({
certificateId: certificateData.certificateId,
- renewBeforeDays: data.renewBeforeDays,
- projectSlug: currentProject.slug
+ renewBeforeDays: data.renewBeforeDays
});
createNotification({
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalDisableModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalDisableModal.tsx
index e44d7e774e..e4089f092f 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalDisableModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalDisableModal.tsx
@@ -29,7 +29,6 @@ export const CertificateRenewalDisableModal = ({ popUp, handlePopUpToggle }: Pro
await updateRenewalConfig({
certificateId: certificateData.certificateId,
- projectSlug: currentProject.slug,
enableAutoRenewal: false
});
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRevocationModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRevocationModal.tsx
index 34b8a80cc8..cad32e26ab 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRevocationModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRevocationModal.tsx
@@ -53,7 +53,6 @@ export const CertificateRevocationModal = ({ popUp, handlePopUpToggle }: Props)
const { certificateId } = popUp.revokeCertificate.data as { certificateId: string };
await revokeCertificate({
- projectId: currentProject.id,
id: certificateId,
revocationReason
});
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx
index c781e8b80c..0784f1a203 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx
@@ -64,8 +64,7 @@ export const CertificatesSection = ({
if (!currentProject?.slug) return;
await deleteCert({
- id,
- projectId: currentProject.id
+ id
});
createNotification({
@@ -103,7 +102,6 @@ export const CertificatesSection = ({
try {
await downloadCertPkcs12({
certificateId,
- projectSlug: currentProject.slug,
password: options.pkcs12.password,
alias: options.pkcs12.alias
});
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
index 6d9382fc92..7024a07351 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
@@ -250,12 +250,11 @@ export const CertificatesTable = ({
);
const { data: profilesData } = useListCertificateProfiles({
- projectId: currentProject?.id ?? "",
limit: 100
});
- const { data: caData } = useListCasByProjectId(currentProject?.id ?? "");
- const { data: viewsData } = useListCertificateInventoryViews(currentProject?.id ?? "");
+ const { data: caData } = useListCasByProjectId();
+ const { data: viewsData } = useListCertificateInventoryViews();
const { mutateAsync: deleteView } = useDeleteCertificateInventoryView();
const { mutateAsync: updateView } = useUpdateCertificateInventoryView();
const { mutateAsync: updateRenewalConfig } = useUpdateRenewalConfig();
@@ -341,7 +340,6 @@ export const CertificatesTable = ({
try {
await updateRenewalConfig({
certificateId,
- projectSlug: currentProject.slug,
enableAutoRenewal: false
});
createNotification({
@@ -556,7 +554,7 @@ export const CertificatesTable = ({
const handleDeleteView = async (viewId: string) => {
if (!currentProject?.id) return;
try {
- await deleteView({ projectId: currentProject.id, viewId });
+ await deleteView({ viewId });
createNotification({ text: "View deleted", type: "success" });
if (activeViewId === viewId) {
handleClearAllFilters();
@@ -569,7 +567,7 @@ export const CertificatesTable = ({
const handleToggleShare = async (viewId: string, isShared: boolean) => {
if (!currentProject?.id) return;
try {
- await updateView({ projectId: currentProject.id, viewId, isShared });
+ await updateView({ viewId, isShared });
createNotification({
text: isShared ? "View shared with team" : "View made personal",
type: "success"
@@ -1304,7 +1302,6 @@ export const CertificatesTable = ({
<SaveViewModal
isOpen={isSaveViewOpen}
onOpenChange={setIsSaveViewOpen}
- projectId={currentProject?.id ?? ""}
filters={pendingFilters.length > 0 ? pendingFilters : appliedFilters}
onViewCreated={(viewId, viewFilters) => {
handleSelectView(viewId, viewFilters);
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/SaveViewModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/SaveViewModal.tsx
index 361a346d9f..61db8ebee5 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/SaveViewModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/SaveViewModal.tsx
@@ -20,18 +20,11 @@ import { type FilterRule, filtersToSearchParams } from "./inventory-types";
type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
- projectId: string;
filters: FilterRule[];
onViewCreated?: (viewId: string, filters: TInventoryViewFilters) => void;
};
-export const SaveViewModal = ({
- isOpen,
- onOpenChange,
- projectId,
- filters,
- onViewCreated
-}: Props) => {
+export const SaveViewModal = ({ isOpen, onOpenChange, filters, onViewCreated }: Props) => {
const [name, setName] = useState("");
const [isShared, setIsShared] = useState(false);
const { mutateAsync: createView, isPending } = useCreateCertificateInventoryView();
@@ -41,7 +34,6 @@ export const SaveViewModal = ({
const apiFilters = filtersToSearchParams(filters);
const result = await createView({
- projectId,
name: name.trim(),
filters: apiFilters,
isShared
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/CodeSigningPage.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/CodeSigningPage.tsx
index c9b0159f92..0cc023b2d8 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/CodeSigningPage.tsx
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/CodeSigningPage.tsx
@@ -1,26 +1,30 @@
import { useState } from "react";
import { Helmet } from "react-helmet";
import { useTranslation } from "react-i18next";
-import { useSearch } from "@tanstack/react-router";
+import { useNavigate, useSearch } from "@tanstack/react-router";
-import { PageHeader } from "@app/components/v2";
+import { PageHeader, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
import { useProject } from "@app/context";
import { ProjectType } from "@app/hooks/api/projects/types";
import { CodeSigningGrantsTab } from "../ApprovalsPage/components/CodeSigningGrantsTab";
import { CodeSigningPolicyTab } from "../ApprovalsPage/components/CodeSigningPolicyTab";
-import { CodeSigningRequestsTab } from "../ApprovalsPage/components/CodeSigningRequestsTab";
import { CreateSignerModal } from "./components/CreateSignerModal";
import { SignersTable } from "./components/SignersTable";
+const TABS = ["signers", "signing-policies", "grants"] as const;
+
export const CodeSigningPage = () => {
const { t } = useTranslation();
const { currentProject } = useProject();
+ const navigate = useNavigate();
const { selectedTab } = useSearch({
from: "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/code-signing/"
});
- const activeTab = selectedTab || "signers";
+ const activeTab: (typeof TABS)[number] = TABS.includes(selectedTab as (typeof TABS)[number])
+ ? (selectedTab as (typeof TABS)[number])
+ : "signers";
const [isCreateOpen, setIsCreateOpen] = useState(false);
return (
@@ -34,17 +38,40 @@ export const CodeSigningPage = () => {
title="Code Signing"
description="Manage signers and control who can sign artifacts."
/>
- <div>
- {activeTab === "signers" && (
+ <Tabs
+ value={activeTab}
+ onValueChange={(v) =>
+ navigate({
+ to: "/organizations/$orgId/projects/cert-manager/$projectId/code-signing",
+ params: { orgId: currentProject.orgId, projectId: currentProject.id },
+ search: { selectedTab: v } as never
+ } as never)
+ }
+ >
+ <TabList>
+ <Tab variant="project" value="signers">
+ Signers
+ </Tab>
+ <Tab variant="project" value="grants">
+ Grants
+ </Tab>
+ <Tab variant="project" value="signing-policies">
+ Signer Policies
+ </Tab>
+ </TabList>
+ <TabPanel value="signers">
<SignersTable
projectId={currentProject.id}
onCreateSigner={() => setIsCreateOpen(true)}
/>
- )}
- {activeTab === "signing-requests" && <CodeSigningRequestsTab />}
- {activeTab === "signing-policies" && <CodeSigningPolicyTab />}
- {activeTab === "grants" && <CodeSigningGrantsTab />}
- </div>
+ </TabPanel>
+ <TabPanel value="grants">
+ <CodeSigningGrantsTab />
+ </TabPanel>
+ <TabPanel value="signing-policies">
+ <CodeSigningPolicyTab />
+ </TabPanel>
+ </Tabs>
</div>
<CreateSignerModal
isOpen={isCreateOpen}
diff --git a/frontend/src/pages/cert-manager/DashboardPage/DashboardPage.tsx b/frontend/src/pages/cert-manager/DashboardPage/DashboardPage.tsx
index 90b3c3abb5..190f7b3a5e 100644
--- a/frontend/src/pages/cert-manager/DashboardPage/DashboardPage.tsx
+++ b/frontend/src/pages/cert-manager/DashboardPage/DashboardPage.tsx
@@ -17,6 +17,7 @@ import {
useGetCertPqcTrend
} from "@app/hooks/api/certificates";
import { ProjectType } from "@app/hooks/api/projects/types";
+import { CertManagerAdminOnly } from "@app/pages/cert-manager/components/CertManagerAdminOnly";
import {
ActivityTrend,
@@ -43,13 +44,13 @@ export const DashboardPage = () => {
const navigateToInventory = useCallback(
(filters: Record<string, string | undefined>) => {
navigate({
- to: "/organizations/$orgId/projects/cert-manager/$projectId/policies",
+ to: "/organizations/$orgId/projects/cert-manager/$projectId/inventory",
params: {
orgId: currentProject?.orgId || "",
projectId: currentProject?.id || ""
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- search: { selectedTab: "certificates", ...filters } as any
+ search: filters as any
});
},
[navigate, currentProject]
@@ -69,48 +70,50 @@ export const DashboardPage = () => {
title="Certificate Dashboard"
description="At-a-glance view of your certificate estate."
/>
- <ProjectPermissionCan
- renderGuardBanner
- I={ProjectPermissionCertificateActions.Read}
- a={ProjectPermissionSub.Certificates}
- >
- {isStatsLoading || !stats ? (
- <PageLoader />
- ) : (
- <div className="flex flex-col gap-6">
- <KpiCards stats={stats} onNavigate={navigateToInventory} />
- <div className="flex flex-wrap gap-4">
- <DistributionCharts stats={stats} onNavigate={navigateToInventory} />
- <ExpirationTimeline
- buckets={stats.expirationBuckets}
- onNavigate={navigateToInventory}
+ <CertManagerAdminOnly>
+ <ProjectPermissionCan
+ renderGuardBanner
+ I={ProjectPermissionCertificateActions.Read}
+ a={ProjectPermissionSub.Certificates}
+ >
+ {isStatsLoading || !stats ? (
+ <PageLoader />
+ ) : (
+ <div className="flex flex-col gap-6">
+ <KpiCards stats={stats} onNavigate={navigateToInventory} />
+ <div className="flex flex-wrap gap-4">
+ <DistributionCharts stats={stats} onNavigate={navigateToInventory} />
+ <ExpirationTimeline
+ buckets={stats.expirationBuckets}
+ onNavigate={navigateToInventory}
+ />
+ </div>
+ <CodeSigningSection projectId={currentProject.id} />
+ <ActivityTrend
+ data={trendData?.periods || []}
+ currentRange={trendRange}
+ onRangeChange={setTrendRange}
/>
- </div>
- <CodeSigningSection projectId={currentProject.id} />
- <ActivityTrend
- data={trendData?.periods || []}
- currentRange={trendRange}
- onRangeChange={setTrendRange}
- />
- <ValidityReadinessSection stats={stats} />
- {stats.totals.total > 0 && (
- <div className="flex flex-col gap-4">
- <h2 className="text-lg font-semibold text-foreground">
- Post-Quantum Readiness
- </h2>
- <div className="flex flex-wrap gap-4">
- <PqcReadinessChart stats={stats} onNavigate={navigateToInventory} />
- <PqcTrend
- data={pqcTrendData?.periods || []}
- currentRange={pqcTrendRange}
- onRangeChange={setPqcTrendRange}
- />
+ <ValidityReadinessSection stats={stats} />
+ {stats.totals.total > 0 && (
+ <div className="flex flex-col gap-4">
+ <h2 className="text-lg font-semibold text-foreground">
+ Post-Quantum Readiness
+ </h2>
+ <div className="flex flex-wrap gap-4">
+ <PqcReadinessChart stats={stats} onNavigate={navigateToInventory} />
+ <PqcTrend
+ data={pqcTrendData?.periods || []}
+ currentRange={pqcTrendRange}
+ onRangeChange={setPqcTrendRange}
+ />
+ </div>
</div>
- </div>
- )}
- </div>
- )}
- </ProjectPermissionCan>
+ )}
+ </div>
+ )}
+ </ProjectPermissionCan>
+ </CertManagerAdminOnly>
</div>
</div>
</div>
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/DiscoveryPage.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/DiscoveryPage.tsx
index 196a01b163..f603aa00e2 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/DiscoveryPage.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/DiscoveryPage.tsx
@@ -12,6 +12,7 @@ import {
useProject
} from "@app/context";
import { ProjectType } from "@app/hooks/api/projects/types";
+import { CertManagerAdminOnly } from "@app/pages/cert-manager/components/CertManagerAdminOnly";
import { DiscoveryJobsTab, InstallationsTab } from "./components";
@@ -42,7 +43,7 @@ export const DiscoveryPage = () => {
}
description="Discover and track SSL/TLS certificates across your infrastructure."
/>
- <div>
+ <CertManagerAdminOnly>
{activeTab === "jobs" && (
<ProjectPermissionCan
renderGuardBanner
@@ -61,7 +62,7 @@ export const DiscoveryPage = () => {
<InstallationsTab projectId={currentProject?.id || ""} />
</ProjectPermissionCan>
)}
- </div>
+ </CertManagerAdminOnly>
</div>
</div>
);
diff --git a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncRow.tsx b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncRow.tsx
index 7d424c1bc8..28ab1bd74d 100644
--- a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncRow.tsx
+++ b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncRow.tsx
@@ -54,6 +54,7 @@ type Props = {
onTriggerImportCertificates: (pkiSync: TPkiSync) => void;
onTriggerRemoveCertificates: (pkiSync: TPkiSync) => void;
onToggleEnable: (pkiSync: TPkiSync) => void;
+ applicationName?: string;
};
export const PkiSyncRow = ({
@@ -62,7 +63,8 @@ export const PkiSyncRow = ({
onTriggerSyncCertificates,
onTriggerImportCertificates,
onTriggerRemoveCertificates,
- onToggleEnable
+ onToggleEnable,
+ applicationName
}: Props) => {
const navigate = useNavigate();
const {
@@ -74,7 +76,8 @@ export const PkiSyncRow = ({
description,
syncStatus,
isAutoSyncEnabled,
- projectId
+ projectId,
+ applicationId
} = pkiSync;
const destinationName = PKI_SYNC_MAP[destination].name;
@@ -136,7 +139,8 @@ export const PkiSyncRow = ({
syncId: id,
projectId,
orgId: currentOrg.id
- }
+ },
+ search: applicationName ? { applicationName } : undefined
});
}}
className={twMerge(
@@ -166,6 +170,11 @@ export const PkiSyncRow = ({
/>
</Tooltip>
)}
+ {!applicationId && (
+ <span className="ml-2 rounded bg-mineshaft-600 px-2 py-0.5 text-[10px] tracking-wide text-mineshaft-200 uppercase">
+ Legacy
+ </span>
+ )}
</div>
<p className="truncate text-xs leading-4 text-bunker-300">
{destinationDetails.name}
diff --git a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncsTable.tsx b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncsTable.tsx
index 68e7cf294c..7a13c507e5 100644
--- a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncsTable.tsx
+++ b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncsTable.tsx
@@ -82,6 +82,7 @@ const getSyncStatusOrderValue = (syncStatus: PkiSyncStatus | null) => {
type Props = {
pkiSyncs: TPkiSync[];
+ applicationName?: string;
};
const STATUS_ICON_MAP = {
@@ -91,7 +92,7 @@ const STATUS_ICON_MAP = {
[PkiSyncStatus.Running]: { icon: faRotate, className: "text-yellow", name: "Syncing" }
};
-export const PkiSyncsTable = ({ pkiSyncs }: Props) => {
+export const PkiSyncsTable = ({ pkiSyncs, applicationName }: Props) => {
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
"deleteSync",
"importCertificates",
@@ -399,6 +400,7 @@ export const PkiSyncsTable = ({ pkiSyncs }: Props) => {
onTriggerImportCertificates={handleTriggerImportCertificates}
onTriggerRemoveCertificates={handleTriggerRemoveCertificates}
onToggleEnable={handleToggleEnableSync}
+ applicationName={applicationName}
/>
))}
</TBody>
diff --git a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncsTab.tsx b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncsTab.tsx
index 677a2b2a50..cd6cb3fc83 100644
--- a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncsTab.tsx
+++ b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncsTab.tsx
@@ -1,15 +1,11 @@
import { useCallback, useEffect, useMemo } from "react";
-import { faPlus } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNavigate, useSearch } from "@tanstack/react-router";
-import { ProjectPermissionCan } from "@app/components/permissions";
import { CreatePkiSyncModal } from "@app/components/pki-syncs";
-import { Button, Spinner } from "@app/components/v2";
+import { Spinner } from "@app/components/v2";
import { DocumentationLinkBadge } from "@app/components/v3";
import { ROUTE_PATHS } from "@app/const/routes";
-import { ProjectPermissionSub, useOrganization, useProject } from "@app/context";
-import { ProjectPermissionPkiSyncActions } from "@app/context/ProjectPermissionContext/types";
+import { useOrganization, useProject } from "@app/context";
import { usePopUp } from "@app/hooks";
import { useListPkiSyncs } from "@app/hooks/api/pkiSyncs";
import { IntegrationsListPageTabs } from "@app/types/integrations";
@@ -110,25 +106,10 @@ export const PkiSyncsTab = () => {
</div>
</div>
<p className="text-sm text-bunker-300">
- Use App Connections to sync certificates to third-party services.
+ Existing project-level syncs remain editable. Create new syncs inside a Cert Manager
+ Application.
</p>
</div>
- <ProjectPermissionCan
- I={ProjectPermissionPkiSyncActions.Create}
- a={ProjectPermissionSub.PkiSyncs}
- >
- {(isAllowed) => (
- <Button
- colorSchema="secondary"
- type="button"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={() => handlePopUpOpen("addSync")}
- isDisabled={!isAllowed}
- >
- Add Sync
- </Button>
- )}
- </ProjectPermissionCan>
</div>
<PkiSyncsTable pkiSyncs={pkiSyncs} />
</div>
diff --git a/frontend/src/pages/cert-manager/IntegrationsListPage/route.tsx b/frontend/src/pages/cert-manager/IntegrationsListPage/route.tsx
index 0fba9b6b4a..0d8cec2e67 100644
--- a/frontend/src/pages/cert-manager/IntegrationsListPage/route.tsx
+++ b/frontend/src/pages/cert-manager/IntegrationsListPage/route.tsx
@@ -11,7 +11,8 @@ const IntegrationsListPageQuerySchema = z.object({
selectedTab: z.nativeEnum(IntegrationsListPageTabs).optional(),
addSync: z.nativeEnum(PkiSync).optional(),
connectionId: z.string().optional(),
- connectionName: z.string().optional()
+ connectionName: z.string().optional(),
+ legacy: z.enum(["true"]).optional()
});
export const Route = createFileRoute(
diff --git a/frontend/src/pages/cert-manager/InventoryPage/InventoryPage.tsx b/frontend/src/pages/cert-manager/InventoryPage/InventoryPage.tsx
new file mode 100644
index 0000000000..5d024c30c8
--- /dev/null
+++ b/frontend/src/pages/cert-manager/InventoryPage/InventoryPage.tsx
@@ -0,0 +1,120 @@
+import { useMemo } from "react";
+import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
+import { useSearch } from "@tanstack/react-router";
+
+import { PermissionDeniedBanner } from "@app/components/permissions";
+import { PageHeader } from "@app/components/v2";
+import { PageLoader } from "@app/components/v3";
+import { useProject, useProjectPermission } from "@app/context";
+import {
+ ProjectPermissionCertificateActions,
+ ProjectPermissionSub
+} from "@app/context/ProjectPermissionContext/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import { CertManagerAdminOnly } from "@app/pages/cert-manager/components/CertManagerAdminOnly";
+
+import type { FilterRule } from "../CertificatesPage/components/inventory-types";
+import { CertificatesTab } from "../PoliciesPage/components/CertificatesTab";
+
+export const InventoryPage = () => {
+ const { t } = useTranslation();
+ const { currentProject } = useProject();
+ const { permission } = useProjectPermission();
+ const searchParams = useSearch({
+ from: "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/inventory"
+ });
+
+ const dashboardFilters = useMemo<FilterRule[]>(() => {
+ const filters: FilterRule[] = [];
+ if (searchParams.filterStatus) {
+ filters.push({
+ id: "dash-status",
+ field: "status",
+ operator: "in",
+ value: [searchParams.filterStatus]
+ });
+ }
+ if (searchParams.filterEnrollmentType) {
+ filters.push({
+ id: "dash-enrollment",
+ field: "enrollmentType",
+ operator: "in",
+ value: [searchParams.filterEnrollmentType]
+ });
+ }
+ if (searchParams.filterKeyAlgorithm) {
+ filters.push({
+ id: "dash-algorithm",
+ field: "keyAlgorithm",
+ operator: "is",
+ value: searchParams.filterKeyAlgorithm
+ });
+ }
+ if (searchParams.filterCaId) {
+ filters.push({
+ id: "dash-ca",
+ field: "caId",
+ operator: "in",
+ value: [searchParams.filterCaId]
+ });
+ }
+ if (searchParams.filterExpiresDays) {
+ const days = Number(searchParams.filterExpiresDays);
+ const futureDate = new Date();
+ futureDate.setDate(futureDate.getDate() + days);
+ filters.push({
+ id: "dash-expires",
+ field: "notAfter",
+ operator: "before",
+ value: futureDate.toISOString().split("T")[0]
+ });
+ }
+ if (searchParams.filterExpiresAfterDays) {
+ const days = Number(searchParams.filterExpiresAfterDays);
+ const afterDate = new Date();
+ afterDate.setDate(afterDate.getDate() + days);
+ filters.push({
+ id: "dash-expires-after",
+ field: "notAfter",
+ operator: "after",
+ value: afterDate.toISOString().split("T")[0]
+ });
+ }
+ return filters;
+ }, [searchParams]);
+
+ const canReadCertificates = permission.can(
+ ProjectPermissionCertificateActions.Read,
+ ProjectPermissionSub.Certificates
+ );
+
+ if (!currentProject) {
+ return <PageLoader />;
+ }
+
+ return (
+ <div className="mx-auto flex h-full flex-col justify-between bg-bunker-800 text-white">
+ <Helmet>
+ <title>{t("common.head-title", { title: "Inventory" })}</title>
+ </Helmet>
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <PageHeader
+ scope={ProjectType.CertificateManager}
+ title="Inventory"
+ description="All certificates across this Certificate Manager instance — filter, view, and inspect."
+ />
+ <CertManagerAdminOnly>
+ {canReadCertificates ? (
+ <CertificatesTab
+ dashboardFilters={dashboardFilters}
+ dashboardViewId={searchParams.viewId}
+ />
+ ) : (
+ <PermissionDeniedBanner />
+ )}
+ </CertManagerAdminOnly>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/InventoryPage/route.tsx b/frontend/src/pages/cert-manager/InventoryPage/route.tsx
new file mode 100644
index 0000000000..c7e2d2c200
--- /dev/null
+++ b/frontend/src/pages/cert-manager/InventoryPage/route.tsx
@@ -0,0 +1,25 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { zodValidator } from "@tanstack/zod-adapter";
+import { z } from "zod";
+
+import { InventoryPage } from "./InventoryPage";
+
+const inventoryPageSearchSchema = z.object({
+ filterStatus: z.string().optional(),
+ filterEnrollmentType: z.string().optional(),
+ filterKeyAlgorithm: z.string().optional(),
+ filterCaId: z.string().optional(),
+ filterExpiresDays: z.string().optional(),
+ filterExpiresAfterDays: z.string().optional(),
+ viewId: z.string().optional()
+});
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/inventory"
+)({
+ component: InventoryPage,
+ validateSearch: zodValidator(inventoryPageSearchSchema),
+ beforeLoad: ({ context }) => ({
+ breadcrumbs: [...context.breadcrumbs, { label: "Inventory" }]
+ })
+});
diff --git a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx
index 88e03a2f31..e0f311e42d 100644
--- a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx
@@ -54,7 +54,6 @@ export const PkiCollectionPage = () => {
if (!projectId) return;
await deletePkiCollection({
- projectId,
collectionId: collectionIdToDelete
});
diff --git a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/PkiSubscriberDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/PkiSubscriberDetailsByIDPage.tsx
index 779afb0a42..d93852d9fe 100644
--- a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/PkiSubscriberDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/PkiSubscriberDetailsByIDPage.tsx
@@ -41,8 +41,7 @@ const Page = () => {
select: (el) => el.subscriberName
});
const { data } = useGetPkiSubscriber({
- subscriberName,
- projectId
+ subscriberName
});
const { mutateAsync: deletePkiSubscriber } = useDeletePkiSubscriber();
@@ -55,7 +54,7 @@ const Page = () => {
const onRemoveSubscriberSubmit = async (subscriberNameToDelete: string) => {
if (!projectId) return;
- await deletePkiSubscriber({ subscriberName: subscriberNameToDelete, projectId });
+ await deletePkiSubscriber({ subscriberName: subscriberNameToDelete });
createNotification({
text: "Successfully deleted subscriber",
diff --git a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberCertificatesTable.tsx b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberCertificatesTable.tsx
index 8362229848..60a8065df9 100644
--- a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberCertificatesTable.tsx
+++ b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberCertificatesTable.tsx
@@ -27,7 +27,6 @@ import { Badge } from "@app/components/v3";
import {
ProjectPermissionPkiSubscriberActions,
ProjectPermissionSub,
- useProject,
useProjectPermission
} from "@app/context";
import { useGetPkiSubscriberCertificates } from "@app/hooks/api";
@@ -45,8 +44,6 @@ type Props = {
const PER_PAGE_INIT = 25;
export const PkiSubscriberCertificatesTable = ({ subscriberName, handlePopUpOpen }: Props) => {
- const { currentProject } = useProject();
- const projectId = currentProject.id;
const { permission } = useProjectPermission();
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(PER_PAGE_INIT);
@@ -54,7 +51,6 @@ export const PkiSubscriberCertificatesTable = ({ subscriberName, handlePopUpOpen
const { data, isPending } = useGetPkiSubscriberCertificates(
{
subscriberName,
- projectId,
offset: (page - 1) * perPage,
limit: perPage
},
@@ -64,7 +60,7 @@ export const PkiSubscriberCertificatesTable = ({ subscriberName, handlePopUpOpen
);
// Fetch CA data to determine capabilities
- const { data: caData } = useListCasByProjectId(currentProject.id);
+ const { data: caData } = useListCasByProjectId();
// Create mapping from caId to CA type for capability checking
const caCapabilityMap = useMemo(() => {
diff --git a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberDetailsSection.tsx b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberDetailsSection.tsx
index dd1dcbbc7d..d7b687fd95 100644
--- a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberDetailsSection.tsx
@@ -16,7 +16,6 @@ import {
import {
ProjectPermissionPkiSubscriberActions,
ProjectPermissionSub,
- useProject,
useProjectPermission
} from "@app/context";
import { useTimedReset } from "@app/hooks";
@@ -44,8 +43,6 @@ type TCertificateDetails = {
};
export const PkiSubscriberDetailsSection = ({ subscriberName, handlePopUpOpen }: Props) => {
- const { currentProject } = useProject();
- const projectId = currentProject.id;
const { permission } = useProjectPermission();
const [certificateDetails, setCertificateDetails] = useState<TCertificateDetails | null>(null);
const [isModalOpen, setIsModalOpen] = useState(false);
@@ -55,8 +52,7 @@ export const PkiSubscriberDetailsSection = ({ subscriberName, handlePopUpOpen }:
const { data: pkiSubscriber } = useGetPkiSubscriber(
{
- subscriberName,
- projectId
+ subscriberName
},
{
refetchInterval: 30_000
@@ -71,7 +67,7 @@ export const PkiSubscriberDetailsSection = ({ subscriberName, handlePopUpOpen }:
const onIssuePkiSubscriberCert = async () => {
if (pkiSubscriber?.supportsImmediateCertIssuance) {
- const response = await issuePkiSubscriberCert({ subscriberName, projectId });
+ const response = await issuePkiSubscriberCert({ subscriberName });
setCertificateDetails({
serialNumber: response.serialNumber,
@@ -87,7 +83,7 @@ export const PkiSubscriberDetailsSection = ({ subscriberName, handlePopUpOpen }:
type: "success"
});
} else {
- await orderPkiSubscriberCert({ subscriberName, projectId });
+ await orderPkiSubscriberCert({ subscriberName });
createNotification({
text: "Successfully ordered certificate. It will be issued after CA processing which could take a few minutes.",
diff --git a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx
index 054cbcc45b..6a4220b551 100644
--- a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx
+++ b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx
@@ -161,13 +161,11 @@ export const PkiSubscriberModal = ({ popUp, handlePopUpToggle }: Props) => {
const { currentProject } = useProject();
const projectId = currentProject.id;
const { data: subscribers } = useListWorkspacePkiSubscribers(projectId);
- const { data: cas } = useListCasByProjectId(projectId);
+ const { data: cas } = useListCasByProjectId();
const [tabValue, setTabValue] = useState<FormTab>(FormTab.Configuration);
const { data: pkiSubscriber } = useGetPkiSubscriber({
- subscriberName:
- (popUp?.pkiSubscriber?.data as { subscriberName: string })?.subscriberName || "",
- projectId
+ subscriberName: (popUp?.pkiSubscriber?.data as { subscriberName: string })?.subscriberName || ""
});
const { mutateAsync: createMutateAsync } = useCreatePkiSubscriber();
@@ -213,7 +211,6 @@ export const PkiSubscriberModal = ({ popUp, handlePopUpToggle }: Props) => {
// Fetch Azure ADCS templates when Azure CA is selected
const { data: azureTemplates } = useGetAzureAdcsTemplates({
caId: selectedCa?.type === CaType.AZURE_AD_CS ? selectedCaId : "",
- projectId,
isAzureAdcsCa: true
});
@@ -345,7 +342,6 @@ export const PkiSubscriberModal = ({ popUp, handlePopUpToggle }: Props) => {
if (pkiSubscriber) {
await updateMutateAsync({
subscriberName: pkiSubscriber.name,
- projectId,
name,
caId,
commonName,
@@ -365,7 +361,6 @@ export const PkiSubscriberModal = ({ popUp, handlePopUpToggle }: Props) => {
});
} else {
await createMutateAsync({
- projectId,
name,
caId,
commonName,
diff --git a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx
index ae09cde2eb..a71ead0b69 100644
--- a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx
@@ -18,7 +18,6 @@ import { PkiSubscribersTable } from "./PkiSubscribersTable";
export const PkiSubscriberSection = () => {
const { currentProject } = useProject();
- const projectId = currentProject.id;
// TODO: Use subscription.pkiLegacyTemplates to block legacy templates creation
const canCreateLegacySubscribers = true;
@@ -32,7 +31,7 @@ export const PkiSubscriberSection = () => {
] as const);
const onRemovePkiSubscriberSubmit = async (subscriberName: string) => {
- const subscriber = await deletePkiSubscriber({ subscriberName, projectId });
+ const subscriber = await deletePkiSubscriber({ subscriberName });
createNotification({
text: `Successfully deleted PKI subscriber: ${subscriber.name}`,
@@ -51,7 +50,7 @@ export const PkiSubscriberSection = () => {
}) => {
if (!currentProject?.slug) return;
- await updatePkiSubscriber({ subscriberName, projectId, status });
+ await updatePkiSubscriber({ subscriberName, status });
createNotification({
text: `Successfully ${status === PkiSubscriberStatus.ACTIVE ? "enabled" : "disabled"} subscriber`,
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx
index e4fca2023d..03efb9b3bf 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx
@@ -1,7 +1,7 @@
import { Helmet } from "react-helmet";
import { faBan, faChevronLeft } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { useNavigate, useParams } from "@tanstack/react-router";
+import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ProjectPermissionCan } from "@app/components/permissions";
import { EditPkiSyncModal } from "@app/components/pki-syncs";
@@ -30,6 +30,9 @@ const PageContent = () => {
const { syncId, projectId, orgId } = useParams({
from: ROUTE_PATHS.CertManager.PkiSyncDetailsByIDPage.id
});
+ const { applicationName } = useSearch({
+ from: ROUTE_PATHS.CertManager.PkiSyncDetailsByIDPage.id
+ });
const { handlePopUpToggle, popUp, handlePopUpOpen } = usePopUp(["editSync"] as const);
@@ -76,6 +79,13 @@ const PageContent = () => {
type="submit"
leftIcon={<FontAwesomeIcon icon={faChevronLeft} />}
onClick={() => {
+ if (applicationName) {
+ navigate({
+ to: `/organizations/${orgId}/projects/cert-manager/${projectId}/applications/${applicationName}` as never,
+ search: { selectedTab: "syncs" } as never
+ } as never);
+ return;
+ }
navigate({
to: ROUTE_PATHS.CertManager.IntegrationsListPage.path,
params: {
@@ -88,7 +98,7 @@ const PageContent = () => {
});
}}
>
- PKI Syncs
+ {applicationName || "PKI Syncs"}
</Button>
<div className="mb-6 flex w-full items-center gap-3">
<img
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/route.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/route.tsx
index 78f67cc3ac..dca8def99f 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/route.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/route.tsx
@@ -1,13 +1,20 @@
import { createFileRoute, linkOptions } from "@tanstack/react-router";
+import { zodValidator } from "@tanstack/zod-adapter";
+import { z } from "zod";
import { IntegrationsListPageTabs } from "@app/types/integrations";
import { PkiSyncDetailsByIDPage } from "./index";
+const PkiSyncDetailsSearchSchema = z.object({
+ applicationName: z.string().optional()
+});
+
export const Route = createFileRoute(
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/integrations/$syncId"
)({
component: PkiSyncDetailsByIDPage,
+ validateSearch: zodValidator(PkiSyncDetailsSearchSchema),
beforeLoad: ({ context, params }) => {
return {
breadcrumbs: [
diff --git a/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx b/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx
index b7cb9a3220..91ec4e0c36 100644
--- a/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx
+++ b/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx
@@ -44,7 +44,6 @@ import {
ProjectPermissionCertificateActions,
ProjectPermissionPkiTemplateActions,
ProjectPermissionSub,
- useProject,
useSubscription
} from "@app/context";
import { usePopUp } from "@app/hooks";
@@ -59,7 +58,6 @@ import { PkiTemplateForm } from "./components/PkiTemplateForm";
const PER_PAGE_INIT = 25;
export const PkiTemplateListPage = () => {
const { t } = useTranslation();
- const { currentProject } = useProject();
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(PER_PAGE_INIT);
@@ -74,7 +72,6 @@ export const PkiTemplateListPage = () => {
const { subscription } = useSubscription();
const { data, isPending } = useListCertificateTemplates({
- projectId: currentProject.id,
offset: (page - 1) * perPage,
limit: perPage
});
@@ -83,7 +80,6 @@ export const PkiTemplateListPage = () => {
const onRemovePkiSubscriberSubmit = async () => {
const pkiTemplate = await deleteCertTemplate.mutateAsync({
- projectId: currentProject.id,
templateName: popUp?.deleteTemplate?.data?.name
});
diff --git a/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx b/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx
index d0decf3f64..545fc3e770 100644
--- a/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx
+++ b/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx
@@ -74,7 +74,7 @@ type Props = {
export const PkiTemplateForm = ({ certTemplate, handlePopUpToggle }: Props) => {
const { currentProject } = useProject();
- const { data: cas, isPending: isCaLoading } = useListCasByProjectId(currentProject.id);
+ const { data: cas, isPending: isCaLoading } = useListCasByProjectId();
const { mutateAsync: createCertTemplate } = useCreateCertTemplateV2();
const { mutateAsync: updateCertTemplate } = useUpdateCertTemplateV2();
@@ -131,7 +131,6 @@ export const PkiTemplateForm = ({ certTemplate, handlePopUpToggle }: Props) => {
if (certTemplate) {
await updateCertTemplate({
templateName: certTemplate.name,
- projectId: currentProject.id,
caName: ca.name,
name,
commonName,
@@ -155,7 +154,6 @@ export const PkiTemplateForm = ({ certTemplate, handlePopUpToggle }: Props) => {
});
} else {
await createCertTemplate({
- projectId: currentProject.id,
caName: ca.name,
name,
commonName,
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/PolicyList.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/PolicyList.tsx
index 0e24464aaf..fbc039028e 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/PolicyList.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatePoliciesTab/PolicyList.tsx
@@ -46,7 +46,6 @@ export const PolicyList = ({ onEditPolicy, onDeletePolicy }: Props) => {
const [isIdCopied, setIsIdCopied] = useToggle(false);
const { data, isLoading } = useListCertificatePolicies({
- projectId: currentProject?.id || "",
limit: 100,
offset: 0
});
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
index 8308e3a041..e3a95bea93 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
@@ -593,9 +593,8 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
ProjectPermissionSub.CertificatePolicies
);
- const { data: allCaData } = useListCasByProjectId(currentProject?.id || "");
+ const { data: allCaData } = useListCasByProjectId();
const { data: policyData } = useListCertificatePolicies({
- projectId: currentProject?.id || "",
limit: 100,
offset: 0
});
@@ -713,14 +712,8 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
}
});
- const watchedEnrollmentType = watch("enrollmentType");
const watchedIssuerType = watch("issuerType");
const watchedCertificateAuthorityId = watch("certificateAuthorityId");
- const watchedDisableBootstrapValidation = watch("estConfig.disableBootstrapCaValidation");
- const watchedAutoRenew = watch("apiConfig.autoRenew");
- const watchedSkipDnsOwnershipVerification = watch("acmeConfig.skipDnsOwnershipVerification");
- const watchedSkipEabBinding = watch("acmeConfig.skipEabBinding");
- const watchedChallengeType = watch("scepConfig.challengeType");
const watchedPolicyId = watch("certificatePolicyId");
const watchedDefaultsIsCA = watch("defaults.basicConstraints.isCA") || false;
@@ -824,7 +817,6 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
// Fetch Azure ADCS templates if needed
const { data: azureAdcsTemplatesData } = useGetAzureAdcsTemplates({
caId: watchedCertificateAuthorityId || "",
- projectId: currentProject?.id || "",
isAzureAdcsCa
});
@@ -947,16 +939,6 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
issuerType: data.issuerType
};
- if (data.enrollmentType === EnrollmentType.EST && data.estConfig) {
- updateData.estConfig = data.estConfig;
- } else if (data.enrollmentType === EnrollmentType.API && data.apiConfig) {
- updateData.apiConfig = data.apiConfig;
- } else if (data.enrollmentType === EnrollmentType.ACME && data.acmeConfig) {
- updateData.acmeConfig = data.acmeConfig;
- } else if (data.enrollmentType === EnrollmentType.SCEP && data.scepConfig) {
- updateData.scepConfig = data.scepConfig;
- }
-
if (data.externalConfigs) {
updateData.externalConfigs = data.externalConfigs;
}
@@ -971,7 +953,6 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
}
const createData: TCreateCertificateProfileDTO = {
- projectId: currentProject.id,
slug: data.slug,
description: data.description,
enrollmentType: data.enrollmentType,
@@ -983,20 +964,6 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
certificatePolicyId: data.certificatePolicyId
};
- if (data.enrollmentType === EnrollmentType.EST && data.estConfig) {
- createData.estConfig = {
- passphrase: data.estConfig.passphrase,
- caChain: data.estConfig.caChain || undefined,
- disableBootstrapCaValidation: data.estConfig.disableBootstrapCaValidation
- };
- } else if (data.enrollmentType === EnrollmentType.API && data.apiConfig) {
- createData.apiConfig = data.apiConfig;
- } else if (data.enrollmentType === EnrollmentType.ACME && data.acmeConfig) {
- createData.acmeConfig = data.acmeConfig;
- } else if (data.enrollmentType === EnrollmentType.SCEP && data.scepConfig) {
- createData.scepConfig = data.scepConfig;
- }
-
if (data.externalConfigs) {
createData.externalConfigs = data.externalConfigs;
}
@@ -1280,465 +1247,6 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
</FormControl>
)}
/>
-
- <Controller
- control={control}
- name="enrollmentType"
- render={({ field: { onChange, ...field }, fieldState: { error } }) => (
- <FormControl
- label="Enrollment Method"
- isRequired
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Select
- {...field}
- onValueChange={(value) => {
- if (value === EnrollmentType.EST) {
- setValue("estConfig", {
- disableBootstrapCaValidation: false,
- passphrase: ""
- });
- } else if (value === EnrollmentType.API) {
- setValue("apiConfig", {
- autoRenew: false,
- renewBeforeDays: 30
- });
- } else if (value === EnrollmentType.ACME) {
- setValue("acmeConfig", {
- skipDnsOwnershipVerification: false,
- skipEabBinding: false
- });
- } else if (value === EnrollmentType.SCEP) {
- setValue("scepConfig", {
- challengeType: ScepChallengeType.STATIC,
- challengePassword: "",
- includeCaCertInResponse: true,
- allowCertBasedRenewal: true,
- dynamicChallengeExpiryMinutes: 60,
- dynamicChallengeMaxPending: 100
- });
- }
- onChange(value);
- }}
- className="w-full"
- position="popper"
- isDisabled={Boolean(isEdit)}
- >
- <SelectItem value={EnrollmentType.API}>API</SelectItem>
- {watchedIssuerType !== IssuerType.SELF_SIGNED && (
- <SelectItem value={EnrollmentType.EST}>EST</SelectItem>
- )}
- {watchedIssuerType !== IssuerType.SELF_SIGNED && (
- <SelectItem value={EnrollmentType.ACME}>ACME</SelectItem>
- )}
- {watchedIssuerType !== IssuerType.SELF_SIGNED && (
- <SelectItem value={EnrollmentType.SCEP}>SCEP</SelectItem>
- )}
- </Select>
- </FormControl>
- )}
- />
-
- {/* EST Configuration */}
- {watchedEnrollmentType === EnrollmentType.EST && (
- <div className="mb-4 space-y-4">
- <div className="space-y-4">
- <Controller
- control={control}
- name="estConfig.disableBootstrapCaValidation"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div className="flex items-center gap-3 rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4">
- <Checkbox
- id="disableBootstrapCaValidation"
- isChecked={value}
- onCheckedChange={onChange}
- />
- <div className="space-y-1">
- <span className="text-sm font-medium text-mineshaft-100">
- Disable Bootstrap CA Validation
- </span>
- <p className="text-xs text-bunker-300">
- Skip CA certificate validation during EST bootstrap phase
- </p>
- </div>
- </div>
- </FormControl>
- )}
- />
-
- <Controller
- control={control}
- name="estConfig.passphrase"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="EST Passphrase"
- isRequired={!isEdit}
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Input
- {...field}
- type="password"
- placeholder="Enter secure passphrase for EST authentication"
- className="w-full"
- />
- </FormControl>
- )}
- />
-
- {!watchedDisableBootstrapValidation && (
- <Controller
- control={control}
- name="estConfig.caChain"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="CA Chain Certificate"
- isRequired={!isEdit}
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <div className="space-y-2">
- <TextArea
- {...field}
- placeholder="-----BEGIN CERTIFICATE-----&#10;MIIDXTCCAkWgAwIBAgIJAKoK/heBjcOuMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV&#10;BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX&#10;...&#10;-----END CERTIFICATE-----"
- rows={6}
- className="w-full font-mono text-xs"
- />
- <p className="text-xs text-bunker-400">
- Paste the complete CA certificate chain in PEM format
- </p>
- </div>
- </FormControl>
- )}
- />
- )}
- </div>
- </div>
- )}
-
- {/* API Configuration */}
- {watchedEnrollmentType === EnrollmentType.API && (
- <div className="mb-4 space-y-4">
- <Controller
- control={control}
- name="apiConfig.autoRenew"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div className="flex items-center gap-2">
- <Checkbox id="autoRenew" isChecked={value} onCheckedChange={onChange}>
- Enable Auto-Renewal By Default
- </Checkbox>
- <Tooltip content="If enabled, certificates issued against this profile will auto-renew at specified days before expiration.">
- <FontAwesomeIcon
- icon={faQuestionCircle}
- className="cursor-help text-mineshaft-400 hover:text-mineshaft-300"
- size="sm"
- />
- </Tooltip>
- </div>
- </FormControl>
- )}
- />
- {watchedAutoRenew && (
- <Controller
- control={control}
- name="apiConfig.renewBeforeDays"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Auto-Renewal Days Before Expiration"
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Input
- {...field}
- type="number"
- placeholder="30"
- min="1"
- max="365"
- className="w-full"
- onChange={(e) => {
- const { value } = e.target;
- if (value === "") {
- field.onChange("");
- } else {
- const parsed = parseInt(value, 10);
- if (!Number.isNaN(parsed) && parsed >= 1 && parsed <= 365) {
- field.onChange(parsed);
- } else {
- field.onChange(field.value || "");
- }
- }
- }}
- />
- </FormControl>
- )}
- />
- )}
- </div>
- )}
-
- {/* ACME Configuration */}
- {watchedEnrollmentType === EnrollmentType.ACME && (
- <div className="mb-4 space-y-4">
- <Controller
- control={control}
- name="acmeConfig.skipEabBinding"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div
- className={`flex items-center gap-3 rounded-md border bg-mineshaft-900 p-4 ${
- watchedSkipDnsOwnershipVerification
- ? "border-mineshaft-700 opacity-50"
- : "border-mineshaft-600"
- }`}
- >
- <Checkbox
- id="skipEabBinding"
- isChecked={value || false}
- onCheckedChange={onChange}
- isDisabled={watchedSkipDnsOwnershipVerification}
- />
- <div className="space-y-1">
- <span className="text-sm font-medium text-mineshaft-100">
- Skip External Account Binding (EAB)
- </span>
- <p className="text-xs text-bunker-300">
- Skip EAB authentication when clients create ACME accounts.
- </p>
- {watchedSkipDnsOwnershipVerification && (
- <p className="text-xs text-yellow-500">
- Cannot be enabled while DNS ownership validation is skipped.
- </p>
- )}
- </div>
- </div>
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="acmeConfig.skipDnsOwnershipVerification"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div
- className={`flex items-center gap-3 rounded-md border bg-mineshaft-900 p-4 ${
- watchedSkipEabBinding
- ? "border-mineshaft-700 opacity-50"
- : "border-mineshaft-600"
- }`}
- >
- <Checkbox
- id="skipDnsOwnershipVerification"
- isChecked={value || false}
- onCheckedChange={onChange}
- isDisabled={watchedSkipEabBinding}
- />
- <div className="space-y-1">
- <span className="text-sm font-medium text-mineshaft-100">
- Skip DNS Ownership Validation
- </span>
- <p className="text-xs text-bunker-300">
- Skip DNS ownership verification during ACME certificate issuance.
- </p>
- {watchedSkipEabBinding && (
- <p className="text-xs text-yellow-500">
- Cannot be enabled while EAB is skipped.
- </p>
- )}
- </div>
- </div>
- </FormControl>
- )}
- />
- </div>
- )}
-
- {/* SCEP Configuration */}
- {watchedEnrollmentType === EnrollmentType.SCEP && (
- <div className="mb-4 space-y-4">
- <Controller
- control={control}
- name="scepConfig.challengeType"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl
- label="Challenge Type"
- isError={Boolean(error)}
- errorText={error?.message}
- helperText={
- value === ScepChallengeType.DYNAMIC
- ? "Challenges are generated on-demand via an authenticated API endpoint. Ideal for MDM tools like JAMF."
- : "A single shared challenge password is used for all enrollment requests."
- }
- >
- <Select
- value={value ?? ScepChallengeType.STATIC}
- onValueChange={(val) => {
- onChange(val);
- if (val === ScepChallengeType.DYNAMIC) {
- setValue("scepConfig.challengePassword", "");
- }
- }}
- className="w-full"
- >
- <SelectItem
- value={ScepChallengeType.STATIC}
- key={ScepChallengeType.STATIC}
- >
- Static Challenge
- </SelectItem>
- <SelectItem
- value={ScepChallengeType.DYNAMIC}
- key={ScepChallengeType.DYNAMIC}
- >
- Dynamic Challenge
- </SelectItem>
- </Select>
- </FormControl>
- )}
- />
-
- {watchedChallengeType !== ScepChallengeType.DYNAMIC && (
- <Controller
- control={control}
- name="scepConfig.challengePassword"
- render={({ field, fieldState: { error } }) => {
- const hadStaticPassword =
- isEdit &&
- profile?.scepConfig?.challengeType === ScepChallengeType.STATIC;
-
- return (
- <FormControl
- label="Challenge Password"
- isRequired={!hadStaticPassword}
- isError={Boolean(error)}
- errorText={error?.message}
- helperText="The challenge password cannot be viewed after saving. Make sure to save it somewhere safe."
- >
- <Input
- {...field}
- type="password"
- placeholder={
- hadStaticPassword
- ? "Leave empty to keep current password"
- : "Enter SCEP challenge password"
- }
- className="w-full"
- />
- </FormControl>
- );
- }}
- />
- )}
-
- {watchedChallengeType === ScepChallengeType.DYNAMIC && (
- <>
- <Controller
- control={control}
- name="scepConfig.dynamicChallengeExpiryMinutes"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Challenge Expiry (minutes)"
- isError={Boolean(error)}
- errorText={error?.message}
- helperText="How long each generated challenge remains valid before expiring."
- >
- <Input
- {...field}
- type="number"
- placeholder="60"
- min="1"
- max="1440"
- className="w-full"
- onChange={(e) => {
- const val = e.target.value;
- field.onChange(val === "" ? undefined : Number(val));
- }}
- value={field.value ?? ""}
- />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="scepConfig.dynamicChallengeMaxPending"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Max Pending Challenges"
- isError={Boolean(error)}
- errorText={error?.message}
- helperText="Maximum number of unused challenges that can exist at once."
- >
- <Input
- {...field}
- type="number"
- placeholder="100"
- min="1"
- max="1000"
- className="w-full"
- onChange={(e) => {
- const val = e.target.value;
- field.onChange(val === "" ? undefined : Number(val));
- }}
- value={field.value ?? ""}
- />
- </FormControl>
- )}
- />
- </>
- )}
-
- <Controller
- control={control}
- name="scepConfig.includeCaCertInResponse"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div className="flex items-center gap-3 rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4">
- <Checkbox
- id="includeCaCertInResponse"
- isChecked={value ?? true}
- onCheckedChange={onChange}
- />
- <div className="space-y-1">
- <span className="text-sm font-medium text-mineshaft-100">
- Include CA Certificate in Response
- </span>
- <p className="text-xs text-bunker-300">
- Include the CA certificate chain in SCEP responses
- </p>
- </div>
- </div>
- </FormControl>
- )}
- />
-
- <Controller
- control={control}
- name="scepConfig.allowCertBasedRenewal"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl isError={Boolean(error)} errorText={error?.message}>
- <div className="flex items-center gap-3 rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4">
- <Checkbox
- id="allowCertBasedRenewal"
- isChecked={value ?? true}
- onCheckedChange={onChange}
- />
- <div className="space-y-1">
- <span className="text-sm font-medium text-mineshaft-100">
- Allow Certificate-Based Renewal
- </span>
- <p className="text-xs text-bunker-300">
- Allow clients to renew certificates using an existing valid
- certificate instead of the challenge password
- </p>
- </div>
- </div>
- </FormControl>
- )}
- />
- </div>
- )}
</Tab.Panel>
{/* Tab 2: Certificate Defaults */}
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileList.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileList.tsx
index 830bc28b75..161ef0ed01 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileList.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileList.tsx
@@ -33,7 +33,6 @@ export const ProfileList = ({
const { currentProject } = useProject();
const { data, isLoading } = useListCertificateProfiles({
- projectId: currentProject?.id || "",
limit: 100,
offset: 0,
includeConfigs: true
diff --git a/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx b/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx
new file mode 100644
index 0000000000..a3f3b4dc88
--- /dev/null
+++ b/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx
@@ -0,0 +1,360 @@
+import { useMemo, useState } from "react";
+import { Helmet } from "react-helmet";
+import { useQuery } from "@tanstack/react-query";
+import { Link, useNavigate, useParams, useSearch } from "@tanstack/react-router";
+import { SearchIcon } from "lucide-react";
+
+import { PageHeader, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
+import {
+ Badge,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { useDebounce } from "@app/hooks";
+import { ApprovalPolicyType } from "@app/hooks/api/approvalPolicies";
+import {
+ approvalRequestQuery,
+ ApprovalRequestStatus,
+ CertRequestRequestData,
+ TApprovalRequest
+} from "@app/hooks/api/approvalRequests";
+import { useListPkiApplications } from "@app/hooks/api/pkiApplications";
+import { ProjectType } from "@app/hooks/api/projects/types";
+
+type StatusFilter = "pending" | "approved" | "rejected" | "all";
+
+const STATUS_TABS: {
+ key: StatusFilter;
+ label: string;
+ matches: (s: ApprovalRequestStatus) => boolean;
+}[] = [
+ {
+ key: "pending",
+ label: "Pending",
+ matches: (s) => s === ApprovalRequestStatus.Pending
+ },
+ {
+ key: "approved",
+ label: "Approved",
+ matches: (s) => s === ApprovalRequestStatus.Approved
+ },
+ {
+ key: "rejected",
+ label: "Rejected",
+ matches: (s) =>
+ s === ApprovalRequestStatus.Rejected ||
+ s === ApprovalRequestStatus.Cancelled ||
+ s === ApprovalRequestStatus.Expired
+ },
+ { key: "all", label: "All", matches: () => true }
+];
+
+const STATUS_BADGE: Record<
+ ApprovalRequestStatus,
+ { label: string; variant: "warning" | "success" | "danger" | "neutral" | "info" }
+> = {
+ [ApprovalRequestStatus.Pending]: { label: "Pending review", variant: "warning" },
+ [ApprovalRequestStatus.Approved]: { label: "Approved", variant: "success" },
+ [ApprovalRequestStatus.Rejected]: { label: "Rejected", variant: "danger" },
+ [ApprovalRequestStatus.Cancelled]: { label: "Cancelled", variant: "neutral" },
+ [ApprovalRequestStatus.Expired]: { label: "Expired", variant: "neutral" }
+};
+
+const formatRelative = (iso: string): string => {
+ const minutes = Math.round((Date.now() - new Date(iso).getTime()) / 60000);
+ if (minutes < 1) return "just now";
+ if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
+ const hours = Math.round(minutes / 60);
+ if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
+ const days = Math.round(hours / 24);
+ return `${days} day${days === 1 ? "" : "s"} ago`;
+};
+
+const isCertRequestData = (data: unknown): data is { requestData: CertRequestRequestData } => {
+ return Boolean(
+ data &&
+ typeof data === "object" &&
+ "requestData" in data &&
+ data.requestData &&
+ typeof data.requestData === "object" &&
+ "profileName" in (data.requestData as object)
+ );
+};
+
+export const RequestsPage = () => {
+ const { projectId, orgId } = useParams({ strict: false }) as {
+ projectId?: string;
+ orgId?: string;
+ };
+ const search = useSearch({ strict: false }) as { selectedTab?: string };
+ const navigate = useNavigate();
+ const selectedTab = search.selectedTab ?? "application-requests";
+
+ const [activeStatus, setActiveStatus] = useState<StatusFilter>("pending");
+ const [searchInput, setSearchInput] = useState("");
+ const [debouncedSearch] = useDebounce(searchInput, 300);
+
+ const { data: requests = [], isPending: isRequestsLoading } = useQuery(
+ approvalRequestQuery.list({
+ policyType: ApprovalPolicyType.CertRequest,
+ projectId: projectId ?? ""
+ })
+ );
+
+ const { data: apps = [] } = useListPkiApplications();
+ const appById = useMemo(() => {
+ const map = new Map<string, { id: string; name: string; slug: string }>();
+ apps.forEach((a) => map.set(a.id, { id: a.id, name: a.name, slug: a.slug }));
+ return map;
+ }, [apps]);
+
+ const filtered = useMemo(() => {
+ const tab = STATUS_TABS.find((t) => t.key === activeStatus) ?? STATUS_TABS[0];
+ const norm = debouncedSearch.trim().toLowerCase();
+
+ return (requests as TApprovalRequest[])
+ .filter((r) => tab.matches(r.status as ApprovalRequestStatus))
+ .filter((r) => {
+ if (!norm) return true;
+ const cn = isCertRequestData(r.requestData)
+ ? (r.requestData.requestData.certificateRequest?.commonName ?? "")
+ : "";
+ const profile = isCertRequestData(r.requestData)
+ ? (r.requestData.requestData.profileName ?? "")
+ : "";
+ const requester = `${r.requesterName} ${r.requesterEmail}`;
+ return (
+ cn.toLowerCase().includes(norm) ||
+ profile.toLowerCase().includes(norm) ||
+ requester.toLowerCase().includes(norm)
+ );
+ });
+ }, [requests, activeStatus, debouncedSearch]);
+
+ const counts = useMemo(() => {
+ const result: Record<StatusFilter, number> = {
+ pending: 0,
+ approved: 0,
+ rejected: 0,
+ all: requests.length
+ };
+ (requests as TApprovalRequest[]).forEach((r) => {
+ const s = r.status as ApprovalRequestStatus;
+ if (s === ApprovalRequestStatus.Pending) result.pending += 1;
+ else if (s === ApprovalRequestStatus.Approved) result.approved += 1;
+ else if (
+ s === ApprovalRequestStatus.Rejected ||
+ s === ApprovalRequestStatus.Cancelled ||
+ s === ApprovalRequestStatus.Expired
+ )
+ result.rejected += 1;
+ });
+ return result;
+ }, [requests]);
+
+ return (
+ <>
+ <Helmet>
+ <title>Requests</title>
+ </Helmet>
+ <div className="h-full bg-bunker-800">
+ <div className="mx-auto flex flex-col text-white">
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <PageHeader
+ scope={ProjectType.CertificateManager}
+ title="Requests"
+ description="Certificate approval requests across every Application. Use this inbox to approve, reject, or follow up on pending issuance."
+ />
+
+ <Tabs
+ value={selectedTab}
+ onValueChange={(v) =>
+ navigate({
+ to: `/organizations/${orgId ?? ""}/projects/cert-manager/${projectId ?? ""}/requests`,
+ search: { selectedTab: v } as never
+ } as never)
+ }
+ >
+ <TabList>
+ <Tab variant="project" value="application-requests">
+ Application Requests
+ </Tab>
+ <Tab variant="project" value="signing-requests">
+ Signing Requests
+ </Tab>
+ </TabList>
+
+ <TabPanel value="application-requests">
+ <Card>
+ <CardHeader>
+ <CardTitle>Application Requests</CardTitle>
+ <CardDescription>
+ Cert-request approval workflows triggered by an Application policy.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Tabs
+ value={activeStatus}
+ onValueChange={(v) => setActiveStatus(v as StatusFilter)}
+ >
+ <TabList>
+ {STATUS_TABS.map((t) => (
+ <Tab key={t.key} value={t.key} variant="project">
+ {t.label} ({counts[t.key]})
+ </Tab>
+ ))}
+ </TabList>
+ {STATUS_TABS.map((t) => (
+ <TabPanel key={t.key} value={t.key}>
+ <div className="my-4">
+ <InputGroup>
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ placeholder="Search by common name, profile, or requester…"
+ value={searchInput}
+ onChange={(e) => setSearchInput(e.target.value)}
+ />
+ </InputGroup>
+ </div>
+
+ {isRequestsLoading && (
+ <Empty>
+ <EmptyHeader>
+ <EmptyTitle>Loading…</EmptyTitle>
+ </EmptyHeader>
+ </Empty>
+ )}
+ {!isRequestsLoading && filtered.length === 0 && (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>
+ {activeStatus === "pending"
+ ? "No requests pending review"
+ : "No requests"}
+ </EmptyTitle>
+ <EmptyDescription>
+ Cert-request approval workflows from any Application in this
+ project will appear here.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ )}
+ {!isRequestsLoading && filtered.length > 0 && (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Common Name</TableHead>
+ <TableHead>Profile</TableHead>
+ <TableHead>Application</TableHead>
+ <TableHead>Requester</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead>Requested</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {filtered.map((r) => {
+ const certData = isCertRequestData(r.requestData)
+ ? r.requestData.requestData
+ : null;
+ const cn = certData?.certificateRequest?.commonName ?? "—";
+ const profile = certData?.profileName ?? "—";
+ const app = r.applicationId ? appById.get(r.applicationId) : null;
+ const badge = STATUS_BADGE[r.status as ApprovalRequestStatus] ?? {
+ label: r.status,
+ variant: "neutral" as const
+ };
+
+ return (
+ <TableRow key={r.id}>
+ <TableCell isTruncatable className="font-mono">
+ {cn}
+ </TableCell>
+ <TableCell className="font-mono text-xs">{profile}</TableCell>
+ <TableCell className="font-mono text-xs">
+ {app ? (
+ <Link
+ to={
+ `/organizations/${orgId}/projects/cert-manager/${projectId}/applications/${app.slug}` as never
+ }
+ className="text-foreground hover:text-project"
+ >
+ {app.slug}
+ </Link>
+ ) : (
+ <span className="text-accent">—</span>
+ )}
+ </TableCell>
+ <TableCell>
+ <div>{r.requesterName || "—"}</div>
+ {r.requesterEmail ? (
+ <div className="text-xs text-accent">
+ {r.requesterEmail}
+ </div>
+ ) : null}
+ </TableCell>
+ <TableCell>
+ <Badge variant={badge.variant}>{badge.label}</Badge>
+ </TableCell>
+ <TableCell className="text-accent">
+ {formatRelative(r.createdAt)}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ )}
+ </TabPanel>
+ ))}
+ </Tabs>
+ </CardContent>
+ </Card>
+ </TabPanel>
+
+ <TabPanel value="signing-requests">
+ <Card>
+ <CardHeader>
+ <CardTitle>Signing Requests</CardTitle>
+ <CardDescription>
+ Code-signing requests live on the Code Signing page. Visit Signers to review
+ pending signing operations.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>Code signing has its own surface</EmptyTitle>
+ <EmptyDescription>
+ Visit the Signers page to review pending code-signing requests — we link
+ out instead of duplicating the list here.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </CardContent>
+ </Card>
+ </TabPanel>
+ </Tabs>
+ </div>
+ </div>
+ </div>
+ </>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/RequestsPage/route.tsx b/frontend/src/pages/cert-manager/RequestsPage/route.tsx
new file mode 100644
index 0000000000..e48b47e238
--- /dev/null
+++ b/frontend/src/pages/cert-manager/RequestsPage/route.tsx
@@ -0,0 +1,22 @@
+import { createFileRoute, stripSearchParams } from "@tanstack/react-router";
+import { zodValidator } from "@tanstack/zod-adapter";
+import { z } from "zod";
+
+import { RequestsPage } from "./RequestsPage";
+
+const SearchSchema = z.object({
+ selectedTab: z.enum(["application-requests", "signing-requests"]).optional()
+});
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/requests"
+)({
+ component: RequestsPage,
+ validateSearch: zodValidator(SearchSchema),
+ search: {
+ middlewares: [stripSearchParams({ selectedTab: "application-requests" })]
+ },
+ beforeLoad: ({ context }) => ({
+ breadcrumbs: [...context.breadcrumbs, { label: "Requests" }]
+ })
+});
diff --git a/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx b/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx
index ab0fd0b376..4fd156b85c 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/SettingsPage.tsx
@@ -1,46 +1,115 @@
import { Helmet } from "react-helmet";
-import { useTranslation } from "react-i18next";
-import { Link, useSearch } from "@tanstack/react-router";
-import { InfoIcon } from "lucide-react";
+import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
-import { PageHeader } from "@app/components/v2";
-import { useOrganization } from "@app/context";
+import { ProjectPermissionCan } from "@app/components/permissions";
+import { PageHeader, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
+import {
+ ProjectPermissionAppConnectionActions,
+ ProjectPermissionCertificatePolicyActions,
+ ProjectPermissionCertificateProfileActions
+} from "@app/context/ProjectPermissionContext/types";
import { ProjectType } from "@app/hooks/api/projects/types";
-import { ProjectGeneralTab } from "@app/pages/project/SettingsPage/components/ProjectGeneralTab";
+import { AppConnectionsTable } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";
+import { CaSection, ExternalCaSection } from "../CertificateAuthoritiesPage/components";
+import { CertificatePoliciesTab, CertificateProfilesTab } from "../PoliciesPage/components";
import { CertificateCleanupTab } from "./components/CertificateCleanupTab";
export const SettingsPage = () => {
- const { t } = useTranslation();
- const { currentOrg, isSubOrganization } = useOrganization();
- const { selectedTab } = useSearch({
- from: "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/settings"
- });
-
- const activeTab = selectedTab || "general";
+ const { orgId, projectId } = useParams({ strict: false });
+ const search = useSearch({ strict: false }) as { selectedTab?: string };
+ const navigate = useNavigate();
+ const { currentProject } = useProject();
+ const activeTab = search.selectedTab ?? "certificate-authorities";
return (
<div className="flex h-full w-full justify-center bg-bunker-800 text-white">
<Helmet>
- <title>{t("common.head-title", { title: t("settings.project.title") })}</title>
+ <title>Settings</title>
</Helmet>
<div className="w-full max-w-8xl">
- <PageHeader scope={ProjectType.CertificateManager} title={t("settings.project.title")}>
- <Link
- to="/organizations/$orgId/settings"
- params={{
- orgId: currentOrg.id
- }}
- className="flex items-center gap-x-1.5 text-xs whitespace-nowrap text-neutral hover:underline"
- >
- <InfoIcon size={12} /> Looking for {isSubOrganization ? "sub-" : ""}organization
- settings?
- </Link>
- </PageHeader>
- <div>
- {activeTab === "general" && <ProjectGeneralTab />}
- {activeTab === "certificate-cleanup" && <CertificateCleanupTab />}
- </div>
+ <PageHeader
+ scope={ProjectType.CertificateManager}
+ title="Settings"
+ description="Configure certificate authorities, profiles, policies, app connections, and cleanup rules."
+ />
+
+ <Tabs
+ value={activeTab}
+ onValueChange={(v) =>
+ navigate({
+ to: `/organizations/${orgId ?? ""}/projects/cert-manager/${projectId ?? ""}/settings`,
+ search: { selectedTab: v } as never
+ } as never)
+ }
+ >
+ <TabList>
+ <Tab variant="project" value="certificate-authorities">
+ Certificate Authorities
+ </Tab>
+ <Tab variant="project" value="certificate-profiles">
+ Certificate Profiles
+ </Tab>
+ <Tab variant="project" value="certificate-policies">
+ Certificate Policies
+ </Tab>
+ <Tab variant="project" value="app-connections">
+ App Connections
+ </Tab>
+ <Tab variant="project" value="cleanup">
+ Cleanup
+ </Tab>
+ </TabList>
+
+ <TabPanel value="certificate-authorities">
+ <ProjectPermissionCan
+ renderGuardBanner
+ I={ProjectPermissionActions.Read}
+ a={ProjectPermissionSub.CertificateAuthorities}
+ >
+ <CaSection />
+ <ExternalCaSection />
+ </ProjectPermissionCan>
+ </TabPanel>
+
+ <TabPanel value="certificate-profiles">
+ <ProjectPermissionCan
+ renderGuardBanner
+ I={ProjectPermissionCertificateProfileActions.Read}
+ a={ProjectPermissionSub.CertificateProfiles}
+ >
+ <CertificateProfilesTab />
+ </ProjectPermissionCan>
+ </TabPanel>
+
+ <TabPanel value="certificate-policies">
+ <ProjectPermissionCan
+ renderGuardBanner
+ I={ProjectPermissionCertificatePolicyActions.Read}
+ a={ProjectPermissionSub.CertificatePolicies}
+ >
+ <CertificatePoliciesTab />
+ </ProjectPermissionCan>
+ </TabPanel>
+
+ <TabPanel value="app-connections">
+ <ProjectPermissionCan
+ renderGuardBanner
+ I={ProjectPermissionAppConnectionActions.Read}
+ a={ProjectPermissionSub.AppConnections}
+ >
+ <AppConnectionsTable
+ projectId={currentProject.id}
+ projectType={currentProject.type}
+ />
+ </ProjectPermissionCan>
+ </TabPanel>
+
+ <TabPanel value="cleanup">
+ <CertificateCleanupTab />
+ </TabPanel>
+ </Tabs>
</div>
</div>
);
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/CertificateCleanupTab.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/CertificateCleanupTab.tsx
index 29d5600ef1..8f12111d8a 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/components/CertificateCleanupTab.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/CertificateCleanupTab.tsx
@@ -6,7 +6,6 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Badge, Button, Input, Skeleton, Switch } from "@app/components/v3";
-import { useProject } from "@app/context";
import {
useGetCertificateCleanupConfig,
useUpdateCertificateCleanupConfig
@@ -21,10 +20,7 @@ const formSchema = z.object({
type TFormData = z.infer<typeof formSchema>;
export const CertificateCleanupTab = () => {
- const { currentProject } = useProject();
- const projectId = currentProject?.id || "";
-
- const { data: config, isLoading } = useGetCertificateCleanupConfig(projectId);
+ const { data: config, isLoading } = useGetCertificateCleanupConfig();
const updateConfig = useUpdateCertificateCleanupConfig();
const {
@@ -57,7 +53,6 @@ export const CertificateCleanupTab = () => {
const onSubmit = async (data: TFormData) => {
try {
await updateConfig.mutateAsync({
- projectId,
...data
});
createNotification({
diff --git a/frontend/src/pages/cert-manager/SettingsPage/route.tsx b/frontend/src/pages/cert-manager/SettingsPage/route.tsx
index 2a8ac1da10..d478694390 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/route.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/route.tsx
@@ -5,7 +5,7 @@ import { z } from "zod";
import { SettingsPage } from "./SettingsPage";
const settingsPageSearchSchema = z.object({
- selectedTab: z.string().optional().default("general")
+ selectedTab: z.string().optional().default("certificate-authorities")
});
export const Route = createFileRoute(
diff --git a/frontend/src/pages/cert-manager/components/CertManagerAdminOnly.tsx b/frontend/src/pages/cert-manager/components/CertManagerAdminOnly.tsx
new file mode 100644
index 0000000000..e7b7dda01b
--- /dev/null
+++ b/frontend/src/pages/cert-manager/components/CertManagerAdminOnly.tsx
@@ -0,0 +1,27 @@
+import { ReactNode, useEffect } from "react";
+import { useNavigate, useParams } from "@tanstack/react-router";
+
+import { useProjectPermission } from "@app/context";
+
+type Props = {
+ children: ReactNode;
+};
+
+export const CertManagerAdminOnly = ({ children }: Props) => {
+ const { hasProjectRole } = useProjectPermission();
+ const { orgId, projectId } = useParams({ strict: false });
+ const navigate = useNavigate();
+ const isAdmin = hasProjectRole("admin");
+
+ useEffect(() => {
+ if (!isAdmin && orgId && projectId) {
+ navigate({
+ to: `/organizations/${orgId}/projects/cert-manager/${projectId}/applications` as never
+ } as never);
+ }
+ }, [isAdmin, orgId, projectId, navigate]);
+
+ if (!isAdmin) return null;
+ // eslint-disable-next-line react/jsx-no-useless-fragment
+ return <>{children}</>;
+};
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx
index d4cdbca255..33dd248838 100644
--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx
@@ -1,4 +1,4 @@
-import { useEffect } from "react";
+import { useEffect, useMemo } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
@@ -23,6 +23,7 @@ import {
useGetProjectRoles,
useGetUserProjects
} from "@app/hooks/api";
+import { useCertManagerInstanceState } from "@app/hooks/api/certManagerInstance";
import { ProjectType, ProjectVersion } from "@app/hooks/api/projects/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -37,6 +38,11 @@ const BUILT_IN_PROJECT_ROLES = [
{ slug: "no-access", name: "No Access", description: "No access to any resources in the project" }
];
+const CERT_MANAGER_ROLES = [
+ { slug: "admin", name: "Admin", description: "Full administrative access over Cert Manager" },
+ { slug: "member", name: "Guest", description: "Limited read/write access in Cert Manager" }
+];
+
const EmailSchema = z.string().email().min(1).trim().toLowerCase();
const addMemberFormSchema = z.object({
@@ -47,7 +53,8 @@ const addMemberFormSchema = z.object({
name: z.string(),
id: z.string(),
slug: z.string(),
- version: z.nativeEnum(ProjectVersion)
+ version: z.nativeEnum(ProjectVersion),
+ type: z.nativeEnum(ProjectType).optional()
})
)
.default([]),
@@ -88,9 +95,21 @@ export const AddOrgMemberModal = ({
const { data: serverDetails } = useFetchServerStatus();
const { mutateAsync: addUsersMutateAsync } = useAddUsersToOrg();
const { mutateAsync: addUserToProject } = useAddUserToWsNonE2EE();
- const { data: projects, isPending: isProjectsLoading } = useGetUserProjects({
+ const { data: rawProjects, isPending: isProjectsLoading } = useGetUserProjects({
includeRoles: true
});
+ const { data: certManagerInstance } = useCertManagerInstanceState();
+
+ const projects = useMemo(() => {
+ if (!rawProjects) return rawProjects;
+ const activeId = certManagerInstance?.activeProjectId ?? null;
+ return rawProjects
+ .filter((p) => {
+ if (p.type !== ProjectType.CertificateManager) return true;
+ return activeId ? p.id === activeId : true;
+ })
+ .map((p) => (p.type === ProjectType.CertificateManager ? { ...p, name: "Cert Manager" } : p));
+ }, [rawProjects, certManagerInstance?.activeProjectId]);
const {
control,
@@ -106,14 +125,22 @@ export const AddOrgMemberModal = ({
const selectedProjects = watch("projects", []);
const singleSelectedProjectId =
selectedProjects.length === 1 ? selectedProjects[0].id : undefined;
+ const hasCertManagerSelection = selectedProjects.some(
+ (p) => p.type === ProjectType.CertificateManager
+ );
const { data: fetchedProjectRoles, isPending: isProjectRolesLoading } = useGetProjectRoles(
singleSelectedProjectId ?? ""
);
- const projectRoles = fetchedProjectRoles?.length ? fetchedProjectRoles : BUILT_IN_PROJECT_ROLES;
+ // eslint-disable-next-line no-nested-ternary
+ const projectRoles = hasCertManagerSelection
+ ? CERT_MANAGER_ROLES
+ : fetchedProjectRoles?.length
+ ? fetchedProjectRoles
+ : BUILT_IN_PROJECT_ROLES;
useEffect(() => {
setValue("projectRole", DEFAULT_PROJECT_ROLE);
- }, [singleSelectedProjectId, setValue]);
+ }, [singleSelectedProjectId, hasCertManagerSelection, setValue]);
// set initial form role based off org default role
useEffect(() => {
diff --git a/frontend/src/pages/organization/ProjectsPage/components/MyProjectView.tsx b/frontend/src/pages/organization/ProjectsPage/components/MyProjectView.tsx
index c59ecf57a5..fa8289dfb8 100644
--- a/frontend/src/pages/organization/ProjectsPage/components/MyProjectView.tsx
+++ b/frontend/src/pages/organization/ProjectsPage/components/MyProjectView.tsx
@@ -31,7 +31,12 @@ import {
Tooltip
} from "@app/components/v2";
import { OrgPermissionActions, OrgPermissionSubjects, useOrganization } from "@app/context";
-import { getProjectHomePage, getProjectLottieIcon, getProjectTitle } from "@app/helpers/project";
+import {
+ collapseCertManagerProjects,
+ getProjectHomePage,
+ getProjectLottieIcon,
+ getProjectTitle
+} from "@app/helpers/project";
import {
getUserTablePreference,
PreferenceKey,
@@ -39,6 +44,7 @@ import {
} from "@app/helpers/userTablePreferences";
import { usePagination, useResetPageHelper } from "@app/hooks";
import { useGetUserProjects } from "@app/hooks/api";
+import { useCertManagerInstanceState } from "@app/hooks/api/certManagerInstance";
import { OrderByDirection } from "@app/hooks/api/generic/types";
import { Project, ProjectType } from "@app/hooks/api/projects/types";
import { useUpdateUserProjectFavorites } from "@app/hooks/api/users/mutation";
@@ -78,7 +84,12 @@ export const MyProjectView = ({
{}
);
- const { data: workspaces = [], isPending: isWorkspaceLoading } = useGetUserProjects();
+ const { data: rawWorkspaces = [], isPending: isWorkspaceLoading } = useGetUserProjects();
+ const { data: certManagerInstance } = useCertManagerInstanceState();
+ const workspaces = useMemo(
+ () => collapseCertManagerProjects(rawWorkspaces, certManagerInstance?.activeProjectId ?? null),
+ [rawWorkspaces, certManagerInstance?.activeProjectId]
+ );
const {
setPage,
perPage,
diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/OrgCertManagerTab.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/OrgCertManagerTab.tsx
new file mode 100644
index 0000000000..7deb47805d
--- /dev/null
+++ b/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/OrgCertManagerTab.tsx
@@ -0,0 +1,120 @@
+import { useState } from "react";
+
+import { createNotification } from "@app/components/notifications";
+import { Spinner } from "@app/components/v2";
+import {
+ Badge,
+ Button,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import {
+ useCertManagerLegacyInstances,
+ useSetCertManagerActiveProject
+} from "@app/hooks/api/certManagerInstance";
+
+export const OrgCertManagerTab = () => {
+ const { data, isPending } = useCertManagerLegacyInstances();
+ const setActive = useSetCertManagerActiveProject();
+ const [pendingId, setPendingId] = useState<string | null>(null);
+
+ const onPick = async (projectId: string, name: string) => {
+ setPendingId(projectId);
+ try {
+ await setActive.mutateAsync(projectId);
+ createNotification({
+ type: "success",
+ text: `${name} is now the active Cert Manager instance`
+ });
+ } catch (err) {
+ const detail = err instanceof Error ? err.message : "Failed to switch active instance.";
+ createNotification({ type: "error", text: detail });
+ } finally {
+ setPendingId(null);
+ }
+ };
+
+ if (isPending || !data) {
+ return (
+ <div className="flex items-center justify-center p-8">
+ <Spinner />
+ </div>
+ );
+ }
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Cert Manager</CardTitle>
+ <CardDescription>
+ Pick which Cert Manager instance the product launches into. API requests without a
+ projectId resolve to the active instance.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ {data.instances.length === 0 ? (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>No Cert Manager instances</EmptyTitle>
+ <EmptyDescription>
+ Create a Cert Manager project from the organization to get started.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ <TableHead className="text-right">Certificates</TableHead>
+ <TableHead className="text-right">Syncs</TableHead>
+ <TableHead className="text-right">Alerts</TableHead>
+ <TableHead className="text-right">Action</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {data.instances.map((i) => (
+ <TableRow key={i.id}>
+ <TableCell isTruncatable>
+ <div className="font-medium text-foreground">{i.name}</div>
+ <div className="font-mono text-xs text-accent">{i.slug}</div>
+ </TableCell>
+ <TableCell className="text-right">{i.certificateCount}</TableCell>
+ <TableCell className="text-right">{i.syncCount}</TableCell>
+ <TableCell className="text-right">{i.alertCount}</TableCell>
+ <TableCell className="text-right">
+ {i.isActive ? (
+ <Badge variant="success">Active</Badge>
+ ) : (
+ <Button
+ size="xs"
+ variant="outline"
+ isPending={pendingId === i.id}
+ onClick={() => onPick(i.id, i.name)}
+ >
+ Set as active
+ </Button>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/index.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/index.tsx
new file mode 100644
index 0000000000..6698a9b38d
--- /dev/null
+++ b/frontend/src/pages/organization/SettingsPage/components/OrgCertManagerTab/index.tsx
@@ -0,0 +1 @@
+export { OrgCertManagerTab } from "./OrgCertManagerTab";
diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgTabGroup/OrgTabGroup.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgTabGroup/OrgTabGroup.tsx
index 6d0f489556..db1f2f0def 100644
--- a/frontend/src/pages/organization/SettingsPage/components/OrgTabGroup/OrgTabGroup.tsx
+++ b/frontend/src/pages/organization/SettingsPage/components/OrgTabGroup/OrgTabGroup.tsx
@@ -4,10 +4,12 @@ import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
import { TabPanel, Tabs } from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
import { useOrganization, useSubscription } from "@app/context";
+import { useCertManagerInstanceState } from "@app/hooks/api/certManagerInstance";
import { usePopUp } from "@app/hooks/usePopUp";
import { AuditLogStreamsTab } from "../AuditLogStreamTab";
import { ExternalMigrationsTab } from "../ExternalMigrationsTab";
+import { OrgCertManagerTab } from "../OrgCertManagerTab";
import { OrgEncryptionTab } from "../OrgEncryptionTab";
import { OrgGeneralTab } from "../OrgGeneralTab";
import { OrgProductSettingsTab } from "../OrgProductSettingsTab";
@@ -25,8 +27,11 @@ export const OrgTabGroup = () => {
const navigate = useNavigate();
const { currentOrg, isSubOrganization } = useOrganization();
const { subscription } = useSubscription();
+ const { data: certManagerInstance } = useCertManagerInstanceState();
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["upgradePlan"] as const);
+ const hasMultipleCertManagerInstances = (certManagerInstance?.projects.length ?? 0) >= 2;
+
const tabs = [
{ name: "General", key: "tab-org-general", component: OrgGeneralTab },
{
@@ -73,6 +78,12 @@ export const OrgTabGroup = () => {
key: "product-enforcements",
component: OrgProductSettingsTab
},
+ {
+ name: "Certificate Manager",
+ key: "cert-manager",
+ component: OrgCertManagerTab,
+ isHidden: !hasMultipleCertManagerInstances
+ },
{
name: "Sub Organizations",
key: "tab-sub-organizations",
diff --git a/frontend/src/pages/project/AccessControlPage/AccessControlPage.tsx b/frontend/src/pages/project/AccessControlPage/AccessControlPage.tsx
index 7ba8536bca..6ae57df2f2 100644
--- a/frontend/src/pages/project/AccessControlPage/AccessControlPage.tsx
+++ b/frontend/src/pages/project/AccessControlPage/AccessControlPage.tsx
@@ -38,14 +38,19 @@ const Page = () => {
};
const isSecretManager = currentProject.type === ProjectType.SecretManager;
+ const isCertManager = currentProject.type === ProjectType.CertificateManager;
return (
<div className="mx-auto flex flex-col justify-between bg-bunker-800 text-white">
<div className="mx-auto mb-6 w-full max-w-8xl">
<PageHeader
scope={currentProject.type}
- title="Project Access Control"
- description="Manage fine-grained access for users, groups, roles, and machine identities within your project resources."
+ title={isCertManager ? "Cert Manager Access Control" : "Project Access Control"}
+ description={
+ isCertManager
+ ? "Manage fine-grained access for users, groups, roles, and machine identities within your Cert Manager."
+ : "Manage fine-grained access for users, groups, roles, and machine identities within your project resources."
+ }
>
<Link
to="/organizations/$orgId/access-management"
diff --git a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupModal.tsx b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupModal.tsx
index 17ef73120b..324e2b2e52 100644
--- a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupModal.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupModal.tsx
@@ -13,6 +13,7 @@ import {
useGetProjectRoles,
useListWorkspaceGroups
} from "@app/hooks/api";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
const schema = z.object({
@@ -36,9 +37,12 @@ const Content = ({ popUp, handlePopUpToggle }: Props) => {
const orgId = currentOrg?.id || "";
const { data: groups } = useGetOrganizationGroups(orgId);
- const { data: groupMemberships } = useListWorkspaceGroups(currentProject?.id || "");
+ const { data: groupMemberships } = useListWorkspaceGroups(
+ currentProject?.id || "",
+ currentProject?.type
+ );
- const { data: roles } = useGetProjectRoles(currentProject?.id || "");
+ const { data: roles } = useGetProjectRoles(currentProject?.id || "", currentProject?.type);
const { mutateAsync: addGroupToWorkspaceMutateAsync } = useAddGroupToWorkspace();
@@ -64,6 +68,7 @@ const Content = ({ popUp, handlePopUpToggle }: Props) => {
const onFormSubmit = async ({ group, role }: FormData) => {
await addGroupToWorkspaceMutateAsync({
projectId: currentProject?.id || "",
+ projectType: currentProject?.type,
groupId: group.id,
role: role.slug || undefined
});
@@ -148,12 +153,16 @@ const Content = ({ popUp, handlePopUpToggle }: Props) => {
};
export const GroupModal = ({ popUp, handlePopUpToggle }: Props) => {
+ const { currentProject } = useProject();
+ const isCertManager = currentProject?.type === ProjectType.CertificateManager;
+ const productLabel = isCertManager ? "Cert Manager" : "Project";
+
return (
<Modal
isOpen={popUp?.group?.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("group", isOpen)}
>
- <ModalContent bodyClassName="overflow-visible" title="Add Group to Project">
+ <ModalContent bodyClassName="overflow-visible" title={`Add Group to ${productLabel}`}>
<Content popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
</ModalContent>
</Modal>
diff --git a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupRoles.tsx b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupRoles.tsx
index 7e60ecf61f..f24278e7cd 100644
--- a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupRoles.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupRoles.tsx
@@ -279,6 +279,7 @@ const GroupRolesForm = ({ projectRoles, roles, groupId, onClose }: FormProps) =>
await updateGroupWorkspaceRole.mutateAsync({
projectId: currentProject?.id || "",
+ projectType: currentProject?.type,
groupId,
roles: selectedRoles
});
@@ -398,7 +399,8 @@ export const GroupRoles = ({
const [isEditOpen, setIsEditOpen] = useState(false);
const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(
- currentProject?.id ?? ""
+ currentProject?.id ?? "",
+ currentProject?.type
);
const assignRoleConditions = useMemo(
diff --git a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsSection.tsx b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsSection.tsx
index b7fa484355..94140c1d68 100644
--- a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsSection.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsSection.tsx
@@ -22,6 +22,7 @@ import {
} from "@app/context";
import { usePopUp } from "@app/hooks";
import { useDeleteGroupFromWorkspace } from "@app/hooks/api";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { GroupModal } from "./GroupModal";
import { GroupTable } from "./GroupsTable";
@@ -29,6 +30,8 @@ import { GroupTable } from "./GroupsTable";
export const GroupsSection = () => {
const { subscription } = useSubscription();
const { currentProject } = useProject();
+ const isCertManager = currentProject?.type === ProjectType.CertificateManager;
+ const productLabel = isCertManager ? "Cert Manager" : "Project";
const { mutateAsync: deleteMutateAsync } = useDeleteGroupFromWorkspace();
@@ -52,11 +55,12 @@ export const GroupsSection = () => {
const onRemoveGroupSubmit = async (groupId: string) => {
await deleteMutateAsync({
groupId,
- projectId: currentProject?.id || ""
+ projectId: currentProject?.id || "",
+ projectType: currentProject?.type
});
createNotification({
- text: "Successfully removed identity from project",
+ text: `Successfully removed group from ${productLabel.toLowerCase()}`,
type: "success"
});
@@ -68,10 +72,10 @@ export const GroupsSection = () => {
<Card>
<CardHeader>
<CardTitle>
- Project Groups
+ {`${productLabel} Groups`}
<DocumentationLinkBadge href="https://infisical.com/docs/documentation/platform/groups#user-groups" />
</CardTitle>
- <CardDescription>Add and manage project groups</CardDescription>
+ <CardDescription>{`Add and manage ${productLabel.toLowerCase()} groups`}</CardDescription>
<CardAction>
<ProjectPermissionCan
I={ProjectPermissionActions.Create}
@@ -84,7 +88,7 @@ export const GroupsSection = () => {
isDisabled={!isAllowed}
>
<PlusIcon />
- Add Group to Project
+ {`Add Group to ${productLabel}`}
</Button>
)}
</ProjectPermissionCan>
@@ -99,7 +103,7 @@ export const GroupsSection = () => {
isOpen={popUp.deleteGroup.isOpen}
title={`Are you sure you want to remove the group ${
(popUp?.deleteGroup?.data as { name: string })?.name || ""
- } from the project?`}
+ } from the ${productLabel.toLowerCase()}?`}
onChange={(isOpen) => handlePopUpToggle("deleteGroup", isOpen)}
deleteKey="confirm"
onDeleteApproved={() =>
diff --git a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsTable.tsx b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsTable.tsx
index e8cf481fbb..8098f02482 100644
--- a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsTable.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsTable.tsx
@@ -42,6 +42,7 @@ import {
import { usePagination, useResetPageHelper } from "@app/hooks";
import { useListWorkspaceGroups } from "@app/hooks/api";
import { OrderByDirection } from "@app/hooks/api/generic/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { GroupRoles } from "./GroupRoles";
@@ -64,6 +65,8 @@ export const GroupTable = ({ handlePopUpOpen }: Props) => {
const { currentOrg } = useOrganization();
const { currentProject } = useProject();
const navigate = useNavigate();
+ const isCertManager = currentProject?.type === ProjectType.CertificateManager;
+ const productLabel = isCertManager ? "Cert Manager" : "Project";
const {
search,
@@ -86,7 +89,8 @@ export const GroupTable = ({ handlePopUpOpen }: Props) => {
};
const { data: groupMemberships = [], isPending } = useListWorkspaceGroups(
- currentProject?.id || ""
+ currentProject?.id || "",
+ currentProject?.type
);
const filteredGroupMemberships = useMemo(() => {
@@ -123,7 +127,7 @@ export const GroupTable = ({ handlePopUpOpen }: Props) => {
<InputGroupInput
value={search}
onChange={(e) => setSearch(e.target.value)}
- placeholder="Search project groups..."
+ placeholder={isCertManager ? "Search groups..." : "Search project groups..."}
/>
</InputGroup>
</div>
@@ -131,7 +135,14 @@ export const GroupTable = ({ handlePopUpOpen }: Props) => {
<Empty className="border">
<EmptyHeader>
<EmptyTitle>
- {search ? "No project groups match search" : "No project groups found"}
+ {/* eslint-disable-next-line no-nested-ternary */}
+ {search
+ ? isCertManager
+ ? "No groups match search"
+ : "No project groups match search"
+ : isCertManager
+ ? "No groups found"
+ : "No project groups found"}
</EmptyTitle>
<EmptyDescription>
{search ? "Adjust your search criteria." : "Add a group to get started."}
@@ -152,7 +163,7 @@ export const GroupTable = ({ handlePopUpOpen }: Props) => {
)}
/>
</TableHead>
- <TableHead>Project Role</TableHead>
+ <TableHead>{`${productLabel} Role`}</TableHead>
<TableHead>Added on</TableHead>
<TableHead className="w-5" />
</TableRow>
@@ -256,7 +267,7 @@ export const GroupTable = ({ handlePopUpOpen }: Props) => {
}}
>
<UserRoundXIcon />
- Remove Group From Project
+ {`Remove Group From ${productLabel}`}
</DropdownMenuItem>
)}
</ProjectPermissionCan>
diff --git a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/IdentityTab.tsx b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/IdentityTab.tsx
index 61f5c063b7..1e0d5d9c3c 100644
--- a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/IdentityTab.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/IdentityTab.tsx
@@ -83,7 +83,7 @@ import {
useListProjectIdentityMemberships
} from "@app/hooks/api";
import { OrderByDirection } from "@app/hooks/api/generic/types";
-import { ProjectIdentityOrderBy } from "@app/hooks/api/projects/types";
+import { ProjectIdentityOrderBy, ProjectType } from "@app/hooks/api/projects/types";
import { usePopUp } from "@app/hooks/usePopUp";
import { ProjectIdentityModal } from "@app/pages/project/AccessControlPage/components/IdentityTab/components/ProjectIdentityModal";
@@ -101,6 +101,8 @@ export const IdentityTab = withProjectPermission(
const { currentProject, projectId } = useProject();
const navigate = useNavigate();
const { isSubOrganization, currentOrg } = useOrganization();
+ const isCertManager = currentProject?.type === ProjectType.CertificateManager;
+ const productLabel = isCertManager ? "Cert Manager" : "Project";
const [addMachineIdentityType, setAddMachineIdentityType] = useState<AddIdentityType>(
AddIdentityType.CreateNew
@@ -129,7 +131,7 @@ export const IdentityTab = withProjectPermission(
setUserTablePreference("projectIdentityTable", PreferenceKey.PerPage, newPerPage);
};
- const { data: projectRoles } = useGetProjectRoles(projectId);
+ const { data: projectRoles } = useGetProjectRoles(projectId, currentProject?.type);
const [filterRoles, setFilterRoles] = useState<string[]>([]);
const isTableFiltered = Boolean(filterRoles.length);
@@ -149,6 +151,7 @@ export const IdentityTab = withProjectPermission(
const { data, isPending, isFetching } = useListProjectIdentityMemberships(
{
projectId,
+ projectType: currentProject?.type,
offset,
limit,
orderDirection,
@@ -191,7 +194,8 @@ export const IdentityTab = withProjectPermission(
} else {
await deleteMembershipMutateAsync({
identityId,
- projectId
+ projectId,
+ projectType: currentProject?.type
});
createNotification({
@@ -225,10 +229,10 @@ export const IdentityTab = withProjectPermission(
<Card>
<CardHeader>
<CardTitle>
- Project Machine Identities
+ {productLabel} Machine Identities
<DocumentationLinkBadge href="https://infisical.com/docs/documentation/platform/identities/machine-identities" />
</CardTitle>
- <CardDescription>Create and manage project machine identities</CardDescription>
+ <CardDescription>{`Create and manage ${productLabel.toLowerCase()} machine identities`}</CardDescription>
<CardAction>
<ProjectPermissionCan
I={ProjectPermissionActions.Create}
@@ -241,7 +245,7 @@ export const IdentityTab = withProjectPermission(
isDisabled={!isAllowed}
>
<PlusIcon />
- Add Machine Identity to Project
+ {`Add Machine Identity to ${productLabel}`}
</Button>
)}
</ProjectPermissionCan>
@@ -257,7 +261,11 @@ export const IdentityTab = withProjectPermission(
<InputGroupInput
value={search}
onChange={(e) => setSearch(e.target.value)}
- placeholder="Search project machine identities by name..."
+ placeholder={
+ isCertManager
+ ? "Search machine identities by name..."
+ : "Search project machine identities by name..."
+ }
/>
</InputGroup>
<DropdownMenu>
@@ -267,7 +275,7 @@ export const IdentityTab = withProjectPermission(
</IconButton>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
- <DropdownMenuLabel>Filter by Project Role</DropdownMenuLabel>
+ <DropdownMenuLabel>{`Filter by ${productLabel} Role`}</DropdownMenuLabel>
{projectRoles?.map(({ id, slug, name }) => (
<DropdownMenuCheckboxItem
key={id}
@@ -287,9 +295,12 @@ export const IdentityTab = withProjectPermission(
<Empty className="border">
<EmptyHeader>
<EmptyTitle>
+ {/* eslint-disable-next-line no-nested-ternary */}
{debouncedSearch.trim().length > 0 || isTableFiltered
? "No machine identities match search"
- : "No machine identities have been added to this project"}
+ : isCertManager
+ ? "No machine identities have been added to this Cert Manager"
+ : "No machine identities have been added to this project"}
</EmptyTitle>
<EmptyDescription>
{debouncedSearch.trim().length > 0 || isTableFiltered
@@ -318,7 +329,7 @@ export const IdentityTab = withProjectPermission(
)}
/>
</TableHead>
- <TableHead className="w-1/3">Project Role</TableHead>
+ <TableHead className="w-1/3">{`${productLabel} Role`}</TableHead>
<TableHead>Managed by</TableHead>
<TableHead className="w-5">
{isFetching ? <Spinner size="xs" /> : null}
@@ -559,9 +570,12 @@ export const IdentityTab = withProjectPermission(
}}
>
{identityProjectId ? <TrashIcon /> : <XIcon />}
+ {/* eslint-disable-next-line no-nested-ternary */}
{identityProjectId
? "Delete Machine Identity"
- : "Remove From Project"}
+ : isCertManager
+ ? "Remove From Cert Manager"
+ : "Remove From Project"}
</DropdownMenuItem>
)}
</ProjectPermissionCan>
@@ -609,7 +623,7 @@ export const IdentityTab = withProjectPermission(
>
<ModalContent
bodyClassName="overflow-visible"
- title="Add Machine Identity to Project"
+ title={`Add Machine Identity to ${productLabel}`}
subTitle="Create a new machine identity or assign an existing one"
>
<div className="mb-4 flex items-center justify-center gap-x-2">
@@ -690,7 +704,7 @@ export const IdentityTab = withProjectPermission(
isOpen={popUp.deleteIdentity.isOpen}
title={`Are you sure you want to remove ${
(popUp?.deleteIdentity?.data as { name: string })?.name || ""
- } from the project?`}
+ } from the ${productLabel.toLowerCase()}?`}
onChange={(isOpen) => handlePopUpToggle("deleteIdentity", isOpen)}
deleteKey="confirm"
onDeleteApproved={() =>
diff --git a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/ProjectIdentityModal.tsx b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/ProjectIdentityModal.tsx
index 7dc8e93fc4..b51de6b080 100644
--- a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/ProjectIdentityModal.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/ProjectIdentityModal.tsx
@@ -55,7 +55,7 @@ export const ProjectIdentityModal = ({ onClose, identity }: ContentProps) => {
const isUpdate = Boolean(identity);
- const { data: roles } = useGetProjectRoles(currentProject.id);
+ const { data: roles } = useGetProjectRoles(currentProject.id, currentProject.type);
const { mutateAsync: createMutateAsync } = useCreateProjectIdentity();
const { mutateAsync: updateMutateAsync } = useUpdateProjectIdentity();
@@ -109,7 +109,8 @@ export const ProjectIdentityModal = ({ onClose, identity }: ContentProps) => {
await updateMembershipMutateAsync({
roles: [{ role: role.slug }],
identityId: createdId,
- projectId: currentProject.id
+ projectId: currentProject.id,
+ projectType: currentProject.type
});
}
diff --git a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/ProjectLinkIdentityModal.tsx b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/ProjectLinkIdentityModal.tsx
index 71e289465b..2547feada8 100644
--- a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/ProjectLinkIdentityModal.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/ProjectLinkIdentityModal.tsx
@@ -30,7 +30,7 @@ type Props = {
};
export const ProjectLinkIdentityModal = ({ handlePopUpToggle }: Props) => {
- const { projectId } = useProject();
+ const { projectId, currentProject } = useProject();
// const [searchValue, setSearchValue] = useState("");
@@ -39,7 +39,8 @@ export const ProjectLinkIdentityModal = ({ handlePopUpToggle }: Props) => {
// TODO: name search needs to be implemented on the backend
const { data: identityMembershipOrgs, isPending: isMembershipsLoading } = useQuery({
...projectIdentityMembershipQuery.listAvailable({
- projectId
+ projectId,
+ projectType: currentProject?.type
// identityName: debouncedSearchValue
}),
placeholderData: (prev) => prev
@@ -47,11 +48,15 @@ export const ProjectLinkIdentityModal = ({ handlePopUpToggle }: Props) => {
const { data: identityMembershipsData } = useListProjectIdentityMemberships({
projectId,
+ projectType: currentProject?.type,
limit: 1000 // TODO: this is temp to preserve functionality for larger projects, will optimize in PR referenced above
});
const identityMemberships = identityMembershipsData?.identityMemberships;
- const { data: roles, isPending: isRolesLoading } = useGetProjectRoles(projectId);
+ const { data: roles, isPending: isRolesLoading } = useGetProjectRoles(
+ projectId,
+ currentProject?.type
+ );
const { mutateAsync: createProjectIdentityMembershipMutateAsync } =
useCreateProjectIdentityMembership();
@@ -78,6 +83,7 @@ export const ProjectLinkIdentityModal = ({ handlePopUpToggle }: Props) => {
const onFormSubmit = async ({ identity, role }: FormData) => {
await createProjectIdentityMembershipMutateAsync({
projectId,
+ projectType: currentProject?.type,
identityId: identity.id,
role: role.slug || undefined
});
diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx
index 38ec96692d..1273b2b29e 100644
--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx
@@ -31,7 +31,7 @@ import {
useGetProjectRoles,
useGetWorkspaceUsers
} from "@app/hooks/api";
-import { ProjectVersion } from "@app/hooks/api/projects/types";
+import { ProjectType, ProjectVersion } from "@app/hooks/api/projects/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { filterByGrantConditions, getMemberAssignRoleConditions } from "@app/lib/fn/permission";
@@ -69,11 +69,13 @@ export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => {
const orgId = currentOrg?.id || "";
const projectId = currentProject?.id || "";
+ const isCertManager = currentProject?.type === ProjectType.CertificateManager;
+ const productLabel = isCertManager ? "Cert Manager" : "Project";
const { data: members } = useGetWorkspaceUsers(projectId);
const { data: orgUsers } = useGetOrgUsers(orgId);
- const { data: roles } = useGetProjectRoles(currentProject?.id || "");
+ const { data: roles } = useGetProjectRoles(currentProject?.id || "", currentProject?.type);
const assignRoleConditions = useMemo(
() => getMemberAssignRoleConditions(projectPermission),
@@ -160,6 +162,7 @@ export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => {
usernames: [...inviteeEmails, ...newInvitees],
orgId,
projectId: currentProject.id,
+ projectType: currentProject.type,
roleSlugs: projectRoleSlugs.map((role) => role.slug)
});
}
@@ -235,7 +238,11 @@ export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => {
>
<ModalContent
bodyClassName="overflow-visible"
- title={t("section.members.add-dialog.add-member-to-project") as string}
+ title={
+ isCertManager
+ ? "Add Members to Cert Manager"
+ : (t("section.members.add-dialog.add-member-to-project") as string)
+ }
subTitle={t("section.members.add-dialog.user-will-email")}
>
<form onSubmit={handleSubmit(onAddMembers)}>
@@ -248,7 +255,7 @@ export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => {
className="w-full"
isError={!!errors.orgMemberships?.length}
errorText={errors.orgMemberships?.[0]?.message}
- label="Invite users to project"
+ label={`Invite users to ${productLabel.toLowerCase()}`}
helperText={
canInviteNewMembers
? "You can invite new users to your organization by typing out their email address"
diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRbacSection.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRbacSection.tsx
index ff87e9d05e..f1a0e2afdb 100644
--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRbacSection.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRbacSection.tsx
@@ -64,8 +64,11 @@ type Props = {
};
export const MemberRbacSection = ({ projectMember, onOpenUpgradeModal }: Props) => {
const { subscription } = useSubscription();
- const { projectId } = useProject();
- const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(projectId);
+ const { projectId, currentProject } = useProject();
+ const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(
+ projectId,
+ currentProject?.type
+ );
const { permission } = useProjectPermission();
const isMemberEditDisabled = permission.cannot(
ProjectPermissionMemberActions.Edit,
@@ -129,6 +132,7 @@ export const MemberRbacSection = ({ projectMember, onOpenUpgradeModal }: Props)
await updateMembershipRole.mutateAsync({
projectId,
+ projectType: currentProject.type,
membershipId: projectMember.id,
roles: sanitizedRoles
});
diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx
index cb36aafe87..5af78b42ef 100644
--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx
@@ -21,6 +21,7 @@ import {
} from "@app/context";
import { usePopUp } from "@app/hooks";
import { useDeleteUserFromWorkspace } from "@app/hooks/api";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { AddMemberModal } from "./AddMemberModal";
import { MembersTable } from "./MembersTable";
@@ -28,6 +29,8 @@ import { MembersTable } from "./MembersTable";
export const MembersSection = () => {
const { currentOrg } = useOrganization();
const { currentProject } = useProject();
+ const isCertManager = currentProject?.type === ProjectType.CertificateManager;
+ const productLabel = isCertManager ? "Cert Manager" : "Project";
const { mutateAsync: removeUserFromWorkspace } = useDeleteUserFromWorkspace();
@@ -43,6 +46,7 @@ export const MembersSection = () => {
await removeUserFromWorkspace({
projectId: currentProject.id,
+ projectType: currentProject.type,
usernames: [username],
orgId: currentOrg.id
});
@@ -58,10 +62,10 @@ export const MembersSection = () => {
<Card>
<CardHeader>
<CardTitle>
- Project Users
+ {`${productLabel} Users`}
<DocumentationLinkBadge href="https://infisical.com/docs/documentation/platform/identities/user-identities" />
</CardTitle>
- <CardDescription>Invite and manage project users</CardDescription>
+ <CardDescription>{`Invite and manage ${productLabel.toLowerCase()} users`}</CardDescription>
<CardAction>
<ProjectPermissionCan
I={ProjectPermissionActions.Create}
@@ -74,7 +78,7 @@ export const MembersSection = () => {
isDisabled={!isAllowed}
>
<UserPlusIcon />
- Add Users to Project
+ {`Add Users to ${productLabel}`}
</Button>
)}
</ProjectPermissionCan>
@@ -88,7 +92,7 @@ export const MembersSection = () => {
<DeleteActionModal
isOpen={popUp.removeMember.isOpen}
deleteKey="remove"
- title="Do you want to remove this user from the project?"
+ title={`Do you want to remove this user from the ${productLabel.toLowerCase()}?`}
onChange={(isOpen) => handlePopUpToggle("removeMember", isOpen)}
onDeleteApproved={handleRemoveUser}
/>
diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersTable.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersTable.tsx
index 9e6ef603a6..5ef6b0a117 100644
--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersTable.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersTable.tsx
@@ -54,6 +54,7 @@ import {
import { usePagination, useResetPageHelper } from "@app/hooks";
import { useGetProjectRoles, useGetWorkspaceUsers } from "@app/hooks/api";
import { OrderByDirection } from "@app/hooks/api/generic/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
const MAX_ROLES_TO_BE_SHOWN_IN_TABLE = 2;
@@ -80,9 +81,11 @@ export const MembersTable = ({ handlePopUpOpen }: Props) => {
});
const filterRoles = useMemo(() => filter.roles, [filter.roles]);
+ const isCertManager = currentProject?.type === ProjectType.CertificateManager;
+ const productLabel = isCertManager ? "Cert Manager" : "Project";
const userId = user?.id || "";
const projectId = currentProject?.id || "";
- const { data: projectRoles } = useGetProjectRoles(projectId);
+ const { data: projectRoles } = useGetProjectRoles(projectId, currentProject?.type);
const {
search,
@@ -191,7 +194,7 @@ export const MembersTable = ({ handlePopUpOpen }: Props) => {
<InputGroupInput
value={search}
onChange={(e) => setSearch(e.target.value)}
- placeholder="Search project users..."
+ placeholder={isCertManager ? "Search users..." : "Search project users..."}
/>
</InputGroup>
<DropdownMenu>
@@ -201,7 +204,7 @@ export const MembersTable = ({ handlePopUpOpen }: Props) => {
</IconButton>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
- <DropdownMenuLabel>Filter by Project Role</DropdownMenuLabel>
+ <DropdownMenuLabel>{`Filter by ${productLabel} Role`}</DropdownMenuLabel>
{projectRoles?.map(({ id, slug, name }) => (
<DropdownMenuCheckboxItem
key={id}
@@ -222,9 +225,14 @@ export const MembersTable = ({ handlePopUpOpen }: Props) => {
<Empty className="border">
<EmptyHeader>
<EmptyTitle>
+ {/* eslint-disable-next-line no-nested-ternary */}
{search || isTableFiltered
- ? "No project users match search"
- : "No project users found"}
+ ? isCertManager
+ ? "No users match search"
+ : "No project users match search"
+ : isCertManager
+ ? "No users found"
+ : "No project users found"}
</EmptyTitle>
<EmptyDescription>
{search || isTableFiltered
@@ -262,7 +270,7 @@ export const MembersTable = ({ handlePopUpOpen }: Props) => {
)}
/>
</TableHead>
- <TableHead>Project Role</TableHead>
+ <TableHead>{`${productLabel} Role`}</TableHead>
<TableHead className="w-5" />
</TableRow>
</TableHeader>
@@ -454,7 +462,7 @@ export const MembersTable = ({ handlePopUpOpen }: Props) => {
}}
>
<UserXIcon />
- Remove User From Project
+ {`Remove User From ${productLabel}`}
</DropdownMenuItem>
)}
</ProjectPermissionCan>
diff --git a/frontend/src/pages/project/AccessControlPage/components/ProjectRoleListTab/components/ProjectRoleList/ProjectRoleList.tsx b/frontend/src/pages/project/AccessControlPage/components/ProjectRoleListTab/components/ProjectRoleList/ProjectRoleList.tsx
index c7fdc191ea..0e94307cec 100644
--- a/frontend/src/pages/project/AccessControlPage/components/ProjectRoleListTab/components/ProjectRoleList/ProjectRoleList.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/ProjectRoleListTab/components/ProjectRoleList/ProjectRoleList.tsx
@@ -68,6 +68,7 @@ import {
import { usePagination, usePopUp, useResetPageHelper } from "@app/hooks";
import { useDeleteProjectRole, useGetProjectRoles } from "@app/hooks/api";
import { OrderByDirection } from "@app/hooks/api/generic/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole, TProjectRole } from "@app/hooks/api/roles/types";
import { SubscriptionPlanTypes } from "@app/hooks/api/subscriptions/types";
import { DuplicateProjectRoleModal } from "@app/pages/project/RoleDetailsBySlugPage/components/DuplicateProjectRoleModal";
@@ -88,8 +89,12 @@ export const ProjectRoleList = () => {
] as const);
const { currentProject } = useProject();
const projectId = currentProject?.id || "";
+ const isCertManager = currentProject?.type === ProjectType.CertificateManager;
- const { data: roles, isPending: isRolesLoading } = useGetProjectRoles(projectId);
+ const { data: roles, isPending: isRolesLoading } = useGetProjectRoles(
+ projectId,
+ currentProject?.type
+ );
const { mutateAsync: deleteRole } = useDeleteProjectRole();
const { subscription } = useSubscription();
@@ -98,6 +103,7 @@ export const ProjectRoleList = () => {
const { id } = popUp?.deleteRole?.data as TProjectRole;
await deleteRole({
projectId,
+ projectType: currentProject?.type,
id
});
createNotification({ type: "success", text: "Successfully removed the role" });
@@ -222,24 +228,33 @@ export const ProjectRoleList = () => {
<Card>
<CardHeader>
<CardTitle>
- Project Roles
+ {isCertManager ? "Cert Manager Roles" : "Project Roles"}
<DocumentationLinkBadge href="https://infisical.com/docs/documentation/platform/access-controls/role-based-access-controls#project-level-access-controls" />
</CardTitle>
- <CardDescription>Create and manage project roles</CardDescription>
- <CardAction>
- <ProjectPermissionCan I={ProjectPermissionActions.Create} a={ProjectPermissionSub.Role}>
- {(isAllowed) => (
- <Button
- variant="project"
- onClick={() => handlePopUpOpen("role")}
- isDisabled={!isAllowed}
- >
- <PlusIcon />
- Add Project Role
- </Button>
- )}
- </ProjectPermissionCan>
- </CardAction>
+ <CardDescription>
+ {isCertManager
+ ? "View built-in roles for Cert Manager"
+ : "Create and manage project roles"}
+ </CardDescription>
+ {!isCertManager && (
+ <CardAction>
+ <ProjectPermissionCan
+ I={ProjectPermissionActions.Create}
+ a={ProjectPermissionSub.Role}
+ >
+ {(isAllowed) => (
+ <Button
+ variant="project"
+ onClick={() => handlePopUpOpen("role")}
+ isDisabled={!isAllowed}
+ >
+ <PlusIcon />
+ Add Project Role
+ </Button>
+ )}
+ </ProjectPermissionCan>
+ </CardAction>
+ )}
</CardHeader>
<CardContent>
<div className="mb-4">
@@ -250,7 +265,7 @@ export const ProjectRoleList = () => {
<InputGroupInput
value={search}
onChange={(e) => setSearch(e.target.value)}
- placeholder="Search project roles..."
+ placeholder={isCertManager ? "Search roles..." : "Search project roles..."}
/>
</InputGroup>
</div>
@@ -258,12 +273,22 @@ export const ProjectRoleList = () => {
<Empty className="border">
<EmptyHeader>
<EmptyTitle>
+ {/* eslint-disable-next-line no-nested-ternary */}
{roles?.length
- ? "No project roles match search"
- : "This project does not have any roles"}
+ ? isCertManager
+ ? "No roles match search"
+ : "No project roles match search"
+ : isCertManager
+ ? "No roles available"
+ : "This project does not have any roles"}
</EmptyTitle>
<EmptyDescription>
- {roles?.length ? "Adjust your search criteria." : "Add a role to get started."}
+ {/* eslint-disable-next-line no-nested-ternary */}
+ {roles?.length
+ ? "Adjust your search criteria."
+ : isCertManager
+ ? "Built-in roles will appear here."
+ : "Add a role to get started."}
</EmptyDescription>
</EmptyHeader>
</Empty>
@@ -401,23 +426,25 @@ export const ProjectRoleList = () => {
</DropdownMenuItem>
)}
</ProjectPermissionCan>
- <ProjectPermissionCan
- I={ProjectPermissionActions.Create}
- a={ProjectPermissionSub.Role}
- >
- {(isAllowed) => (
- <DropdownMenuItem
- onClick={(e) => {
- e.stopPropagation();
- handlePopUpOpen("duplicateRole", role);
- }}
- isDisabled={!isAllowed}
- >
- <CopyIcon />
- Duplicate Role
- </DropdownMenuItem>
- )}
- </ProjectPermissionCan>
+ {!isCertManager && (
+ <ProjectPermissionCan
+ I={ProjectPermissionActions.Create}
+ a={ProjectPermissionSub.Role}
+ >
+ {(isAllowed) => (
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePopUpOpen("duplicateRole", role);
+ }}
+ isDisabled={!isAllowed}
+ >
+ <CopyIcon />
+ Duplicate Role
+ </DropdownMenuItem>
+ )}
+ </ProjectPermissionCan>
+ )}
{!isNonMutatable && (
<ProjectPermissionCan
I={ProjectPermissionActions.Delete}
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx
index ea58ab7a96..0a2ce37c78 100644
--- a/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx
@@ -59,7 +59,7 @@ export const Page = () => {
} = useUser();
const { data: membershipDetails, isPending: isMembershipDetailsLoading } =
- useGetWorkspaceUserDetails(projectId, membershipId);
+ useGetWorkspaceUserDetails(projectId, membershipId, currentProject?.type);
const { mutateAsync: removeUserFromWorkspace } = useDeleteUserFromWorkspace();
const assumePrivileges = useAssumeProjectPrivileges();
@@ -99,6 +99,7 @@ export const Page = () => {
await removeUserFromWorkspace({
projectId,
+ projectType: currentProject?.type,
usernames: [membershipDetails?.user?.username],
orgId: currentOrg.id
});
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleDetailsSection.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleDetailsSection.tsx
index a4eb33c9c2..e0d1407cda 100644
--- a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleDetailsSection.tsx
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleDetailsSection.tsx
@@ -100,6 +100,7 @@ export const MemberRoleDetailsSection = ({
const updatedRoles = membershipDetails?.roles?.filter((el) => el.id !== id);
await updateUserWorkspaceRole({
projectId,
+ projectType: currentProject?.type,
roles: updatedRoles.map(
({
role,
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleModify.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleModify.tsx
index a3640b8dfa..7b8a89b84f 100644
--- a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleModify.tsx
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleModify.tsx
@@ -73,8 +73,11 @@ type Props = {
export const MemberRoleModify = ({ projectMember, onOpenUpgradeModal }: Props) => {
const { subscription } = useSubscription();
- const { projectId } = useProject();
- const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(projectId);
+ const { projectId, currentProject } = useProject();
+ const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(
+ projectId,
+ currentProject?.type
+ );
const { permission } = useProjectPermission();
const isMemberEditDisabled = permission.cannot(
ProjectPermissionMemberActions.Edit,
@@ -181,6 +184,7 @@ export const MemberRoleModify = ({ projectMember, onOpenUpgradeModal }: Props) =
await updateMembershipRole.mutateAsync({
projectId,
+ projectType: currentProject?.type,
membershipId: projectMember.id,
roles: sanitizedRoles
});
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/RoleDetailsBySlugPage.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/RoleDetailsBySlugPage.tsx
index 594cd52e8a..6e3fb480ec 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/RoleDetailsBySlugPage.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/RoleDetailsBySlugPage.tsx
@@ -22,6 +22,7 @@ import {
} from "@app/context";
import { getProjectBaseURL } from "@app/helpers/project";
import { useDeleteProjectRole, useGetProjectRoleBySlug } from "@app/hooks/api";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
import { usePopUp } from "@app/hooks/usePopUp";
import { DuplicateProjectRoleModal } from "@app/pages/project/RoleDetailsBySlugPage/components/DuplicateProjectRoleModal";
@@ -41,7 +42,9 @@ const Page = () => {
const projectId = currentProject?.id || "";
const orgId = currentOrg?.id || "";
- const { data } = useGetProjectRoleBySlug(projectId, roleSlug as string);
+ const isCertManager = currentProject?.type === ProjectType.CertificateManager;
+ const { data } = useGetProjectRoleBySlug(projectId, roleSlug as string, currentProject?.type);
+ const displayName = isCertManager && data?.slug === "member" ? "Guest" : (data?.name ?? "");
const { mutateAsync: deleteProjectRole } = useDeleteProjectRole();
@@ -96,11 +99,11 @@ const Page = () => {
className="mb-4 flex items-center gap-x-2 text-sm text-muted"
>
<ChevronLeftIcon className="size-4" />
- Project Roles
+ {isCertManager ? "Cert Manager Roles" : "Project Roles"}
</Link>
<PageHeader
scope={currentProject.type}
- title={data.name}
+ title={displayName}
description={
<>
{data.slug} {data.description && `- ${data.description}`}
@@ -199,6 +202,19 @@ const Page = () => {
</DropdownMenu>
)}
</PageHeader>
+ {isCertManager && isCustomRole && (
+ <div className="mb-4 rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4 text-sm text-mineshaft-200">
+ <p className="font-medium text-mineshaft-100">
+ Custom roles act as Member in Cert Manager
+ </p>
+ <p className="mt-1 text-mineshaft-300">
+ In the new Cert Manager flow, access is granted through Application memberships
+ (Admin or Member). Permissions defined here only apply to legacy endpoints — users
+ with this role are treated as Member at the project level and only see resources
+ inside Applications they are explicitly added to.
+ </p>
+ </div>
+ )}
<RolePermissionsSection roleSlug={roleSlug} isDisabled={!isCustomRole} />
</div>
)}
diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.ts
index 9acecdf506..a1037c68c8 100644
--- a/frontend/src/routeTree.gen.ts
+++ b/frontend/src/routeTree.gen.ts
@@ -118,9 +118,12 @@ import { Route as kmsSettingsPageRouteImport } from './pages/kms/SettingsPage/ro
import { Route as kmsOverviewPageRouteImport } from './pages/kms/OverviewPage/route'
import { Route as kmsKmipPageRouteImport } from './pages/kms/KmipPage/route'
import { Route as certManagerSettingsPageRouteImport } from './pages/cert-manager/SettingsPage/route'
+import { Route as certManagerRequestsPageRouteImport } from './pages/cert-manager/RequestsPage/route'
import { Route as certManagerPoliciesPageRouteImport } from './pages/cert-manager/PoliciesPage/route'
import { Route as certManagerDashboardPageRouteImport } from './pages/cert-manager/DashboardPage/route'
+import { Route as certManagerInventoryPageRouteImport } from './pages/cert-manager/InventoryPage/route'
import { Route as certManagerCertificateAuthoritiesPageRouteImport } from './pages/cert-manager/CertificateAuthoritiesPage/route'
+import { Route as certManagerCertManagerAccessPageRouteImport } from './pages/cert-manager/CertManagerAccessPage/route'
import { Route as certManagerAlertingPageRouteImport } from './pages/cert-manager/AlertingPage/route'
import { Route as aiSettingsPageRouteImport } from './pages/ai/SettingsPage/route'
import { Route as aiMCPPageRouteImport } from './pages/ai/MCPPage/route'
@@ -167,6 +170,7 @@ import { Route as certManagerSignerDetailPageRouteImport } from './pages/cert-ma
import { Route as certManagerCertificateDetailsByIDPageRouteImport } from './pages/cert-manager/CertificateDetailsByIDPage/route'
import { Route as certManagerCertAuthDetailsByIDPageRouteImport } from './pages/cert-manager/CertAuthDetailsByIDPage/route'
import { Route as certManagerApprovalRequestDetailPageRouteImport } from './pages/cert-manager/ApprovalRequestDetailPage/route'
+import { Route as certManagerApplicationDetailsByIDPageRouteImport } from './pages/cert-manager/ApplicationDetailsByIDPage/route'
import { Route as aiMCPServerDetailPageRouteImport } from './pages/ai/MCPServerDetailPage/route'
import { Route as aiMCPEndpointDetailPageRouteImport } from './pages/ai/MCPEndpointDetailPage/route'
import { Route as secretScanningSecretScanningDataSourcesPageRouteImport } from './pages/secret-scanning/SecretScanningDataSourcesPage/route'
@@ -182,6 +186,7 @@ import { Route as certManagerDiscoveryPageRouteImport } from './pages/cert-manag
import { Route as certManagerCodeSigningPageRouteImport } from './pages/cert-manager/CodeSigningPage/route'
import { Route as certManagerPkiTemplateListPageRouteImport } from './pages/cert-manager/PkiTemplateListPage/route'
import { Route as certManagerApprovalsPageRouteImport } from './pages/cert-manager/ApprovalsPage/route'
+import { Route as certManagerApplicationsPageRouteImport } from './pages/cert-manager/ApplicationsPage/route'
import { Route as secretScanningSecretScanningDataSourceByIdPageRouteImport } from './pages/secret-scanning/SecretScanningDataSourceByIdPage/route'
import { Route as secretManagerIntegrationsWindmillConfigurePageRouteImport } from './pages/secret-manager/integrations/WindmillConfigurePage/route'
import { Route as secretManagerIntegrationsWindmillAuthorizePageRouteImport } from './pages/secret-manager/integrations/WindmillAuthorizePage/route'
@@ -386,6 +391,10 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManager
createFileRoute(
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals',
)()
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsImport =
+ createFileRoute(
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications',
+ )()
const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdImport =
createFileRoute(
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId',
@@ -1244,6 +1253,15 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManager
} as any,
)
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRoute =
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsImport.update(
+ {
+ id: '/applications',
+ path: '/applications',
+ getParentRoute: () => certManagerLayoutRoute,
+ } as any,
+ )
+
const projectAppConnectionsPageRouteCertManagerRoute =
projectAppConnectionsPageRouteCertManagerImport.update({
id: '/app-connections',
@@ -1396,6 +1414,13 @@ const certManagerSettingsPageRouteRoute =
getParentRoute: () => certManagerLayoutRoute,
} as any)
+const certManagerRequestsPageRouteRoute =
+ certManagerRequestsPageRouteImport.update({
+ id: '/requests',
+ path: '/requests',
+ getParentRoute: () => certManagerLayoutRoute,
+ } as any)
+
const certManagerPoliciesPageRouteRoute =
certManagerPoliciesPageRouteImport.update({
id: '/policies',
@@ -1410,6 +1435,13 @@ const certManagerDashboardPageRouteRoute =
getParentRoute: () => certManagerLayoutRoute,
} as any)
+const certManagerInventoryPageRouteRoute =
+ certManagerInventoryPageRouteImport.update({
+ id: '/inventory',
+ path: '/inventory',
+ getParentRoute: () => certManagerLayoutRoute,
+ } as any)
+
const certManagerCertificateAuthoritiesPageRouteRoute =
certManagerCertificateAuthoritiesPageRouteImport.update({
id: '/certificate-authorities',
@@ -1417,6 +1449,13 @@ const certManagerCertificateAuthoritiesPageRouteRoute =
getParentRoute: () => certManagerLayoutRoute,
} as any)
+const certManagerCertManagerAccessPageRouteRoute =
+ certManagerCertManagerAccessPageRouteImport.update({
+ id: '/cert-manager-access',
+ path: '/cert-manager-access',
+ getParentRoute: () => certManagerLayoutRoute,
+ } as any)
+
const certManagerAlertingPageRouteRoute =
certManagerAlertingPageRouteImport.update({
id: '/alerting',
@@ -1745,6 +1784,14 @@ const certManagerApprovalRequestDetailPageRouteRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApprovalsRoute,
} as any)
+const certManagerApplicationDetailsByIDPageRouteRoute =
+ certManagerApplicationDetailsByIDPageRouteImport.update({
+ id: '/$applicationName',
+ path: '/$applicationName',
+ getParentRoute: () =>
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRoute,
+ } as any)
+
const aiMCPServerDetailPageRouteRoute = aiMCPServerDetailPageRouteImport.update(
{
id: '/mcp-servers/$serverId',
@@ -1859,6 +1906,14 @@ const certManagerApprovalsPageRouteRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApprovalsRoute,
} as any)
+const certManagerApplicationsPageRouteRoute =
+ certManagerApplicationsPageRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () =>
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRoute,
+ } as any)
+
const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdImport.update(
{
@@ -3240,6 +3295,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof certManagerAlertingPageRouteImport
parentRoute: typeof certManagerLayoutImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/cert-manager-access': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/cert-manager-access'
+ path: '/cert-manager-access'
+ fullPath: '/organizations/$orgId/projects/cert-manager/$projectId/cert-manager-access'
+ preLoaderRoute: typeof certManagerCertManagerAccessPageRouteImport
+ parentRoute: typeof certManagerLayoutImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificate-authorities': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificate-authorities'
path: '/certificate-authorities'
@@ -3247,6 +3309,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof certManagerCertificateAuthoritiesPageRouteImport
parentRoute: typeof certManagerLayoutImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/inventory': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/inventory'
+ path: '/inventory'
+ fullPath: '/organizations/$orgId/projects/cert-manager/$projectId/inventory'
+ preLoaderRoute: typeof certManagerInventoryPageRouteImport
+ parentRoute: typeof certManagerLayoutImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/overview': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/overview'
path: '/overview'
@@ -3261,6 +3330,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof certManagerPoliciesPageRouteImport
parentRoute: typeof certManagerLayoutImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/requests': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/requests'
+ path: '/requests'
+ fullPath: '/organizations/$orgId/projects/cert-manager/$projectId/requests'
+ preLoaderRoute: typeof certManagerRequestsPageRouteImport
+ parentRoute: typeof certManagerLayoutImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/settings': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/settings'
path: '/settings'
@@ -3422,6 +3498,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof projectAppConnectionsPageRouteCertManagerImport
parentRoute: typeof certManagerLayoutImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications'
+ path: '/applications'
+ fullPath: '/organizations/$orgId/projects/cert-manager/$projectId/applications'
+ preLoaderRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsImport
+ parentRoute: typeof certManagerLayoutImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals'
path: '/approvals'
@@ -3604,6 +3687,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof projectAuditLogsPageRouteSshImport
parentRoute: typeof sshLayoutImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/'
+ path: '/'
+ fullPath: '/organizations/$orgId/projects/cert-manager/$projectId/applications/'
+ preLoaderRoute: typeof certManagerApplicationsPageRouteImport
+ parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals/': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals/'
path: '/'
@@ -3709,6 +3799,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof aiMCPServerDetailPageRouteImport
parentRoute: typeof aiLayoutImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/$applicationName': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/$applicationName'
+ path: '/$applicationName'
+ fullPath: '/organizations/$orgId/projects/cert-manager/$projectId/applications/$applicationName'
+ preLoaderRoute: typeof certManagerApplicationDetailsByIDPageRouteImport
+ parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals/$approvalRequestId': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals/$approvalRequestId'
path: '/$approvalRequestId'
@@ -4746,6 +4843,24 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsAiProjectId
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsAiProjectIdRouteChildren,
)
+interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRouteChildren {
+ certManagerApplicationsPageRouteRoute: typeof certManagerApplicationsPageRouteRoute
+ certManagerApplicationDetailsByIDPageRouteRoute: typeof certManagerApplicationDetailsByIDPageRouteRoute
+}
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRouteChildren: AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRouteChildren =
+ {
+ certManagerApplicationsPageRouteRoute:
+ certManagerApplicationsPageRouteRoute,
+ certManagerApplicationDetailsByIDPageRouteRoute:
+ certManagerApplicationDetailsByIDPageRouteRoute,
+ }
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRouteWithChildren =
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRoute._addFileChildren(
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRouteChildren,
+ )
+
interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApprovalsRouteChildren {
certManagerApprovalsPageRouteRoute: typeof certManagerApprovalsPageRouteRoute
certManagerApprovalRequestDetailPageRouteRoute: typeof certManagerApprovalRequestDetailPageRouteRoute
@@ -4853,13 +4968,17 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManager
interface certManagerLayoutRouteChildren {
certManagerAlertingPageRouteRoute: typeof certManagerAlertingPageRouteRoute
+ certManagerCertManagerAccessPageRouteRoute: typeof certManagerCertManagerAccessPageRouteRoute
certManagerCertificateAuthoritiesPageRouteRoute: typeof certManagerCertificateAuthoritiesPageRouteRoute
+ certManagerInventoryPageRouteRoute: typeof certManagerInventoryPageRouteRoute
certManagerDashboardPageRouteRoute: typeof certManagerDashboardPageRouteRoute
certManagerPoliciesPageRouteRoute: typeof certManagerPoliciesPageRouteRoute
+ certManagerRequestsPageRouteRoute: typeof certManagerRequestsPageRouteRoute
certManagerSettingsPageRouteRoute: typeof certManagerSettingsPageRouteRoute
certManagerDashboardPageRouteIndexRoute: typeof certManagerDashboardPageRouteIndexRoute
projectAccessControlPageRouteCertManagerRoute: typeof projectAccessControlPageRouteCertManagerRoute
projectAppConnectionsPageRouteCertManagerRoute: typeof projectAppConnectionsPageRouteCertManagerRoute
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRouteWithChildren
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApprovalsRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApprovalsRouteWithChildren
projectAuditLogsPageRouteCertManagerRoute: typeof projectAuditLogsPageRouteCertManagerRoute
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutCertificateTemplatesRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutCertificateTemplatesRouteWithChildren
@@ -4878,10 +4997,14 @@ interface certManagerLayoutRouteChildren {
const certManagerLayoutRouteChildren: certManagerLayoutRouteChildren = {
certManagerAlertingPageRouteRoute: certManagerAlertingPageRouteRoute,
+ certManagerCertManagerAccessPageRouteRoute:
+ certManagerCertManagerAccessPageRouteRoute,
certManagerCertificateAuthoritiesPageRouteRoute:
certManagerCertificateAuthoritiesPageRouteRoute,
+ certManagerInventoryPageRouteRoute: certManagerInventoryPageRouteRoute,
certManagerDashboardPageRouteRoute: certManagerDashboardPageRouteRoute,
certManagerPoliciesPageRouteRoute: certManagerPoliciesPageRouteRoute,
+ certManagerRequestsPageRouteRoute: certManagerRequestsPageRouteRoute,
certManagerSettingsPageRouteRoute: certManagerSettingsPageRouteRoute,
certManagerDashboardPageRouteIndexRoute:
certManagerDashboardPageRouteIndexRoute,
@@ -4889,6 +5012,8 @@ const certManagerLayoutRouteChildren: certManagerLayoutRouteChildren = {
projectAccessControlPageRouteCertManagerRoute,
projectAppConnectionsPageRouteCertManagerRoute:
projectAppConnectionsPageRouteCertManagerRoute,
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRoute:
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRouteWithChildren,
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApprovalsRoute:
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApprovalsRouteWithChildren,
projectAuditLogsPageRouteCertManagerRoute:
@@ -6078,9 +6203,12 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/projects/ai/$projectId/overview': typeof aiMCPPageRouteRoute
'/organizations/$orgId/projects/ai/$projectId/settings': typeof aiSettingsPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/alerting': typeof certManagerAlertingPageRouteRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/cert-manager-access': typeof certManagerCertManagerAccessPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/certificate-authorities': typeof certManagerCertificateAuthoritiesPageRouteRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/inventory': typeof certManagerInventoryPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/overview': typeof certManagerDashboardPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/policies': typeof certManagerPoliciesPageRouteRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/requests': typeof certManagerRequestsPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/settings': typeof certManagerSettingsPageRouteRoute
'/organizations/$orgId/projects/kms/$projectId/kmip': typeof kmsKmipPageRouteRoute
'/organizations/$orgId/projects/kms/$projectId/overview': typeof kmsOverviewPageRouteRoute
@@ -6104,6 +6232,7 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/projects/ai/$projectId/audit-logs': typeof projectAuditLogsPageRouteAiRoute
'/organizations/$orgId/projects/cert-manager/$projectId/access-management': typeof projectAccessControlPageRouteCertManagerRoute
'/organizations/$orgId/projects/cert-manager/$projectId/app-connections': typeof projectAppConnectionsPageRouteCertManagerRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/applications': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRouteWithChildren
'/organizations/$orgId/projects/cert-manager/$projectId/approvals': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApprovalsRouteWithChildren
'/organizations/$orgId/projects/cert-manager/$projectId/audit-logs': typeof projectAuditLogsPageRouteCertManagerRoute
'/organizations/$orgId/projects/cert-manager/$projectId/certificate-templates': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutCertificateTemplatesRouteWithChildren
@@ -6130,6 +6259,7 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/projects/secret-scanning/$projectId/data-sources': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretScanningProjectIdSecretScanningLayoutDataSourcesRouteWithChildren
'/organizations/$orgId/projects/ssh/$projectId/access-management': typeof projectAccessControlPageRouteSshRoute
'/organizations/$orgId/projects/ssh/$projectId/audit-logs': typeof projectAuditLogsPageRouteSshRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/applications/': typeof certManagerApplicationsPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/approvals/': typeof certManagerApprovalsPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/certificate-templates/': typeof certManagerPkiTemplateListPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/code-signing/': typeof certManagerCodeSigningPageRouteRoute
@@ -6145,6 +6275,7 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/projects/secret-scanning/$projectId/data-sources/': typeof secretScanningSecretScanningDataSourcesPageRouteRoute
'/organizations/$orgId/projects/ai/$projectId/mcp-endpoints/$endpointId': typeof aiMCPEndpointDetailPageRouteRoute
'/organizations/$orgId/projects/ai/$projectId/mcp-servers/$serverId': typeof aiMCPServerDetailPageRouteRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/applications/$applicationName': typeof certManagerApplicationDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/approvals/$approvalRequestId': typeof certManagerApprovalRequestDetailPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/ca/$caId': typeof certManagerCertAuthDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId': typeof certManagerCertificateDetailsByIDPageRouteRoute
@@ -6353,9 +6484,12 @@ export interface FileRoutesByTo {
'/organizations/$orgId/projects/ai/$projectId/overview': typeof aiMCPPageRouteRoute
'/organizations/$orgId/projects/ai/$projectId/settings': typeof aiSettingsPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/alerting': typeof certManagerAlertingPageRouteRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/cert-manager-access': typeof certManagerCertManagerAccessPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/certificate-authorities': typeof certManagerCertificateAuthoritiesPageRouteRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/inventory': typeof certManagerInventoryPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/overview': typeof certManagerDashboardPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/policies': typeof certManagerPoliciesPageRouteRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/requests': typeof certManagerRequestsPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/settings': typeof certManagerSettingsPageRouteRoute
'/organizations/$orgId/projects/kms/$projectId/kmip': typeof kmsKmipPageRouteRoute
'/organizations/$orgId/projects/kms/$projectId/overview': typeof kmsOverviewPageRouteRoute
@@ -6391,6 +6525,7 @@ export interface FileRoutesByTo {
'/organizations/$orgId/projects/secret-scanning/$projectId/audit-logs': typeof projectAuditLogsPageRouteSecretScanningRoute
'/organizations/$orgId/projects/ssh/$projectId/access-management': typeof projectAccessControlPageRouteSshRoute
'/organizations/$orgId/projects/ssh/$projectId/audit-logs': typeof projectAuditLogsPageRouteSshRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/applications': typeof certManagerApplicationsPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/approvals': typeof certManagerApprovalsPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/certificate-templates': typeof certManagerPkiTemplateListPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/code-signing': typeof certManagerCodeSigningPageRouteRoute
@@ -6406,6 +6541,7 @@ export interface FileRoutesByTo {
'/organizations/$orgId/projects/secret-scanning/$projectId/data-sources': typeof secretScanningSecretScanningDataSourcesPageRouteRoute
'/organizations/$orgId/projects/ai/$projectId/mcp-endpoints/$endpointId': typeof aiMCPEndpointDetailPageRouteRoute
'/organizations/$orgId/projects/ai/$projectId/mcp-servers/$serverId': typeof aiMCPServerDetailPageRouteRoute
+ '/organizations/$orgId/projects/cert-manager/$projectId/applications/$applicationName': typeof certManagerApplicationDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/approvals/$approvalRequestId': typeof certManagerApprovalRequestDetailPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/ca/$caId': typeof certManagerCertAuthDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId': typeof certManagerCertificateDetailsByIDPageRouteRoute
@@ -6628,9 +6764,12 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout/overview': typeof aiMCPPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout/settings': typeof aiSettingsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/alerting': typeof certManagerAlertingPageRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/cert-manager-access': typeof certManagerCertManagerAccessPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificate-authorities': typeof certManagerCertificateAuthoritiesPageRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/inventory': typeof certManagerInventoryPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/overview': typeof certManagerDashboardPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/policies': typeof certManagerPoliciesPageRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/requests': typeof certManagerRequestsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/settings': typeof certManagerSettingsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout/kmip': typeof kmsKmipPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout/overview': typeof kmsOverviewPageRouteRoute
@@ -6654,6 +6793,7 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout/audit-logs': typeof projectAuditLogsPageRouteAiRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/access-management': typeof projectAccessControlPageRouteCertManagerRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/app-connections': typeof projectAppConnectionsPageRouteCertManagerRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApplicationsRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutApprovalsRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/audit-logs': typeof projectAuditLogsPageRouteCertManagerRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificate-templates': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdCertManagerLayoutCertificateTemplatesRouteWithChildren
@@ -6680,6 +6820,7 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-scanning/$projectId/_secret-scanning-layout/data-sources': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretScanningProjectIdSecretScanningLayoutDataSourcesRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ssh/$projectId/_ssh-layout/access-management': typeof projectAccessControlPageRouteSshRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ssh/$projectId/_ssh-layout/audit-logs': typeof projectAuditLogsPageRouteSshRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/': typeof certManagerApplicationsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals/': typeof certManagerApprovalsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificate-templates/': typeof certManagerPkiTemplateListPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/code-signing/': typeof certManagerCodeSigningPageRouteRoute
@@ -6695,6 +6836,7 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-scanning/$projectId/_secret-scanning-layout/data-sources/': typeof secretScanningSecretScanningDataSourcesPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout/mcp-endpoints/$endpointId': typeof aiMCPEndpointDetailPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout/mcp-servers/$serverId': typeof aiMCPServerDetailPageRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/$applicationName': typeof certManagerApplicationDetailsByIDPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals/$approvalRequestId': typeof certManagerApprovalRequestDetailPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/ca/$caId': typeof certManagerCertAuthDetailsByIDPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificates/$certificateId': typeof certManagerCertificateDetailsByIDPageRouteRoute
@@ -6912,9 +7054,12 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/ai/$projectId/overview'
| '/organizations/$orgId/projects/ai/$projectId/settings'
| '/organizations/$orgId/projects/cert-manager/$projectId/alerting'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/cert-manager-access'
| '/organizations/$orgId/projects/cert-manager/$projectId/certificate-authorities'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/inventory'
| '/organizations/$orgId/projects/cert-manager/$projectId/overview'
| '/organizations/$orgId/projects/cert-manager/$projectId/policies'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/requests'
| '/organizations/$orgId/projects/cert-manager/$projectId/settings'
| '/organizations/$orgId/projects/kms/$projectId/kmip'
| '/organizations/$orgId/projects/kms/$projectId/overview'
@@ -6938,6 +7083,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/ai/$projectId/audit-logs'
| '/organizations/$orgId/projects/cert-manager/$projectId/access-management'
| '/organizations/$orgId/projects/cert-manager/$projectId/app-connections'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/applications'
| '/organizations/$orgId/projects/cert-manager/$projectId/approvals'
| '/organizations/$orgId/projects/cert-manager/$projectId/audit-logs'
| '/organizations/$orgId/projects/cert-manager/$projectId/certificate-templates'
@@ -6964,6 +7110,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/secret-scanning/$projectId/data-sources'
| '/organizations/$orgId/projects/ssh/$projectId/access-management'
| '/organizations/$orgId/projects/ssh/$projectId/audit-logs'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/applications/'
| '/organizations/$orgId/projects/cert-manager/$projectId/approvals/'
| '/organizations/$orgId/projects/cert-manager/$projectId/certificate-templates/'
| '/organizations/$orgId/projects/cert-manager/$projectId/code-signing/'
@@ -6979,6 +7126,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/secret-scanning/$projectId/data-sources/'
| '/organizations/$orgId/projects/ai/$projectId/mcp-endpoints/$endpointId'
| '/organizations/$orgId/projects/ai/$projectId/mcp-servers/$serverId'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/applications/$applicationName'
| '/organizations/$orgId/projects/cert-manager/$projectId/approvals/$approvalRequestId'
| '/organizations/$orgId/projects/cert-manager/$projectId/ca/$caId'
| '/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId'
@@ -7186,9 +7334,12 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/ai/$projectId/overview'
| '/organizations/$orgId/projects/ai/$projectId/settings'
| '/organizations/$orgId/projects/cert-manager/$projectId/alerting'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/cert-manager-access'
| '/organizations/$orgId/projects/cert-manager/$projectId/certificate-authorities'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/inventory'
| '/organizations/$orgId/projects/cert-manager/$projectId/overview'
| '/organizations/$orgId/projects/cert-manager/$projectId/policies'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/requests'
| '/organizations/$orgId/projects/cert-manager/$projectId/settings'
| '/organizations/$orgId/projects/kms/$projectId/kmip'
| '/organizations/$orgId/projects/kms/$projectId/overview'
@@ -7224,6 +7375,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/secret-scanning/$projectId/audit-logs'
| '/organizations/$orgId/projects/ssh/$projectId/access-management'
| '/organizations/$orgId/projects/ssh/$projectId/audit-logs'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/applications'
| '/organizations/$orgId/projects/cert-manager/$projectId/approvals'
| '/organizations/$orgId/projects/cert-manager/$projectId/certificate-templates'
| '/organizations/$orgId/projects/cert-manager/$projectId/code-signing'
@@ -7239,6 +7391,7 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/secret-scanning/$projectId/data-sources'
| '/organizations/$orgId/projects/ai/$projectId/mcp-endpoints/$endpointId'
| '/organizations/$orgId/projects/ai/$projectId/mcp-servers/$serverId'
+ | '/organizations/$orgId/projects/cert-manager/$projectId/applications/$applicationName'
| '/organizations/$orgId/projects/cert-manager/$projectId/approvals/$approvalRequestId'
| '/organizations/$orgId/projects/cert-manager/$projectId/ca/$caId'
| '/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId'
@@ -7459,9 +7612,12 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout/overview'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout/settings'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/alerting'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/cert-manager-access'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificate-authorities'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/inventory'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/overview'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/policies'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/requests'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/settings'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout/kmip'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId/_kms-layout/overview'
@@ -7485,6 +7641,7 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout/audit-logs'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/access-management'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/app-connections'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/audit-logs'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificate-templates'
@@ -7511,6 +7668,7 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-scanning/$projectId/_secret-scanning-layout/data-sources'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ssh/$projectId/_ssh-layout/access-management'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ssh/$projectId/_ssh-layout/audit-logs'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificate-templates/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/code-signing/'
@@ -7526,6 +7684,7 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-scanning/$projectId/_secret-scanning-layout/data-sources/'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout/mcp-endpoints/$endpointId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout/mcp-servers/$serverId'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/$applicationName'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals/$approvalRequestId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/ca/$caId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificates/$certificateId'
@@ -8164,13 +8323,17 @@ export const routeTree = rootRoute
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId",
"children": [
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/alerting",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/cert-manager-access",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificate-authorities",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/inventory",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/overview",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/policies",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/requests",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/settings",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/access-management",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/app-connections",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/audit-logs",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificate-templates",
@@ -8289,10 +8452,18 @@ export const routeTree = rootRoute
"filePath": "cert-manager/AlertingPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/cert-manager-access": {
+ "filePath": "cert-manager/CertManagerAccessPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/certificate-authorities": {
"filePath": "cert-manager/CertificateAuthoritiesPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/inventory": {
+ "filePath": "cert-manager/InventoryPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/overview": {
"filePath": "cert-manager/DashboardPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout"
@@ -8301,6 +8472,10 @@ export const routeTree = rootRoute
"filePath": "cert-manager/PoliciesPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/requests": {
+ "filePath": "cert-manager/RequestsPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/settings": {
"filePath": "cert-manager/SettingsPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout"
@@ -8393,6 +8568,14 @@ export const routeTree = rootRoute
"filePath": "project/AppConnectionsPage/route-cert-manager.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications": {
+ "filePath": "",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout",
+ "children": [
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/",
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/$applicationName"
+ ]
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals": {
"filePath": "",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout",
@@ -8625,6 +8808,10 @@ export const routeTree = rootRoute
"filePath": "project/AuditLogsPage/route-ssh.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ssh/$projectId/_ssh-layout"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/": {
+ "filePath": "cert-manager/ApplicationsPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals/": {
"filePath": "cert-manager/ApprovalsPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals"
@@ -8685,6 +8872,10 @@ export const routeTree = rootRoute
"filePath": "ai/MCPServerDetailPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId/_ai-layout"
},
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications/$applicationName": {
+ "filePath": "cert-manager/ApplicationDetailsByIDPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/applications"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals/$approvalRequestId": {
"filePath": "cert-manager/ApprovalRequestDetailPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/approvals"
diff --git a/frontend/src/routes.ts b/frontend/src/routes.ts
index 126361ec59..46420e32cd 100644
--- a/frontend/src/routes.ts
+++ b/frontend/src/routes.ts
@@ -277,6 +277,7 @@ const certManagerRoutes = route("/organizations/$orgId/projects/cert-manager/$pr
index("cert-manager/DashboardPage/route-index.tsx"),
route("/overview", "cert-manager/DashboardPage/route.tsx"),
route("/policies", "cert-manager/PoliciesPage/route.tsx"),
+ route("/inventory", "cert-manager/InventoryPage/route.tsx"),
route("/subscribers", [
index("cert-manager/PkiSubscribersPage/route.tsx"),
route("/$subscriberName", "cert-manager/PkiSubscriberDetailsByIDPage/route.tsx")
@@ -289,6 +290,12 @@ const certManagerRoutes = route("/organizations/$orgId/projects/cert-manager/$pr
route("/installations/$installationId", "cert-manager/InstallationDetailsByIDPage/route.tsx")
]),
route("/alerting", "cert-manager/AlertingPage/route.tsx"),
+ route("/applications", [
+ index("cert-manager/ApplicationsPage/route.tsx"),
+ route("/$applicationName", "cert-manager/ApplicationDetailsByIDPage/route.tsx")
+ ]),
+ route("/requests", "cert-manager/RequestsPage/route.tsx"),
+ route("/cert-manager-access", "cert-manager/CertManagerAccessPage/route.tsx"),
route("/code-signing", [
index("cert-manager/CodeSigningPage/route.tsx"),
route("/$signerId", "cert-manager/SignerDetailPage/route.tsx")
diff --git a/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx b/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx
index 2ff6e758c1..78766b9672 100644
--- a/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx
+++ b/frontend/src/views/PkiAlertsV2Page/PkiAlertsV2Page.tsx
@@ -1,10 +1,9 @@
import { useState } from "react";
-import { faPlus, faSearch } from "@fortawesome/free-solid-svg-icons";
+import { faSearch } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { createNotification } from "@app/components/notifications";
import {
- Button,
DeleteActionModal,
Input,
Pagination,
@@ -17,7 +16,6 @@ import {
THead,
Tr
} from "@app/components/v2";
-import { useProject } from "@app/context";
import { useDebounce } from "@app/hooks";
import { useDeletePkiAlertV2, useGetPkiAlertsV2 } from "@app/hooks/api/pkiAlertsV2";
@@ -30,7 +28,6 @@ interface Props {
}
export const PkiAlertsV2Page = ({ hideContainer = false }: Props) => {
- const { currentProject } = useProject();
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(25);
const [search, setSearch] = useState("");
@@ -51,7 +48,6 @@ export const PkiAlertsV2Page = ({ hideContainer = false }: Props) => {
});
const { data: alertsData, isLoading } = useGetPkiAlertsV2({
- projectId: currentProject?.id || "",
search: debouncedSearch || undefined,
limit: perPage,
offset: (page - 1) * perPage
@@ -136,15 +132,15 @@ export const PkiAlertsV2Page = ({ hideContainer = false }: Props) => {
<div className={hideContainer ? "" : "container mx-auto p-6"}>
<div className="flex w-full flex-col gap-3 rounded-lg border border-mineshaft-600 bg-mineshaft-900 px-4 py-3">
<div className="flex items-center justify-between border-b border-mineshaft-400 pb-2">
- <h3 className="text-lg font-medium text-mineshaft-100">Certificate Alerts</h3>
- <Button
- variant="solid"
- colorSchema="primary"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={() => setAlertModal({ isOpen: true })}
- >
- Create Certificate Alert
- </Button>
+ <div className="flex items-center gap-x-2">
+ <h3 className="text-lg font-medium text-mineshaft-100">Certificate Alerts</h3>
+ <span className="rounded bg-mineshaft-600 px-2 py-0.5 text-xs tracking-wide text-mineshaft-200 uppercase">
+ Legacy
+ </span>
+ </div>
+ <p className="text-xs text-bunker-300">
+ Create new alerts inside a Cert Manager Application.
+ </p>
</div>
<div className="mb-4 flex items-center">
diff --git a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx
index 8e30b53062..5ecfe8b8cc 100644
--- a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx
+++ b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2FormSteps.tsx
@@ -81,6 +81,7 @@ interface CreatePkiAlertV2FormStepsProps {
expandedChannel: string | undefined;
setExpandedChannel: (channel: string | undefined) => void;
showPreview?: boolean;
+ showFilters?: boolean;
}
type ChannelUIState = {
@@ -95,7 +96,8 @@ type ChannelUIState = {
export const CreatePkiAlertV2FormSteps = ({
expandedChannel,
setExpandedChannel,
- showPreview = true
+ showPreview = true,
+ showFilters = true
}: CreatePkiAlertV2FormStepsProps) => {
const {
control,
@@ -141,7 +143,6 @@ export const CreatePkiAlertV2FormSteps = ({
const { data: currentCertificatesData, isLoading: isLoadingCurrentCertificates } =
useGetPkiAlertV2CurrentMatchingCertificates(
{
- projectId: currentProject?.id || "",
filters: watchedFilters || [],
...(watchedEventType === PkiAlertEventTypeV2.EXPIRATION
? { alertBefore: watchedAlertBefore || "30d" }
@@ -263,7 +264,6 @@ export const CreatePkiAlertV2FormSteps = ({
try {
const result = await testWebhookConfig({
- projectId: currentProject.id,
url: webhookConfig.url,
signingSecret: webhookConfig.signingSecret || undefined
});
@@ -433,153 +433,157 @@ export const CreatePkiAlertV2FormSteps = ({
</div>
</Tab.Panel>
- <Tab.Panel>
- <div className="space-y-6">
- <p className="mb-4 text-sm text-bunker-300">
- Add filter rules to specify which certificates should trigger this alert. Leave empty to
- monitor all certificates.
- </p>
-
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <FormLabel label="Certificate Filter Rules" />
- <Button
- type="button"
- variant="outline_bg"
- size="sm"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={addFilter}
- >
- Add Filter
- </Button>
- </div>
+ {showFilters && (
+ <Tab.Panel>
+ <div className="space-y-6">
+ <p className="mb-4 text-sm text-bunker-300">
+ Add filter rules to specify which certificates should trigger this alert. Leave empty
+ to monitor all certificates.
+ </p>
- {watchedFilters?.map((filter, index) => (
- <div
- key={`filter-${index}`}
- className="space-y-2 rounded-md border border-mineshaft-600 p-3"
- >
- <div className="flex items-center justify-between">
- <h4 className="text-sm font-medium text-mineshaft-100">
- Filter Rule #{index + 1}
- </h4>
- <IconButton
- size="sm"
- variant="plain"
- colorSchema="danger"
- ariaLabel="Remove filter"
- onClick={() => removeFilter(index)}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- </div>
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <FormLabel label="Certificate Filter Rules" />
+ <Button
+ type="button"
+ variant="outline_bg"
+ size="sm"
+ leftIcon={<FontAwesomeIcon icon={faPlus} />}
+ onClick={addFilter}
+ >
+ Add Filter
+ </Button>
+ </div>
- <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
- <div className="md:col-span-1">
- <FormControl label="Field">
- <Select
- value={filter.field}
- onValueChange={(value) =>
- updateFilter(index, {
- field: value as PkiFilterFieldV2,
- operator:
- value === PkiFilterFieldV2.INCLUDE_CAS
- ? PkiFilterOperatorV2.EQUALS
- : filter.operator,
- value: isValueBoolean(value as PkiFilterFieldV2) ? false : ""
- })
- }
- className="w-full min-w-[200px]"
- >
- <SelectItem value={PkiFilterFieldV2.COMMON_NAME}>Common Name</SelectItem>
- <SelectItem value={PkiFilterFieldV2.PROFILE_NAME}>Profile Name</SelectItem>
- <SelectItem value={PkiFilterFieldV2.SAN}>
- Subject Alternative Names
- </SelectItem>
- <SelectItem value={PkiFilterFieldV2.INCLUDE_CAS}>
- Include Certificate Authorities
- </SelectItem>
- </Select>
- </FormControl>
+ {watchedFilters?.map((filter, index) => (
+ <div
+ key={`filter-${index}`}
+ className="space-y-2 rounded-md border border-mineshaft-600 p-3"
+ >
+ <div className="flex items-center justify-between">
+ <h4 className="text-sm font-medium text-mineshaft-100">
+ Filter Rule #{index + 1}
+ </h4>
+ <IconButton
+ size="sm"
+ variant="plain"
+ colorSchema="danger"
+ ariaLabel="Remove filter"
+ onClick={() => removeFilter(index)}
+ >
+ <FontAwesomeIcon icon={faTrash} />
+ </IconButton>
</div>
- <div className="md:col-span-1">
- <FormControl label="Operator">
- <Select
- value={filter.operator}
- onValueChange={(value) =>
- updateFilter(index, { operator: value as PkiFilterOperatorV2 })
- }
- className="w-full min-w-[140px]"
- >
- {getFieldOperators(filter.field).map((operator) => (
- <SelectItem key={operator} value={operator}>
- {operator
- .replace(/_/g, " ")
- .toLowerCase()
- .replace(/\b\w/g, (l) => l.toUpperCase())}
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
+ <div className="md:col-span-1">
+ <FormControl label="Field">
+ <Select
+ value={filter.field}
+ onValueChange={(value) =>
+ updateFilter(index, {
+ field: value as PkiFilterFieldV2,
+ operator:
+ value === PkiFilterFieldV2.INCLUDE_CAS
+ ? PkiFilterOperatorV2.EQUALS
+ : filter.operator,
+ value: isValueBoolean(value as PkiFilterFieldV2) ? false : ""
+ })
+ }
+ className="w-full min-w-[200px]"
+ >
+ <SelectItem value={PkiFilterFieldV2.COMMON_NAME}>Common Name</SelectItem>
+ <SelectItem value={PkiFilterFieldV2.PROFILE_NAME}>
+ Profile Name
</SelectItem>
- ))}
- </Select>
- </FormControl>
- </div>
+ <SelectItem value={PkiFilterFieldV2.SAN}>
+ Subject Alternative Names
+ </SelectItem>
+ <SelectItem value={PkiFilterFieldV2.INCLUDE_CAS}>
+ Include Certificate Authorities
+ </SelectItem>
+ </Select>
+ </FormControl>
+ </div>
- <div className="md:col-span-1">
- <FormControl label="Value">
- {isValueBoolean(filter.field) ? (
+ <div className="md:col-span-1">
+ <FormControl label="Operator">
<Select
- value={String(filter.value)}
+ value={filter.operator}
onValueChange={(value) =>
- updateFilter(index, { value: value === "true" })
+ updateFilter(index, { operator: value as PkiFilterOperatorV2 })
}
- className="w-full"
+ className="w-full min-w-[140px]"
>
- <SelectItem value="true">Yes</SelectItem>
- <SelectItem value="false">No</SelectItem>
+ {getFieldOperators(filter.field).map((operator) => (
+ <SelectItem key={operator} value={operator}>
+ {operator
+ .replace(/_/g, " ")
+ .toLowerCase()
+ .replace(/\b\w/g, (l) => l.toUpperCase())}
+ </SelectItem>
+ ))}
</Select>
- ) : (
- <Input
- value={
- Array.isArray(filter.value)
- ? filter.value.join(", ")
- : String(filter.value || "")
- }
- onChange={(e) => {
- const { value } = e.target;
- updateFilter(index, { value });
- }}
- onBlur={(e) => {
- const { value } = e.target;
- if (canOperatorTakeArray(filter.operator) && value.includes(",")) {
- const finalValue = value
- .split(",")
- .map((v) => v.trim())
- .filter(Boolean);
- updateFilter(index, { value: finalValue });
+ </FormControl>
+ </div>
+
+ <div className="md:col-span-1">
+ <FormControl label="Value">
+ {isValueBoolean(filter.field) ? (
+ <Select
+ value={String(filter.value)}
+ onValueChange={(value) =>
+ updateFilter(index, { value: value === "true" })
}
- }}
- placeholder={
- canOperatorTakeArray(filter.operator)
- ? "example.com, test.com"
- : "example.com"
- }
- className="w-full"
- />
- )}
- </FormControl>
+ className="w-full"
+ >
+ <SelectItem value="true">Yes</SelectItem>
+ <SelectItem value="false">No</SelectItem>
+ </Select>
+ ) : (
+ <Input
+ value={
+ Array.isArray(filter.value)
+ ? filter.value.join(", ")
+ : String(filter.value || "")
+ }
+ onChange={(e) => {
+ const { value } = e.target;
+ updateFilter(index, { value });
+ }}
+ onBlur={(e) => {
+ const { value } = e.target;
+ if (canOperatorTakeArray(filter.operator) && value.includes(",")) {
+ const finalValue = value
+ .split(",")
+ .map((v) => v.trim())
+ .filter(Boolean);
+ updateFilter(index, { value: finalValue });
+ }
+ }}
+ placeholder={
+ canOperatorTakeArray(filter.operator)
+ ? "example.com, test.com"
+ : "example.com"
+ }
+ className="w-full"
+ />
+ )}
+ </FormControl>
+ </div>
</div>
</div>
- </div>
- ))}
+ ))}
- {(!watchedFilters || watchedFilters.length === 0) && (
- <div className="py-8 text-center text-bunker-400">
- No filter rules configured. This alert will monitor all certificates.
- </div>
- )}
+ {(!watchedFilters || watchedFilters.length === 0) && (
+ <div className="py-8 text-center text-bunker-400">
+ No filter rules configured. This alert will monitor all certificates.
+ </div>
+ )}
+ </div>
</div>
- </div>
- </Tab.Panel>
+ </Tab.Panel>
+ )}
{showPreview && (
<Tab.Panel>
@@ -704,7 +708,7 @@ export const CreatePkiAlertV2FormSteps = ({
Add Channel
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="end" sideOffset={4}>
+ <DropdownMenuContent align="end" sideOffset={4} className="z-[70]">
<DropdownMenuItem onClick={() => addChannel(PkiAlertChannelTypeV2.EMAIL)}>
<FontAwesomeIcon icon={faEnvelope} className="mr-2" />
Email
@@ -1006,34 +1010,36 @@ export const CreatePkiAlertV2FormSteps = ({
</div>
</div>
- <div className="flex flex-col gap-3">
- <div className="w-full border-b border-mineshaft-600">
- <span className="text-sm text-mineshaft-300">Filter Rules</span>
- </div>
- <div className="flex flex-wrap gap-x-8 gap-y-2">
- {watchedFilters && watchedFilters.length > 0 ? (
- watchedFilters.map((filter, index) => (
- <GenericFieldLabel key={`review-filter-${index}`} label={`Rule ${index + 1}`}>
- <span className="font-mono text-xs">
- {filter.field
- .replace(/_/g, " ")
- .toLowerCase()
- .replace(/\b\w/g, (l) => l.toUpperCase())}{" "}
- {filter.operator
- .replace(/_/g, " ")
- .toLowerCase()
- .replace(/\b\w/g, (l) => l.toUpperCase())}{" "}
- &quot;{String(filter.value)}&quot;
- </span>
- </GenericFieldLabel>
- ))
- ) : (
- <span className="text-bunker-400">
- No filter rules - will monitor all certificates
- </span>
- )}
+ {showFilters && (
+ <div className="flex flex-col gap-3">
+ <div className="w-full border-b border-mineshaft-600">
+ <span className="text-sm text-mineshaft-300">Filter Rules</span>
+ </div>
+ <div className="flex flex-wrap gap-x-8 gap-y-2">
+ {watchedFilters && watchedFilters.length > 0 ? (
+ watchedFilters.map((filter, index) => (
+ <GenericFieldLabel key={`review-filter-${index}`} label={`Rule ${index + 1}`}>
+ <span className="font-mono text-xs">
+ {filter.field
+ .replace(/_/g, " ")
+ .toLowerCase()
+ .replace(/\b\w/g, (l) => l.toUpperCase())}{" "}
+ {filter.operator
+ .replace(/_/g, " ")
+ .toLowerCase()
+ .replace(/\b\w/g, (l) => l.toUpperCase())}{" "}
+ &quot;{String(filter.value)}&quot;
+ </span>
+ </GenericFieldLabel>
+ ))
+ ) : (
+ <span className="text-bunker-400">
+ No filter rules - will monitor all certificates
+ </span>
+ )}
+ </div>
</div>
- </div>
+ )}
<div className="flex flex-col gap-3">
<div className="w-full border-b border-mineshaft-600">
diff --git a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx
index f32a081a9e..50bca37173 100644
--- a/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx
+++ b/frontend/src/views/PkiAlertsV2Page/components/CreatePkiAlertV2Modal.tsx
@@ -31,6 +31,7 @@ interface Props {
onOpenChange: (isOpen: boolean) => void;
alertToEdit?: TPkiAlertV2;
alertId?: string;
+ applicationId?: string;
}
type TFormData = TCreatePkiAlertV2;
@@ -60,7 +61,21 @@ const TABS_WITHOUT_PREVIEW: TFormTab[] = [
{ name: "Review", key: "review", fields: [] }
];
-const hasPreviewTab = (eventType?: PkiAlertEventTypeV2): boolean => {
+const TABS_APPLICATION_SCOPED: TFormTab[] = [
+ {
+ name: "Details",
+ key: "basicInfo",
+ fields: ["eventType", "name", "description", "alertBefore", "notificationConfig"]
+ },
+ { name: "Channels", key: "channels", fields: ["channels"] },
+ { name: "Review", key: "review", fields: [] }
+];
+
+const hasPreviewTab = (
+ eventType: PkiAlertEventTypeV2 | undefined,
+ applicationScoped: boolean
+): boolean => {
+ if (applicationScoped) return false;
return (
!eventType ||
eventType === PkiAlertEventTypeV2.EXPIRATION ||
@@ -69,18 +84,30 @@ const hasPreviewTab = (eventType?: PkiAlertEventTypeV2): boolean => {
);
};
-const getFormTabs = (eventType?: PkiAlertEventTypeV2): TFormTab[] => {
- if (hasPreviewTab(eventType)) {
- return TABS_WITH_PREVIEW;
- }
+const getFormTabs = (
+ eventType: PkiAlertEventTypeV2 | undefined,
+ applicationScoped: boolean
+): TFormTab[] => {
+ if (applicationScoped) return TABS_APPLICATION_SCOPED;
+ if (hasPreviewTab(eventType, false)) return TABS_WITH_PREVIEW;
return TABS_WITHOUT_PREVIEW;
};
-const getChannelsTabIndex = (eventType?: PkiAlertEventTypeV2): number => {
- return hasPreviewTab(eventType) ? 3 : 2;
+const getChannelsTabIndex = (
+ eventType: PkiAlertEventTypeV2 | undefined,
+ applicationScoped: boolean
+): number => {
+ if (applicationScoped) return 1;
+ return hasPreviewTab(eventType, false) ? 3 : 2;
};
-export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alertId }: Props) => {
+export const CreatePkiAlertV2Modal = ({
+ isOpen,
+ onOpenChange,
+ alertToEdit,
+ alertId,
+ applicationId
+}: Props) => {
const { currentProject } = useProject();
const [selectedTabIndex, setSelectedTabIndex] = useState(0);
const [expandedChannel, setExpandedChannel] = useState<string | undefined>(undefined);
@@ -96,7 +123,6 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
const formMethods = useForm<TFormData>({
resolver: zodResolver(isEditing ? updatePkiAlertV2Schema : createPkiAlertV2Schema),
defaultValues: {
- projectId: currentProject?.id || "",
name: "",
description: "",
eventType: PkiAlertEventTypeV2.EXPIRATION,
@@ -118,8 +144,9 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
} = formMethods;
const watchedEventType = watch("eventType");
- const formTabs = getFormTabs(watchedEventType);
- const channelsTabIndex = getChannelsTabIndex(watchedEventType);
+ const applicationScoped = !!applicationId;
+ const formTabs = getFormTabs(watchedEventType, applicationScoped);
+ const channelsTabIndex = getChannelsTabIndex(watchedEventType, applicationScoped);
useEffect(() => {
if (selectedTabIndex >= formTabs.length) {
@@ -140,7 +167,6 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
React.useEffect(() => {
if (editingAlert && isEditing) {
reset({
- projectId: currentProject?.id || "",
name: editingAlert.name,
description: editingAlert.description || "",
eventType: editingAlert.eventType,
@@ -175,7 +201,6 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
});
} else if (!isEditing) {
reset({
- projectId: currentProject?.id || "",
name: "",
description: "",
eventType: PkiAlertEventTypeV2.EXPIRATION,
@@ -240,7 +265,7 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
} else {
await createAlert({
...processedData,
- projectId: currentProject.id
+ ...(applicationId && { applicationId })
});
}
@@ -317,7 +342,7 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
<form
className={twMerge(
"flex flex-col",
- hasPreviewTab(watchedEventType) ? "min-h-[60vh]" : "min-h-[40vh]",
+ hasPreviewTab(watchedEventType, applicationScoped) ? "min-h-[60vh]" : "min-h-[40vh]",
isFinalStep && "max-h-[70vh] overflow-y-auto"
)}
>
@@ -349,7 +374,8 @@ export const CreatePkiAlertV2Modal = ({ isOpen, onOpenChange, alertToEdit, alert
<CreatePkiAlertV2FormSteps
expandedChannel={expandedChannel}
setExpandedChannel={setExpandedChannel}
- showPreview={hasPreviewTab(watchedEventType)}
+ showPreview={hasPreviewTab(watchedEventType, applicationScoped)}
+ showFilters={!applicationScoped}
/>
</Tab.Panels>
</Tab.Group>