Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Address initial comments and improvements
Carlos Monastyrski2251b5626cc4
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex b1198575fd..0c2a14bebf 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -257,7 +257,7 @@ declare module "fastify" {name: string;};auditLogInfo: Pick<TCreateAuditLogDTO, "userAgent" | "userAgentType" | "ipAddress" | "actor" | "orgId">;- certManagerProjectId: string;+ internalCertManagerProjectId: string;ssoConfig: Awaited<ReturnType<TSamlConfigServiceFactory["getSaml"]>>;ldapConfig: Awaited<ReturnType<TLdapConfigServiceFactory["getLdapCfg"]>> & {allowedFields?: TAllowedFields[];diff --git a/backend/src/db/migrations/20260504432352_cert-manager-applications.ts b/backend/src/db/migrations/20260504432352_cert-manager-applications.tsindex 9b4573cdc3..bdd12a0453 100644--- a/backend/src/db/migrations/20260504432352_cert-manager-applications.ts+++ b/backend/src/db/migrations/20260504432352_cert-manager-applications.ts@@ -206,19 +206,19 @@ export async function up(knex: Knex): Promise<void> {});}- if (!(await knex.schema.hasColumn(TableName.ApprovalPolicies, "applicationId"))) {+ if (!(await knex.schema.hasColumn(TableName.ApprovalPolicies, "scopeType"))) {await knex.schema.alterTable(TableName.ApprovalPolicies, (t) => {- t.uuid("applicationId").nullable();- t.foreign("applicationId").references("id").inTable(TableName.PkiApplication).onDelete("CASCADE");- t.index("applicationId");+ t.string("scopeType").nullable();+ t.uuid("scopeId").nullable();+ t.index(["scopeType", "scopeId"]);});}- if (!(await knex.schema.hasColumn(TableName.ApprovalRequests, "applicationId"))) {+ if (!(await knex.schema.hasColumn(TableName.ApprovalRequests, "scopeType"))) {await knex.schema.alterTable(TableName.ApprovalRequests, (t) => {- t.uuid("applicationId").nullable();- t.foreign("applicationId").references("id").inTable(TableName.PkiApplication).onDelete("CASCADE");- t.index("applicationId");+ t.string("scopeType").nullable();+ t.uuid("scopeId").nullable();+ t.index(["scopeType", "scopeId"]);});}@@ -323,17 +323,17 @@ export async function down(knex: Knex): Promise<void> {});}- if (await knex.schema.hasColumn(TableName.ApprovalRequests, "applicationId")) {+ if (await knex.schema.hasColumn(TableName.ApprovalRequests, "scopeType")) {await knex.schema.alterTable(TableName.ApprovalRequests, (t) => {- t.dropForeign(["applicationId"]);- t.dropColumn("applicationId");+ t.dropColumn("scopeType");+ t.dropColumn("scopeId");});}- if (await knex.schema.hasColumn(TableName.ApprovalPolicies, "applicationId")) {+ if (await knex.schema.hasColumn(TableName.ApprovalPolicies, "scopeType")) {await knex.schema.alterTable(TableName.ApprovalPolicies, (t) => {- t.dropForeign(["applicationId"]);- t.dropColumn("applicationId");+ t.dropColumn("scopeType");+ t.dropColumn("scopeId");});}diff --git a/backend/src/db/schemas/approval-policies.ts b/backend/src/db/schemas/approval-policies.tsindex 1fc33caf95..3e1c5ed053 100644--- a/backend/src/db/schemas/approval-policies.ts+++ b/backend/src/db/schemas/approval-policies.ts@@ -20,7 +20,8 @@ export const ApprovalPoliciesSchema = z.object({createdAt: z.date(),updatedAt: z.date(),bypassForMachineIdentities: z.boolean().default(false).nullable().optional(),- applicationId: z.string().uuid().nullable().optional()+ scopeType: z.string().nullable().optional(),+ scopeId: 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.tsindex 7da89eee22..3dccd7687e 100644--- a/backend/src/db/schemas/approval-requests.ts+++ b/backend/src/db/schemas/approval-requests.ts@@ -24,7 +24,8 @@ export const ApprovalRequestsSchema = z.object({createdAt: z.date(),updatedAt: z.date(),machineIdentityId: z.string().uuid().nullable().optional(),- applicationId: z.string().uuid().nullable().optional()+ scopeType: z.string().nullable().optional(),+ scopeId: z.string().uuid().nullable().optional()});export type TApprovalRequests = z.infer<typeof ApprovalRequestsSchema>;diff --git a/backend/src/ee/routes/scep/pki-scep-router.ts b/backend/src/ee/routes/scep/pki-scep-router.tsindex e855918608..97778633ed 100644--- a/backend/src/ee/routes/scep/pki-scep-router.ts+++ b/backend/src/ee/routes/scep/pki-scep-router.ts@@ -1,6 +1,7 @@import { z } from "zod";import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { ScepOperation } from "@app/ee/services/pki-scep/pki-scep-types";import { BadRequestError } from "@app/lib/errors";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";@@ -49,19 +50,19 @@ export const registerPkiScepRouter = async (server: FastifyZodProvider) => {const { operation, message: messageBase64 } = req.query;switch (operation) {- case "GetCACaps": {+ case ScepOperation.GetCACaps: {const caps = await server.services.pkiScep.getCaCaps({ profileId });void res.header("Content-Type", "text/plain");return caps;}- case "GetCACert": {+ case ScepOperation.GetCACert: {const certBundle = await server.services.pkiScep.getCaCert({ profileId });void res.header("Content-Type", "application/x-x509-ca-ra-cert");return res.send(certBundle);}- case "PKIOperation": {+ case ScepOperation.PKIOperation: {if (!messageBase64) {throw new BadRequestError({ message: "Missing message parameter for PKIOperation" });}@@ -222,17 +223,17 @@ export const registerPkiScepRouter = async (server: FastifyZodProvider) => {const { operation, message: messageBase64 } = req.query;switch (operation) {- case "GetCACaps": {+ case ScepOperation.GetCACaps: {const caps = await server.services.pkiScep.getCaCaps({ profileId, applicationId });void res.header("Content-Type", "text/plain");return caps;}- case "GetCACert": {+ case ScepOperation.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": {+ case ScepOperation.PKIOperation: {if (!messageBase64) {throw new BadRequestError({ message: "Missing message parameter for PKIOperation" });}diff --git a/backend/src/ee/routes/v1/pki-discovery-router.ts b/backend/src/ee/routes/v1/pki-discovery-router.tsindex d0ff39b673..0df62004ed 100644--- a/backend/src/ee/routes/v1/pki-discovery-router.ts+++ b/backend/src/ee/routes/v1/pki-discovery-router.ts@@ -75,6 +75,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>operationId: "createPkiDiscovery",description: "Create a new PKI discovery configuration",body: z.object({+ projectId: z.string().optional().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@@ -102,7 +103,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>throw new BadRequestError({ message: validation.error || "Invalid target configuration" });}- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const discovery = await server.services.pkiDiscovery.createDiscovery({projectId,name: req.body.name,@@ -147,6 +148,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>operationId: "listPkiDiscoveries",description: "List PKI discovery configurations for a project",querystring: z.object({+ projectId: z.string().optional().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")@@ -164,7 +166,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>}},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { discoveries, totalCount } = await server.services.pkiDiscovery.listDiscoveries({projectId,offset: req.query.offset,diff --git a/backend/src/ee/routes/v1/pki-installation-router.ts b/backend/src/ee/routes/v1/pki-installation-router.tsindex fa6959778f..0c0c961831 100644--- a/backend/src/ee/routes/v1/pki-installation-router.ts+++ b/backend/src/ee/routes/v1/pki-installation-router.ts@@ -21,6 +21,7 @@ export const registerPkiInstallationRouter = async (server: FastifyZodProvider)operationId: "listPkiInstallations",description: "List PKI certificate installations for a project",querystring: z.object({+ projectId: z.string().optional().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"),@@ -41,7 +42,7 @@ export const registerPkiInstallationRouter = async (server: FastifyZodProvider)}},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { installations, totalCount } = await server.services.pkiInstallation.listInstallations({projectId,discoveryId: req.query.discoveryId,diff --git a/backend/src/ee/services/pki-scep/pki-scep-types.ts b/backend/src/ee/services/pki-scep/pki-scep-types.tsindex 57897cfb69..7cc456c204 100644--- a/backend/src/ee/services/pki-scep/pki-scep-types.ts+++ b/backend/src/ee/services/pki-scep/pki-scep-types.ts@@ -1,5 +1,11 @@import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";+export enum ScepOperation {+ GetCACaps = "GetCACaps",+ GetCACert = "GetCACert",+ PKIOperation = "PKIOperation"+}+export enum ScepMessageType {CertRep = "3",RenewalReq = "17",diff --git a/backend/src/server/plugins/inject-cert-manager-project-id.ts b/backend/src/server/plugins/inject-cert-manager-project-id.tsindex 8af268bbb1..cb9d2569e0 100644--- a/backend/src/server/plugins/inject-cert-manager-project-id.ts+++ b/backend/src/server/plugins/inject-cert-manager-project-id.ts@@ -1,10 +1,20 @@import { FastifyPluginAsync } from "fastify";import fp from "fastify-plugin";+import { BadRequestError } from "@app/lib/errors";+const CERT_MANAGER_PREFIXES = ["/api/v1/cert-manager/", "/api/v1/pki/", "/api/v2/pki/"];+const readProjectIdFromRequest = (req: { query?: unknown; body?: unknown }): string | null => {+ const fromQuery = (req.query as { projectId?: unknown } | undefined)?.projectId;+ if (typeof fromQuery === "string" && fromQuery.length > 0) return fromQuery;+ const fromBody = (req.body as { projectId?: unknown } | undefined)?.projectId;+ if (typeof fromBody === "string" && fromBody.length > 0) return fromBody;+ return null;+};+export const injectCertManagerProjectId: FastifyPluginAsync = fp(async (server) => {- server.decorateRequest("certManagerProjectId", "");+ server.decorateRequest("internalCertManagerProjectId", "");server.addHook("preValidation", async (req) => {if (!req.permission?.orgId) return;@@ -16,6 +26,18 @@ export const injectCertManagerProjectId: FastifyPluginAsync = fp(async (server)return;}- req.certManagerProjectId = await server.services.certManagerProjectResolver.resolve(req.permission.orgId);+ const explicit = readProjectIdFromRequest(req);+ if (explicit) {+ const isCertManager = await server.services.certManagerProjectResolver.isCertManagerProject(explicit);+ if (!isCertManager) {+ throw new BadRequestError({+ message: "The supplied projectId does not reference a Cert Manager project."+ });+ }+ req.internalCertManagerProjectId = explicit;+ return;+ }++ req.internalCertManagerProjectId = await server.services.certManagerProjectResolver.resolve(req.permission.orgId);});});diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex e61ffd6e8b..8a7daf0ca8 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -1330,6 +1330,10 @@ export const registerRoutes = async (const gatewayPoolMembershipDAL = gatewayPoolMembershipDalFactory(db);const approvalPolicyDAL = approvalPolicyDALFactory(db);+ const approvalRequestDAL = approvalRequestDALFactory(db);+ const approvalRequestGrantsDAL = approvalRequestGrantsDALFactory(db);+ const approvalRequestStepsDAL = approvalRequestStepsDALFactory(db);+ const approvalRequestStepEligibleApproversDAL = approvalRequestStepEligibleApproversDALFactory(db);const orgGatewayConfigV2DAL = orgGatewayConfigV2DalFactory(db);@@ -1432,6 +1436,8 @@ export const registerRoutes = async (pkiApplicationProfileDAL,membershipDAL,membershipRoleDAL,+ approvalPolicyDAL,+ approvalRequestDAL,permissionService});@@ -2257,11 +2263,6 @@ export const registerRoutes = async (licenseService});- const approvalRequestDAL = approvalRequestDALFactory(db);- const approvalRequestGrantsDAL = approvalRequestGrantsDALFactory(db);- const approvalRequestStepsDAL = approvalRequestStepsDALFactory(db);- const approvalRequestStepEligibleApproversDAL = approvalRequestStepEligibleApproversDALFactory(db);-// DAILYconst dailyResourceCleanUp = dailyResourceCleanUpQueueServiceFactory({scimService,@@ -2737,6 +2738,7 @@ export const registerRoutes = async (permissionService,projectMembershipDAL,membershipDAL,+ pkiApplicationDAL,approvalRequestDAL,approvalRequestStepsDAL,approvalRequestStepEligibleApproversDAL,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.tsindex a48271b62c..a2bc7593c2 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@@ -4,7 +4,7 @@ import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { BadRequestError } from "@app/lib/errors";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";-import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";+import { ApprovalPolicyScope, ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";import {TApprovalPolicyInputs,TCreatePolicyDTO,@@ -109,8 +109,8 @@ export const registerApprovalPolicyEndpoints = ({operationId: "listApprovalPolicies",description: "List approval policies",querystring: z.object({- projectId: z.string().uuid(),- applicationId: z.string().uuid().optional()+ scope: z.nativeEnum(ApprovalPolicyScope),+ id: z.string().uuid()}),response: {200: z.object({@@ -120,14 +120,17 @@ export const registerApprovalPolicyEndpoints = ({},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- const { policies } = await server.services.approvalPolicy.list(policyType, req.query.projectId, req.permission, {- applicationId: req.query.applicationId- });+ const { policies, projectId } = await server.services.approvalPolicy.list(+ policyType,+ req.query.scope,+ req.query.id,+ req.permission+ );await server.services.auditLog.createAuditLog({...req.auditLogInfo,orgId: req.permission.orgId,- projectId: req.query.projectId,+ projectId,event: {type: EventType.APPROVAL_POLICY_LIST,metadata: {@@ -279,8 +282,8 @@ export const registerApprovalPolicyEndpoints = ({operationId: "listApprovalRequests",description: "List approval requests",querystring: z.object({- projectId: z.string().uuid(),- applicationId: z.string().uuid().optional()+ scope: z.nativeEnum(ApprovalPolicyScope),+ id: z.string().uuid()}),response: {200: z.object({@@ -290,17 +293,17 @@ export const registerApprovalPolicyEndpoints = ({},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- const { requests } = await server.services.approvalPolicy.listRequests(+ const { requests, projectId } = await server.services.approvalPolicy.listRequests(policyType,- req.query.projectId,- req.permission,- { applicationId: req.query.applicationId }+ req.query.scope,+ req.query.id,+ req.permission);await server.services.auditLog.createAuditLog({...req.auditLogInfo,orgId: req.permission.orgId,- projectId: req.query.projectId,+ projectId,event: {type: EventType.APPROVAL_REQUEST_LIST,metadata: {@@ -560,7 +563,8 @@ export const registerApprovalPolicyEndpoints = ({operationId: "listApprovalGrants",description: "List approval grants",querystring: z.object({- projectId: z.string().uuid()+ scope: z.nativeEnum(ApprovalPolicyScope),+ id: z.string().uuid()}),response: {200: z.object({@@ -570,16 +574,17 @@ export const registerApprovalPolicyEndpoints = ({},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- const { grants } = await server.services.approvalPolicy.listGrants(+ const { grants, projectId } = await server.services.approvalPolicy.listGrants(policyType,- req.query.projectId,+ req.query.scope,+ req.query.id,req.permission);await server.services.auditLog.createAuditLog({...req.auditLogInfo,orgId: req.permission.orgId,- projectId: req.query.projectId,+ projectId,event: {type: EventType.APPROVAL_REQUEST_GRANT_LIST,metadata: {diff --git a/backend/src/server/routes/v1/cert-manager-access-router.ts b/backend/src/server/routes/v1/cert-manager-access-router.tsindex 0cac65e5d3..b1540f77f5 100644--- a/backend/src/server/routes/v1/cert-manager-access-router.ts+++ b/backend/src/server/routes/v1/cert-manager-access-router.ts@@ -78,7 +78,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProvider},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { data: memberships } = await server.services.membershipUser.listMemberships({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },@@ -95,11 +95,11 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderserver.route({method: "GET",- url: "/users/:membershipId",+ url: "/users/:userId",config: { rateLimit: readLimit },schema: {operationId: "getCertManagerUser",- params: z.object({ membershipId: z.string().trim().min(1) }),+ params: z.object({ userId: z.string().trim().min(1) }),response: {200: z.object({membership: ProjectMembershipsSchema.extend({@@ -111,12 +111,8 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProvider},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 projectId = req.internalCertManagerProjectId;+ const { userId } = req.params;const membership = await server.services.membershipUser.getMembershipByUserId({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },@@ -155,7 +151,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProvider},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const usernamesAndEmails = [...req.body.emails, ...req.body.usernames];await server.services.membershipUser.createMembership({@@ -199,22 +195,18 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderserver.route({method: "PATCH",- url: "/users/:membershipId",+ url: "/users/:userId",config: { rateLimit: writeLimit },schema: {operationId: "updateCertManagerUser",- params: z.object({ membershipId: z.string().trim().min(1) }),+ params: z.object({ userId: 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 projectId = req.internalCertManagerProjectId;+ const { userId } = req.params;const { membership } = await server.services.membershipUser.updateMembership({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },@@ -222,7 +214,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderdata: { roles: req.body.roles }});return {- roles: membership.roles.map((el) => ({ ...el, projectMembershipId: req.params.membershipId }))+ roles: membership.roles.map((el) => ({ ...el, projectMembershipId: membership.id }))};}});@@ -250,7 +242,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProvider},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const memberships = await server.services.projectMembership.deleteProjectMemberships({actorId: req.permission.id,actor: req.permission.type,@@ -280,21 +272,17 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderserver.route({method: "DELETE",- url: "/users/:membershipId",+ url: "/users/:userId",config: { rateLimit: writeLimit },schema: {operationId: "removeCertManagerUser",- params: z.object({ membershipId: z.string().trim().min(1) }),+ params: z.object({ userId: 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 projectId = req.internalCertManagerProjectId;+ const { userId } = req.params;const { membership } = await server.services.membershipUser.deleteMembership({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },@@ -345,7 +333,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProvider},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { data: identityMemberships, totalCount } = await server.services.membershipIdentity.listMemberships({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },@@ -362,7 +350,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderserver.route({method: "GET",- url: "/identities/available",+ url: "/available-identities",config: { rateLimit: readLimit },schema: {operationId: "listAvailableCertManagerIdentities",@@ -379,7 +367,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProvider},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { identities } = await server.services.membershipIdentity.listAvailableIdentities({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },@@ -426,7 +414,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProvider},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const identityMembership = await server.services.membershipIdentity.getMembershipByIdentityId({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },@@ -467,7 +455,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderresponse: { 200: z.object({ identityMembership: IdentityProjectMembershipsSchema.omit({ projectId: true }) }) }},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { role, roles } = req.body;if (!role && !roles) {throw new BadRequestError({ message: "You must provide either role or roles field" });@@ -505,7 +493,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderresponse: { 200: z.object({ identityMembership: IdentityProjectMembershipsSchema.omit({ projectId: true }) }) }},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { membership } = await server.services.membershipIdentity.updateMembership({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },@@ -536,7 +524,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderresponse: { 200: z.object({ identityMembership: IdentityProjectMembershipsSchema.omit({ projectId: true }) }) }},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { membership } = await server.services.membershipIdentity.deleteMembership({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },@@ -591,7 +579,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderresponse: { 200: z.object({ groupMemberships: z.array(certManagerGroupMembershipSchema) }) }},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { memberships: groupMemberships } = await server.services.membershipGroup.listMemberships({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },@@ -618,7 +606,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderresponse: { 200: z.object({ groupMembership: certManagerGroupMembershipSchema }) }},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { membership } = await server.services.membershipGroup.getMembershipByGroupId({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },@@ -665,7 +653,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderresponse: { 200: z.object({ groupMembership: certManagerGroupMembershipSchema }) }},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const roles =req.body.roles ??(req.body.role@@ -703,7 +691,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderresponse: { 200: z.object({ roles: ProjectUserMembershipRolesSchema.array() }) }},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { membership: groupMembership } = await server.services.membershipGroup.updateMembership({permission: req.permission,selector: { groupId: req.params.groupId },@@ -733,7 +721,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProvider}},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { membership: groupMembership } = await server.services.membershipGroup.deleteMembership({permission: req.permission,selector: { groupId: req.params.groupId },@@ -768,7 +756,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProvider}},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { roles } = await server.services.role.listRoles({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },@@ -796,7 +784,7 @@ export const registerCertManagerAccessRouter = async (server: FastifyZodProviderresponse: { 200: z.object({ role: SanitizedRoleSchema.omit({ projectId: true }) }) }},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const role = await server.services.role.getRoleBySlug({permission: req.permission,scopeData: { scope: AccessScope.Project, orgId: req.permission.orgId, projectId },diff --git a/backend/src/server/routes/v1/cert-manager-instance-router.ts b/backend/src/server/routes/v1/cert-manager-instance-router.tsindex 80dbe3fd98..ddc0c2f7b2 100644--- a/backend/src/server/routes/v1/cert-manager-instance-router.ts+++ b/backend/src/server/routes/v1/cert-manager-instance-router.ts@@ -32,7 +32,7 @@ export const registerCertManagerInstanceRouter = async (server: FastifyZodProvidurl: "/instance",config: { rateLimit: readLimit },schema: {- hide: false,+ hide: true,operationId: "getCertManagerInstanceState",description:"Get the active Cert Manager project and the list of legacy Cert Manager projects in this organization.",@@ -70,7 +70,7 @@ export const registerCertManagerInstanceRouter = async (server: FastifyZodProvidurl: "/instance/legacy",config: { rateLimit: readLimit },schema: {- hide: false,+ hide: true,operationId: "listCertManagerLegacyInstances",description: "List all Cert Manager projects in the organization with their certificate, sync, and alert counts.",tags: [ApiDocsTags.CertManagerInstance],@@ -97,7 +97,7 @@ export const registerCertManagerInstanceRouter = async (server: FastifyZodProvidurl: "/instance/active-project",config: { rateLimit: writeLimit },schema: {- hide: false,+ hide: true,operationId: "setCertManagerActiveProject",description:"Set the active Cert Manager project for this organization. New API requests resolve to this project when no projectId is supplied.",diff --git a/backend/src/server/routes/v1/certificate-authority-router.ts b/backend/src/server/routes/v1/certificate-authority-router.tsindex 317a4a2554..a5d69782ca 100644--- a/backend/src/server/routes/v1/certificate-authority-router.ts+++ b/backend/src/server/routes/v1/certificate-authority-router.ts@@ -38,6 +38,7 @@ 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),@@ -97,7 +98,6 @@ 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.tsindex 6e1b4a612a..b6583f5514 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,6 +35,9 @@ export const registerAzureAdCsCertificateAuthorityRouter = async (server: Fastifparams: z.object({caId: z.string().describe("Azure AD CS CA ID")}),+ querystring: z.object({+ projectId: z.string().optional().describe("Project ID")+ }),response: {200: z.object({templates: z.array(@@ -49,7 +52,7 @@ export const registerAzureAdCsCertificateAuthorityRouter = async (server: Fastif},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const templates = await server.services.certificateAuthority.getAzureAdcsTemplates({caId: req.params.caId,projectId,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.tsindex c6137c097f..83f943fe73 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@@ -58,7 +58,7 @@ export const registerCertificateAuthorityEndpoints = <},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const projectId = req.query.projectId ?? req.certManagerProjectId;+ const projectId = req.query.projectId ?? req.internalCertManagerProjectId;const certificateAuthorities = (await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId({ projectId, type: caType },@@ -141,7 +141,7 @@ export const registerCertificateAuthorityEndpoints = <handler: async (req) => {const body = req.body as { projectId?: string };const certificateAuthority = (await server.services.certificateAuthority.createCertificateAuthority(- { ...req.body, projectId: body.projectId ?? req.certManagerProjectId, type: caType },+ { ...req.body, projectId: body.projectId ?? req.internalCertManagerProjectId, 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.tsindex dbea4994ee..1f4f4dccf5 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,6 +37,9 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZoperationId: "listCertificateAuthoritiesV1General",tags: [ApiDocsTags.PkiCertificateAuthorities],description: "Get Certificate Authorities",+ querystring: z.object({+ projectId: z.string().optional()+ }),response: {200: z.object({certificateAuthorities: CertificateAuthoritySchema.array()@@ -44,7 +47,7 @@ export const registerGeneralCertificateAuthorityRouter = async (server: FastifyZ}},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const internalCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId({projectId,diff --git a/backend/src/server/routes/v1/certificate-cleanup-router.ts b/backend/src/server/routes/v1/certificate-cleanup-router.tsindex d9dcb1572b..aa2bcf9952 100644--- a/backend/src/server/routes/v1/certificate-cleanup-router.ts+++ b/backend/src/server/routes/v1/certificate-cleanup-router.ts@@ -20,6 +20,9 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvideoperationId: "getCertificateCleanupConfig",description: "Get certificate cleanup configuration for a project",tags: [ApiDocsTags.PkiCertificates],+ querystring: z.object({+ projectId: z.string().trim().optional().describe("Project ID")+ }),response: {200: z.object({config: CertificateCleanupConfigsSchema.omit({ id: true }).nullable()@@ -28,7 +31,7 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvide},handler: async (req) => {const config = await server.services.certificateCleanup.getConfig({- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,@@ -51,6 +54,7 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvidedescription: "Create or update certificate cleanup configuration for a project",tags: [ApiDocsTags.PkiCertificates],body: z.object({+ projectId: z.string().trim().optional().describe("Project ID"),isEnabled: z.boolean().optional().describe("Enable cleanup"),postExpiryRetentionDays: z.number()@@ -69,7 +73,7 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvide},handler: async (req) => {const config = await server.services.certificateCleanup.updateConfig({- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,isEnabled: req.body.isEnabled,postExpiryRetentionDays: req.body.postExpiryRetentionDays,skipCertsWithActiveSyncs: req.body.skipCertsWithActiveSyncs,@@ -81,11 +85,11 @@ export const registerCertificateCleanupRouter = async (server: FastifyZodProvideawait server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.UPDATE_CERTIFICATE_CLEANUP_CONFIG,metadata: {- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,isEnabled: config.isEnabled,postExpiryRetentionDays: config.postExpiryRetentionDays,skipCertsWithActiveSyncs: config.skipCertsWithActiveSyncsdiff --git a/backend/src/server/routes/v1/certificate-inventory-view-router.ts b/backend/src/server/routes/v1/certificate-inventory-view-router.tsindex 63faa598e6..5f82a14338 100644--- a/backend/src/server/routes/v1/certificate-inventory-view-router.ts+++ b/backend/src/server/routes/v1/certificate-inventory-view-router.ts@@ -52,6 +52,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodPtags: [ApiDocsTags.PkiCertificates],description: "List system and custom certificate inventory views for a project.",querystring: z.object({+ projectId: z.string().trim().optional(),applicationId: z.string().uuid().optional()}),response: {@@ -87,7 +88,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodPonRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {return server.services.certificateInventoryView.listViews({- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,applicationId: req.query.applicationId,actorId: req.permission.id,actorOrgId: req.permission.orgId,@@ -109,6 +110,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodPtags: [ApiDocsTags.PkiCertificates],description: "Create a custom certificate inventory view.",body: z.object({+ projectId: z.string().trim().optional(),name: z.string().trim().min(1).max(255),filters: InventoryViewFiltersSchema.default({}),columns: ColumnsSchema.optional(),@@ -124,7 +126,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodPonRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {const view = await server.services.certificateInventoryView.createView({- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,applicationId: req.body.applicationId,name: req.body.name,filters: req.body.filters,@@ -137,7 +139,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.CREATE_CERTIFICATE_INVENTORY_VIEW,metadata: {@@ -168,6 +170,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodPviewId: z.string().uuid()}),body: z.object({+ projectId: z.string().trim().optional(),name: z.string().trim().min(1).max(255).optional(),filters: InventoryViewFiltersSchema.optional(),columns: ColumnsSchema.optional(),@@ -183,7 +186,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodPhandler: async (req) => {const view = await server.services.certificateInventoryView.updateView({viewId: req.params.viewId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,name: req.body.name,filters: req.body.filters,columns: req.body.columns,@@ -195,7 +198,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.UPDATE_CERTIFICATE_INVENTORY_VIEW,metadata: {@@ -235,7 +238,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodPhandler: async (req) => {const view = await server.services.certificateInventoryView.deleteView({viewId: req.params.viewId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,actorId: req.permission.id,actorOrgId: req.permission.orgId,actorAuthMethod: req.permission.authMethod,@@ -243,7 +246,7 @@ export const registerCertificateInventoryViewRouter = async (server: FastifyZodP});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,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.tsindex ad9008078e..27348821a2 100644--- a/backend/src/server/routes/v1/certificate-policy-router.ts+++ b/backend/src/server/routes/v1/certificate-policy-router.ts@@ -175,6 +175,7 @@ const policyBasicConstraintsSchema = z.nullable();const createCertificatePolicySchema = z.object({+ projectId: z.string().min(1).optional(),name: slugSchema({ min: 1, max: 255, field: "Name" }),description: z.string().max(1000).optional(),subject: z.array(policySubjectSchema).optional(),@@ -223,13 +224,13 @@ export const registerCertificatePolicyRouter = async (server: FastifyZodProvideractorId: req.permission.id,actorAuthMethod: req.permission.authMethod!,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,data: req.body});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.CREATE_CERTIFICATE_POLICY,metadata: {@@ -269,15 +270,13 @@ export const registerCertificatePolicyRouter = async (server: FastifyZodProvider},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const { projectId: explicitProjectId, ...query } = req.query;- const projectId = explicitProjectId ?? req.certManagerProjectId;const { policies, totalCount } = await server.services.certificatePolicy.listPolicies({actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod!,actorOrgId: req.permission.orgId,- projectId,- ...query+ ...req.query,+ projectId: req.internalCertManagerProjectId});await server.services.auditLog.createAuditLog({diff --git a/backend/src/server/routes/v1/certificate-profiles-router.ts b/backend/src/server/routes/v1/certificate-profiles-router.tsindex bb69b7c98f..069cdebf54 100644--- a/backend/src/server/routes/v1/certificate-profiles-router.ts+++ b/backend/src/server/routes/v1/certificate-profiles-router.ts@@ -56,6 +56,7 @@ export const registerCertificateProfilesRouter = async (tags: [ApiDocsTags.PkiCertificateProfiles],body: z.object({+ projectId: z.string().min(1).optional(),caId: z.string().uuid().optional(),certificatePolicyId: z.string().uuid(),slug: z@@ -235,13 +236,13 @@ export const registerCertificateProfilesRouter = async (actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,data: req.body});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.CREATE_CERTIFICATE_PROFILE,metadata: {@@ -345,23 +346,22 @@ export const registerCertificateProfilesRouter = async (},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const { projectId: explicitProjectId, ...query } = req.query;const { profiles, totalCount } = await server.services.certificateProfile.listProfiles({actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: explicitProjectId ?? req.certManagerProjectId,- ...query+ ...req.query,+ projectId: req.internalCertManagerProjectId});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.LIST_CERTIFICATE_PROFILES,metadata: {- projectId: req.certManagerProjectId+ projectId: req.internalCertManagerProjectId}}});@@ -504,7 +504,7 @@ export const registerCertificateProfilesRouter = async (actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,slug: req.params.slug});diff --git a/backend/src/server/routes/v1/certificate-router.ts b/backend/src/server/routes/v1/certificate-router.tsindex 83c24296df..70ed85d172 100644--- a/backend/src/server/routes/v1/certificate-router.ts+++ b/backend/src/server/routes/v1/certificate-router.ts@@ -555,7 +555,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const { certificateRequests, totalCount } = await server.services.certificateRequest.listCertificateRequests({actor: req.permission.type,@@ -682,8 +682,8 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const { metadata, projectId: explicitProjectId, ...filters } = req.body;- const projectId = explicitProjectId ?? req.certManagerProjectId;+ const { metadata, ...filters } = req.body;+ const projectId = req.internalCertManagerProjectId;const { certificateRequests, totalCount } = await server.services.certificateRequest.listCertificateRequests({actor: req.permission.type,@@ -1488,7 +1488,7 @@ export const registerCertificateRouter = async (server: FastifyZodProvider) => {actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...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.tsindex 48861a892f..9407ee6811 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,6 +34,9 @@ export const registerAzureAdCsCertificateAuthorityRouter = async (server: Fastifparams: 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(@@ -48,10 +51,9 @@ 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,+ projectId: req.query.projectId,actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,@@ -60,7 +62,7 @@ export const registerAzureAdCsCertificateAuthorityRouter = async (server: Fastifawait server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId,+ projectId: req.query.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.tsindex 76300d0689..05b111f301 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,13 +48,18 @@ 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 projectId = req.certManagerProjectId;+ const {+ query: { projectId }+ } = req;const certificateAuthorities = (await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId({ projectId, type: caType },@@ -88,6 +93,9 @@ export const registerCertificateAuthorityEndpoints = <params: z.object({caName: z.string()}),+ querystring: z.object({+ projectId: z.string().uuid()+ }),response: {200: responseSchema}@@ -95,7 +103,7 @@ export const registerCertificateAuthorityEndpoints = <onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {const { caName } = req.params;- const projectId = req.certManagerProjectId;+ const { projectId } = req.query;const certificateAuthority =(await server.services.certificateAuthority.findCertificateAuthorityByNameAndProjectId(@@ -135,9 +143,8 @@ 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, projectId: body.projectId ?? req.certManagerProjectId, type: caType },+ { ...req.body, type: caType },req.permission)) as T;@@ -177,11 +184,10 @@ 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},@@ -217,6 +223,9 @@ export const registerCertificateAuthorityEndpoints = <params: z.object({caName: z.string()}),+ querystring: z.object({+ projectId: z.string().uuid()+ }),response: {200: responseSchema}@@ -224,7 +233,7 @@ export const registerCertificateAuthorityEndpoints = <onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {const { caName } = req.params;- const projectId = req.certManagerProjectId;+ const { projectId } = req.query;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.tsindex 0e0d83ec0a..955407e4cc 100644--- a/backend/src/server/routes/v1/deprecated-certificate-router.ts+++ b/backend/src/server/routes/v1/deprecated-certificate-router.ts@@ -298,6 +298,8 @@ 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),@@ -321,7 +323,6 @@ 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/pki-alert-router.ts b/backend/src/server/routes/v1/pki-alert-router.tsindex c670482229..50d7b21b4f 100644--- a/backend/src/server/routes/v1/pki-alert-router.ts+++ b/backend/src/server/routes/v1/pki-alert-router.ts@@ -30,6 +30,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {description: "Create a new PKI alert",tags: [ApiDocsTags.PkiAlerting],body: BasePkiAlertV2Schema.extend({+ projectId: z.string().uuid().optional().describe("Project ID"),applicationId: z.string().uuid()@@ -71,13 +72,13 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...req.body});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.CREATE_PKI_ALERT,metadata: {@@ -153,14 +154,13 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {}},handler: async (req) => {- const { projectId: explicitProjectId, ...query } = req.query;const alerts = await server.services.pkiAlertV2.listAlerts({actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: explicitProjectId ?? req.certManagerProjectId,- ...query+ ...req.query,+ projectId: req.internalCertManagerProjectId});return alerts;@@ -440,6 +440,7 @@ 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().optional().describe("Project ID"),filters: z.array(PkiFilterRuleSchema),alertBefore: z.string()@@ -474,7 +475,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...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.tsindex 48ba10a02f..ff3efb1fdb 100644--- a/backend/src/server/routes/v1/pki-application-alert-router.ts+++ b/backend/src/server/routes/v1/pki-application-alert-router.ts@@ -46,7 +46,7 @@ export const registerPkiApplicationAlertRoutes = async (server: FastifyZodProvidactorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,applicationId: req.params.applicationId,search: req.query.search,eventType: req.query.eventType,@@ -80,13 +80,13 @@ export const registerPkiApplicationAlertRoutes = async (server: FastifyZodProvidactorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,applicationId: req.params.applicationId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...req.body});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.CREATE_PKI_ALERT,metadata: {@@ -133,7 +133,7 @@ export const registerPkiApplicationAlertRoutes = async (server: FastifyZodProvidawait server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.UPDATE_PKI_ALERT,metadata: {@@ -178,7 +178,7 @@ export const registerPkiApplicationAlertRoutes = async (server: FastifyZodProvidawait server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.DELETE_PKI_ALERT,metadata: {diff --git a/backend/src/server/routes/v1/pki-application-enrollment-router.ts b/backend/src/server/routes/v1/pki-application-enrollment-router.tsdeleted file mode 100644index 211bd79247..0000000000--- a/backend/src/server/routes/v1/pki-application-enrollment-router.ts+++ /dev/null@@ -1,560 +0,0 @@-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(),- estEndpointUrl: z.string()-});--const AcmeEnrollmentStateSchema = z.object({- id: z.string().uuid(),- skipDnsOwnershipVerification: z.boolean(),- skipEabBinding: z.boolean(),- directoryUrl: z.string()-});--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(),- scepEndpointUrl: z.string(),- challengeEndpointUrl: z.string().nullable(),- raCertificatePem: z.string(),- raCertExpiresAt: z.date()-});--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-enrollment-routers/acme-enrollment-router.ts b/backend/src/server/routes/v1/pki-application-enrollment-routers/acme-enrollment-router.tsnew file mode 100644index 0000000000..b5c5ab9126--- /dev/null+++ b/backend/src/server/routes/v1/pki-application-enrollment-routers/acme-enrollment-router.ts@@ -0,0 +1,184 @@+import { z } from "zod";++import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { ApiDocsTags } from "@app/lib/api-docs";+import { writeLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";++export const registerPkiApplicationAcmeEnrollmentRouter = async (server: FastifyZodProvider) => {+ 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.internalCertManagerProjectId,+ 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.internalCertManagerProjectId,+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ profileId: req.params.profileId+ });+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ profileId: req.params.profileId+ });+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ profileId: req.params.profileId+ });+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.ROTATE_PKI_APPLICATION_ACME_EAB_SECRET,+ metadata: { applicationId: req.params.applicationId, profileId: req.params.profileId }+ }+ });+ return result;+ }+ });+};diff --git a/backend/src/server/routes/v1/pki-application-enrollment-routers/api-enrollment-router.ts b/backend/src/server/routes/v1/pki-application-enrollment-routers/api-enrollment-router.tsnew file mode 100644index 0000000000..6495f20414--- /dev/null+++ b/backend/src/server/routes/v1/pki-application-enrollment-routers/api-enrollment-router.ts@@ -0,0 +1,122 @@+import { z } from "zod";++import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { ApiDocsTags } from "@app/lib/api-docs";+import { 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()+});++export const registerPkiApplicationApiEnrollmentRouter = async (server: FastifyZodProvider) => {+ 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.internalCertManagerProjectId,+ 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.internalCertManagerProjectId,+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ profileId: req.params.profileId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.CLEAR_PKI_APPLICATION_API_ENROLLMENT,+ metadata: {+ applicationId: req.params.applicationId,+ profileId: req.params.profileId+ }+ }+ });++ return result;+ }+ });+};diff --git a/backend/src/server/routes/v1/pki-application-enrollment-routers/enrollment-state-router.ts b/backend/src/server/routes/v1/pki-application-enrollment-routers/enrollment-state-router.tsnew file mode 100644index 0000000000..a99c44c463--- /dev/null+++ b/backend/src/server/routes/v1/pki-application-enrollment-routers/enrollment-state-router.ts@@ -0,0 +1,97 @@+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 } 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(),+ estEndpointUrl: z.string()+});++const AcmeEnrollmentStateSchema = z.object({+ id: z.string().uuid(),+ skipDnsOwnershipVerification: z.boolean(),+ skipEabBinding: z.boolean(),+ directoryUrl: z.string()+});++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(),+ scepEndpointUrl: z.string(),+ challengeEndpointUrl: z.string().nullable(),+ raCertificatePem: z.string(),+ raCertExpiresAt: z.date()+});++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 registerPkiApplicationEnrollmentStateRouter = 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ profileId: req.params.profileId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.GET_PKI_APPLICATION_ENROLLMENT,+ metadata: {+ applicationId: req.params.applicationId,+ profileId: req.params.profileId+ }+ }+ });++ return result;+ }+ });+};diff --git a/backend/src/server/routes/v1/pki-application-enrollment-routers/est-enrollment-router.ts b/backend/src/server/routes/v1/pki-application-enrollment-routers/est-enrollment-router.tsnew file mode 100644index 0000000000..a501b154a2--- /dev/null+++ b/backend/src/server/routes/v1/pki-application-enrollment-routers/est-enrollment-router.ts@@ -0,0 +1,101 @@+import { z } from "zod";++import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { ApiDocsTags } from "@app/lib/api-docs";+import { writeLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";++export const registerPkiApplicationEstEnrollmentRouter = async (server: FastifyZodProvider) => {+ 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.internalCertManagerProjectId,+ 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.internalCertManagerProjectId,+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ profileId: req.params.profileId+ });+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.CLEAR_PKI_APPLICATION_EST_ENROLLMENT,+ metadata: { applicationId: req.params.applicationId, profileId: req.params.profileId }+ }+ });+ return result;+ }+ });+};diff --git a/backend/src/server/routes/v1/pki-application-enrollment-routers/index.ts b/backend/src/server/routes/v1/pki-application-enrollment-routers/index.tsnew file mode 100644index 0000000000..e5cdc02086--- /dev/null+++ b/backend/src/server/routes/v1/pki-application-enrollment-routers/index.ts@@ -0,0 +1,13 @@+import { registerPkiApplicationAcmeEnrollmentRouter } from "./acme-enrollment-router";+import { registerPkiApplicationApiEnrollmentRouter } from "./api-enrollment-router";+import { registerPkiApplicationEnrollmentStateRouter } from "./enrollment-state-router";+import { registerPkiApplicationEstEnrollmentRouter } from "./est-enrollment-router";+import { registerPkiApplicationScepEnrollmentRouter } from "./scep-enrollment-router";++export const registerPkiApplicationEnrollmentRoutes = async (server: FastifyZodProvider) => {+ await registerPkiApplicationEnrollmentStateRouter(server);+ await registerPkiApplicationApiEnrollmentRouter(server);+ await registerPkiApplicationEstEnrollmentRouter(server);+ await registerPkiApplicationAcmeEnrollmentRouter(server);+ await registerPkiApplicationScepEnrollmentRouter(server);+};diff --git a/backend/src/server/routes/v1/pki-application-enrollment-routers/scep-enrollment-router.ts b/backend/src/server/routes/v1/pki-application-enrollment-routers/scep-enrollment-router.tsnew file mode 100644index 0000000000..be35178949--- /dev/null+++ b/backend/src/server/routes/v1/pki-application-enrollment-routers/scep-enrollment-router.ts@@ -0,0 +1,99 @@+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 { writeLimit } from "@app/server/config/rateLimiter";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";++export const registerPkiApplicationScepEnrollmentRouter = async (server: FastifyZodProvider) => {+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ profileId: req.params.profileId,+ config: req.body+ });+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ profileId: req.params.profileId+ });+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ 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-routers/groups-router.ts b/backend/src/server/routes/v1/pki-application-membership-routers/groups-router.tsnew file mode 100644index 0000000000..1166684aa1--- /dev/null+++ b/backend/src/server/routes/v1/pki-application-membership-routers/groups-router.ts@@ -0,0 +1,180 @@+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 { ApplicationMemberSchema, RemoveResponseSchema, RoleBodySchema } from "./schemas";++const GroupParamsSchema = z.object({+ applicationId: z.string().uuid(),+ groupId: z.string().uuid()+});++export const registerPkiApplicationGroupMembershipRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/:applicationId/groups",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listPkiApplicationGroupMembers",+ description: "List group 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ kind: "group"+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.LIST_PKI_APPLICATION_MEMBERS,+ metadata: { applicationId: req.params.applicationId }+ }+ });++ return { memberships };+ }+ });++ server.route({+ method: "POST",+ url: "/:applicationId/groups/:groupId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "addPkiApplicationGroupMember",+ description: "Add a group as a member of a Cert Manager application.",+ tags: [ApiDocsTags.PkiApplications],+ params: GroupParamsSchema,+ body: RoleBodySchema,+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ groupId: req.params.groupId,+ role: req.body.role+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.ADD_PKI_APPLICATION_MEMBER,+ metadata: {+ applicationId: membership.applicationId,+ membershipId: membership.membershipId,+ groupId: membership.actorGroupId ?? undefined,+ role: membership.role+ }+ }+ });++ return { membership };+ }+ });++ server.route({+ method: "PATCH",+ url: "/:applicationId/groups/:groupId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "updatePkiApplicationGroupMemberRole",+ description: "Update the role of a group member on a Cert Manager application.",+ tags: [ApiDocsTags.PkiApplications],+ params: GroupParamsSchema,+ body: RoleBodySchema,+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ kind: "group",+ memberId: req.params.groupId,+ role: req.body.role+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ 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/groups/:groupId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "removePkiApplicationGroupMember",+ description: "Remove a group from a Cert Manager application.",+ tags: [ApiDocsTags.PkiApplications],+ params: GroupParamsSchema,+ response: { 200: RemoveResponseSchema }+ },+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ kind: "group",+ memberId: req.params.groupId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ 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-membership-router.ts b/backend/src/server/routes/v1/pki-application-membership-routers/identities-router.tssimilarity index 56%rename from backend/src/server/routes/v1/pki-application-membership-router.tsrename to backend/src/server/routes/v1/pki-application-membership-routers/identities-router.tsindex 704a3e2907..d3388fc167 100644--- a/backend/src/server/routes/v1/pki-application-membership-router.ts+++ b/backend/src/server/routes/v1/pki-application-membership-routers/identities-router.ts@@ -6,39 +6,23 @@ 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 { ApplicationIdParamsSchema } from "../pki-application-schemas";+import { ApplicationMemberSchema, RemoveResponseSchema, RoleBodySchema } from "./schemas";-const ApplicationMemberSchema = z.object({- membershipId: z.string().uuid(),+const IdentityParamsSchema = z.object({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()+ identityId: z.string().uuid()});-export const registerPkiApplicationMembershipRoutes = async (server: FastifyZodProvider) => {+export const registerPkiApplicationIdentityMembershipRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",- url: "/:applicationId/memberships",+ url: "/:applicationId/identities",config: { rateLimit: readLimit },schema: {hide: false,- operationId: "listPkiApplicationMembers",- description: "List members of a Cert Manager application.",+ operationId: "listPkiApplicationIdentityMembers",+ description: "List identity members of a Cert Manager application.",tags: [ApiDocsTags.PkiApplications],params: ApplicationIdParamsSchema,response: { 200: z.object({ memberships: z.array(ApplicationMemberSchema) }) }@@ -50,13 +34,14 @@ export const registerPkiApplicationMembershipRoutes = async (server: FastifyZodPactorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,- applicationId: req.params.applicationId+ projectId: req.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ kind: "identity"});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.LIST_PKI_APPLICATION_MEMBERS,metadata: { applicationId: req.params.applicationId }@@ -69,25 +54,15 @@ export const registerPkiApplicationMembershipRoutes = async (server: FastifyZodPserver.route({method: "POST",- url: "/:applicationId/memberships",+ url: "/:applicationId/identities/:identityId",config: { rateLimit: writeLimit },schema: {hide: false,- operationId: "addPkiApplicationMember",- description: "Add a user, identity, or group as a member of a Cert Manager application.",+ operationId: "addPkiApplicationIdentityMember",+ description: "Add an identity 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."- ),+ params: IdentityParamsSchema,+ body: RoleBodySchema,response: { 200: z.object({ membership: ApplicationMemberSchema }) }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),@@ -97,25 +72,21 @@ export const registerPkiApplicationMembershipRoutes = async (server: FastifyZodPactorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,applicationId: req.params.applicationId,- userId: req.body.userId,- identityId: req.body.identityId,- groupId: req.body.groupId,+ identityId: req.params.identityId,role: req.body.role});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,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}}@@ -127,20 +98,15 @@ export const registerPkiApplicationMembershipRoutes = async (server: FastifyZodPserver.route({method: "PATCH",- url: "/:applicationId/memberships/:membershipId",+ url: "/:applicationId/identities/:identityId",config: { rateLimit: writeLimit },schema: {hide: false,- operationId: "updatePkiApplicationMemberRole",- description: "Update the role of a member on a Cert Manager application.",+ operationId: "updatePkiApplicationIdentityMemberRole",+ description: "Update the role of an identity 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)- }),+ params: IdentityParamsSchema,+ body: RoleBodySchema,response: { 200: z.object({ membership: ApplicationMemberSchema }) }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),@@ -150,15 +116,16 @@ export const registerPkiApplicationMembershipRoutes = async (server: FastifyZodPactorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,applicationId: req.params.applicationId,- membershipId: req.params.membershipId,+ kind: "identity",+ memberId: req.params.identityId,role: req.body.role});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.UPDATE_PKI_APPLICATION_MEMBER_ROLE,metadata: {@@ -175,23 +142,15 @@ export const registerPkiApplicationMembershipRoutes = async (server: FastifyZodPserver.route({method: "DELETE",- url: "/:applicationId/memberships/:membershipId",+ url: "/:applicationId/identities/:identityId",config: { rateLimit: writeLimit },schema: {hide: false,- operationId: "removePkiApplicationMember",- description: "Remove a member from a Cert Manager application.",+ operationId: "removePkiApplicationIdentityMember",+ description: "Remove an identity 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()- })- }+ params: IdentityParamsSchema,+ response: { 200: RemoveResponseSchema }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {@@ -200,20 +159,18 @@ export const registerPkiApplicationMembershipRoutes = async (server: FastifyZodPactorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,applicationId: req.params.applicationId,- membershipId: req.params.membershipId+ kind: "identity",+ memberId: req.params.identityId});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.REMOVE_PKI_APPLICATION_MEMBER,- metadata: {- applicationId: result.applicationId,- membershipId: result.membershipId- }+ metadata: { applicationId: result.applicationId, membershipId: result.membershipId }}});diff --git a/backend/src/server/routes/v1/pki-application-membership-routers/index.ts b/backend/src/server/routes/v1/pki-application-membership-routers/index.tsnew file mode 100644index 0000000000..4862fe7914--- /dev/null+++ b/backend/src/server/routes/v1/pki-application-membership-routers/index.ts@@ -0,0 +1,9 @@+import { registerPkiApplicationGroupMembershipRouter } from "./groups-router";+import { registerPkiApplicationIdentityMembershipRouter } from "./identities-router";+import { registerPkiApplicationUserMembershipRouter } from "./users-router";++export const registerPkiApplicationMembershipRoutes = async (server: FastifyZodProvider) => {+ await registerPkiApplicationUserMembershipRouter(server);+ await registerPkiApplicationIdentityMembershipRouter(server);+ await registerPkiApplicationGroupMembershipRouter(server);+};diff --git a/backend/src/server/routes/v1/pki-application-membership-routers/schemas.ts b/backend/src/server/routes/v1/pki-application-membership-routers/schemas.tsnew file mode 100644index 0000000000..47eb4c2ec8--- /dev/null+++ b/backend/src/server/routes/v1/pki-application-membership-routers/schemas.ts@@ -0,0 +1,30 @@+import { z } from "zod";++export 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 RoleBodySchema = z.object({ role: z.string().min(1) });++export const RemoveResponseSchema = z.object({+ membershipId: z.string().uuid(),+ applicationId: z.string().uuid()+});diff --git a/backend/src/server/routes/v1/pki-application-membership-routers/users-router.ts b/backend/src/server/routes/v1/pki-application-membership-routers/users-router.tsnew file mode 100644index 0000000000..4df429a4a2--- /dev/null+++ b/backend/src/server/routes/v1/pki-application-membership-routers/users-router.ts@@ -0,0 +1,180 @@+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 { ApplicationMemberSchema, RemoveResponseSchema, RoleBodySchema } from "./schemas";++const UserParamsSchema = z.object({+ applicationId: z.string().uuid(),+ userId: z.string().uuid()+});++export const registerPkiApplicationUserMembershipRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/:applicationId/users",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listPkiApplicationUserMembers",+ description: "List user 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ kind: "user"+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.LIST_PKI_APPLICATION_MEMBERS,+ metadata: { applicationId: req.params.applicationId }+ }+ });++ return { memberships };+ }+ });++ server.route({+ method: "POST",+ url: "/:applicationId/users/:userId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "addPkiApplicationUserMember",+ description: "Add a user as a member of a Cert Manager application.",+ tags: [ApiDocsTags.PkiApplications],+ params: UserParamsSchema,+ body: RoleBodySchema,+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ userId: req.params.userId,+ role: req.body.role+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.ADD_PKI_APPLICATION_MEMBER,+ metadata: {+ applicationId: membership.applicationId,+ membershipId: membership.membershipId,+ userId: membership.actorUserId ?? undefined,+ role: membership.role+ }+ }+ });++ return { membership };+ }+ });++ server.route({+ method: "PATCH",+ url: "/:applicationId/users/:userId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "updatePkiApplicationUserMemberRole",+ description: "Update the role of a user member on a Cert Manager application.",+ tags: [ApiDocsTags.PkiApplications],+ params: UserParamsSchema,+ body: RoleBodySchema,+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ kind: "user",+ memberId: req.params.userId,+ role: req.body.role+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ 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/users/:userId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "removePkiApplicationUserMember",+ description: "Remove a user from a Cert Manager application.",+ tags: [ApiDocsTags.PkiApplications],+ params: UserParamsSchema,+ response: { 200: RemoveResponseSchema }+ },+ 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.internalCertManagerProjectId,+ applicationId: req.params.applicationId,+ kind: "user",+ memberId: req.params.userId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ 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.tsindex 943585f689..0d7dd33c59 100644--- a/backend/src/server/routes/v1/pki-application-profile-router.ts+++ b/backend/src/server/routes/v1/pki-application-profile-router.ts@@ -30,7 +30,7 @@ export const registerPkiApplicationProfileRoutes = async (server: FastifyZodProvactorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,applicationId: req.params.applicationId});@@ -62,14 +62,14 @@ export const registerPkiApplicationProfileRoutes = async (server: FastifyZodProvactorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,applicationId: req.params.applicationId,profileIds: req.body.profileIds});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.ATTACH_PKI_APPLICATION_PROFILES,metadata: {@@ -110,14 +110,14 @@ export const registerPkiApplicationProfileRoutes = async (server: FastifyZodProvactorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,applicationId: req.params.applicationId,profileId: req.params.profileId});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.DETACH_PKI_APPLICATION_PROFILE,metadata: {diff --git a/backend/src/server/routes/v1/pki-application-router.ts b/backend/src/server/routes/v1/pki-application-router.tsindex 5764c6b575..ab5cb02bb5 100644--- a/backend/src/server/routes/v1/pki-application-router.ts+++ b/backend/src/server/routes/v1/pki-application-router.ts@@ -1,24 +1,22 @@-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 { slugSchema } from "@app/server/lib/schemas";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 { registerPkiApplicationEnrollmentRoutes } from "./pki-application-enrollment-routers";+import { registerPkiApplicationMembershipRoutes } from "./pki-application-membership-routers";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_NAME_REGEX = new RE2("^[a-z0-9-]+$");-const APPLICATION_NAME_MESSAGE = "Name must contain only lowercase letters, numbers, and hyphens";+const ApplicationNameSchema = slugSchema({ min: 1, max: 64, field: "Name" });const ApplicationListItemSchema = PkiApplicationsSchema.extend({profileCount: z.number().int().nonnegative(),@@ -37,7 +35,7 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =description: "Create a Cert Manager application.",tags: [ApiDocsTags.PkiApplications],body: z.object({- name: z.string().trim().min(1).max(64).regex(APPLICATION_NAME_REGEX, APPLICATION_NAME_MESSAGE),+ name: ApplicationNameSchema,description: z.string().max(256).optional(),profileIds: z.array(z.string().uuid()).optional()}),@@ -52,7 +50,7 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,name: req.body.name,description: req.body.description,profileIds: req.body.profileIds@@ -60,7 +58,7 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.CREATE_PKI_APPLICATION,metadata: {@@ -103,7 +101,7 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,search: req.query.search,limit: req.query.limit,offset: req.query.offset@@ -111,10 +109,10 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.LIST_PKI_APPLICATIONS,- metadata: { projectId: req.certManagerProjectId }+ metadata: { projectId: req.internalCertManagerProjectId }}});@@ -141,13 +139,13 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,applicationId: req.params.applicationId});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.GET_PKI_APPLICATION,metadata: { applicationId: application.id, name: application.name }@@ -167,7 +165,7 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =operationId: "getPkiApplicationByName",description: "Get a Cert Manager application by name.",tags: [ApiDocsTags.PkiApplications],- params: z.object({ name: z.string().regex(APPLICATION_NAME_REGEX, APPLICATION_NAME_MESSAGE) }),+ params: z.object({ name: ApplicationNameSchema }),response: { 200: z.object({ application: PkiApplicationsSchema }) }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),@@ -177,13 +175,13 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,name: req.params.name});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.GET_PKI_APPLICATION,metadata: { applicationId: application.id, name: application.name }@@ -206,7 +204,7 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =params: ApplicationIdParamsSchema,body: z.object({- name: z.string().trim().min(1).max(64).regex(APPLICATION_NAME_REGEX, APPLICATION_NAME_MESSAGE).optional(),+ name: ApplicationNameSchema.optional(),description: z.string().max(256).nullable().optional()}).refine((d) => d.name !== undefined || d.description !== undefined, {@@ -221,7 +219,7 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,applicationId: req.params.applicationId,name: req.body.name,description: req.body.description@@ -229,7 +227,7 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.UPDATE_PKI_APPLICATION,metadata: { applicationId: application.id, name: application.name }@@ -259,13 +257,13 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,applicationId: req.params.applicationId});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.DELETE_PKI_APPLICATION,metadata: { applicationId: application.id, name: application.name }@@ -280,5 +278,4 @@ export const registerPkiApplicationRouter = async (server: FastifyZodProvider) =await registerPkiApplicationMembershipRoutes(server);await registerPkiApplicationEnrollmentRoutes(server);await registerPkiApplicationAlertRoutes(server);- await registerPkiApplicationSyncRoutes(server);};diff --git a/backend/src/server/routes/v1/pki-application-sync-router.ts b/backend/src/server/routes/v1/pki-application-sync-router.tsdeleted file mode 100644index ab211d19b8..0000000000--- a/backend/src/server/routes/v1/pki-application-sync-router.ts+++ /dev/null@@ -1,146 +0,0 @@-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.tsindex 4e0773d27b..f24b35375c 100644--- a/backend/src/server/routes/v1/pki-collection-router.ts+++ b/backend/src/server/routes/v1/pki-collection-router.ts@@ -22,6 +22,7 @@ export const registerPkiCollectionRouter = async (server: FastifyZodProvider) =>tags: [ApiDocsTags.PkiCertificateCollections],description: "Create PKI collection",body: z.object({+ projectId: z.string().trim().optional().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,7 +36,7 @@ export const registerPkiCollectionRouter = async (server: FastifyZodProvider) =>actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...req.body});diff --git a/backend/src/server/routes/v1/pki-subscriber-router.ts b/backend/src/server/routes/v1/pki-subscriber-router.tsindex 966be49cc4..c31f10e0a8 100644--- a/backend/src/server/routes/v1/pki-subscriber-router.ts+++ b/backend/src/server/routes/v1/pki-subscriber-router.ts@@ -32,6 +32,9 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>params: z.object({subscriberName: z.string().describe(PKI_SUBSCRIBERS.GET.subscriberName)}),+ querystring: z.object({+ projectId: z.string().optional().describe(PKI_SUBSCRIBERS.GET.projectId)+ }),response: {200: sanitizedPkiSubscriber}@@ -40,7 +43,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>handler: async (req) => {const subscriber = await server.services.pkiSubscriber.getSubscriber({subscriberName: req.params.subscriberName,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,@@ -75,6 +78,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>tags: [ApiDocsTags.PkiSubscribers],description: "Create PKI Subscriber",body: z.object({+ projectId: z.string().trim().optional().describe(PKI_SUBSCRIBERS.CREATE.projectId),caId: z.string().trim()@@ -202,7 +206,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>handler: async (req) => {const subscriber = await server.services.pkiSubscriber.createSubscriber({...req.body,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,@@ -247,6 +251,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>subscriberName: z.string().trim().describe(PKI_SUBSCRIBERS.UPDATE.subscriberName)}),body: z.object({+ projectId: z.string().trim().optional().describe(PKI_SUBSCRIBERS.UPDATE.projectId),caId: z.string().trim()@@ -370,7 +375,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>handler: async (req) => {const subscriber = await server.services.pkiSubscriber.updateSubscriber({subscriberName: req.params.subscriberName,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,@@ -413,6 +418,9 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>params: z.object({subscriberName: z.string().describe(PKI_SUBSCRIBERS.DELETE.subscriberName)}),+ querystring: z.object({+ projectId: z.string().trim().optional().describe(PKI_SUBSCRIBERS.DELETE.projectId)+ }),response: {200: sanitizedPkiSubscriber}@@ -421,7 +429,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>handler: async (req) => {const subscriber = await server.services.pkiSubscriber.deleteSubscriber({subscriberName: req.params.subscriberName,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,@@ -459,6 +467,11 @@ 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().optional().describe(PKI_SUBSCRIBERS.ISSUE_CERT.projectId)+ })+ .optional(),response: {200: z.object({message: z.string().trim()@@ -468,7 +481,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>handler: async (req) => {const subscriber = await server.services.pkiSubscriber.orderSubscriberCert({subscriberName: req.params.subscriberName,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,@@ -519,6 +532,11 @@ 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().optional().describe(PKI_SUBSCRIBERS.ISSUE_CERT.projectId)+ })+ .optional(),response: {200: z.object({certificate: z.string().trim().describe(PKI_SUBSCRIBERS.ISSUE_CERT.certificate),@@ -533,7 +551,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.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,@@ -590,6 +608,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>subscriberName: z.string().describe(PKI_SUBSCRIBERS.SIGN_CERT.subscriberName)}),body: z.object({+ projectId: z.string().trim().optional().describe(PKI_SUBSCRIBERS.SIGN_CERT.projectId),csr: z.string().trim().min(1).max(3000).describe(PKI_SUBSCRIBERS.SIGN_CERT.csr)}),response: {@@ -605,7 +624,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>const { certificate, certificateChain, issuingCaCertificate, serialNumber, subscriber } =await server.services.pkiSubscriber.signSubscriberCert({subscriberName: req.params.subscriberName,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,csr: req.body.csr,actor: req.permission.type,actorId: req.permission.id,@@ -660,6 +679,9 @@ 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().optional().describe(PKI_SUBSCRIBERS.GET_LATEST_CERT_BUNDLE.projectId)+ }),response: {200: z.object({certificate: z.string().trim().describe(PKI_SUBSCRIBERS.GET_LATEST_CERT_BUNDLE.certificate),@@ -682,7 +704,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId+ projectId: req.internalCertManagerProjectId});await server.services.auditLog.createAuditLog({@@ -725,6 +747,7 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>subscriberName: z.string().describe(PKI_SUBSCRIBERS.GET.subscriberName)}),querystring: z.object({+ projectId: z.string().trim().optional().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)}),@@ -743,19 +766,19 @@ export const registerPkiSubscriberRouter = async (server: FastifyZodProvider) =>actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...req.query});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.LIST_PKI_SUBSCRIBER_CERTS,metadata: {subscriberId: req.params.subscriberName,name: req.params.subscriberName,- projectId: req.certManagerProjectId+ projectId: req.internalCertManagerProjectId}}});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.tsindex bc62b673ab..f8c2f74124 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@@ -63,13 +63,16 @@ 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().optional()+ }),response: {200: z.object({ pkiSyncs: responseSchema.array() })}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const pkiSyncs = await server.services.pkiSync.listPkiSyncsByProjectId({ projectId }, req.permission);@@ -147,7 +150,7 @@ export const registerSyncPkiEndpoints = ({onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {const pkiSync = await server.services.pkiSync.createPkiSync(- { ...req.body, projectId: req.body.projectId ?? req.certManagerProjectId, destination },+ { ...req.body, projectId: req.body.projectId ?? req.internalCertManagerProjectId, destination },req.permission);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.tsindex 0e22b5b167..82a846b497 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@@ -139,7 +139,9 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider, enableOptags: [ApiDocsTags.PkiSyncs],description: "List all the PKI Syncs for the specified project.",querystring: z.object({- certificateId: z.string().uuid().optional()+ projectId: z.string().trim().optional(),+ certificateId: z.string().uuid().optional(),+ applicationId: z.string().uuid().optional()}),response: {200: z.object({ pkiSyncs: PkiSyncSchema.array() })@@ -148,12 +150,15 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider, enableOponRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {const {- query: { certificateId },+ query: { certificateId, applicationId },permission} = req;- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;- const pkiSyncs = await server.services.pkiSync.listPkiSyncsByProjectId({ projectId, certificateId }, permission);+ const pkiSyncs = await server.services.pkiSync.listPkiSyncsByProjectId(+ { projectId, certificateId, applicationId },+ permission+ );await server.services.auditLog.createAuditLog({...req.auditLogInfo,diff --git a/backend/src/server/routes/v2/certificate-authority-router.ts b/backend/src/server/routes/v2/certificate-authority-router.tsindex e2e605ffe4..2adf990abc 100644--- a/backend/src/server/routes/v2/certificate-authority-router.ts+++ b/backend/src/server/routes/v2/certificate-authority-router.ts@@ -37,6 +37,9 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {operationId: "listCertificateAuthoritiesV2",tags: [ApiDocsTags.PkiCertificateAuthorities],description: "Get Certificate Authorities",+ querystring: z.object({+ projectId: z.string().optional()+ }),response: {200: z.object({certificateAuthorities: CertificateAuthoritySchema.array()@@ -44,7 +47,7 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {}},handler: async (req) => {- const projectId = req.certManagerProjectId;+ const projectId = req.internalCertManagerProjectId;const internalCas = await server.services.certificateAuthority.listCertificateAuthoritiesByProjectId({projectId,diff --git a/backend/src/server/routes/v2/pki-alert-router.ts b/backend/src/server/routes/v2/pki-alert-router.tsindex 6c839dd7d8..77e9d7d130 100644--- a/backend/src/server/routes/v2/pki-alert-router.ts+++ b/backend/src/server/routes/v2/pki-alert-router.ts@@ -29,6 +29,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {description: "Create a new PKI alert",tags: [ApiDocsTags.PkiAlerting],body: BasePkiAlertV2Schema.extend({+ projectId: z.string().uuid().optional().describe("Project ID"),applicationId: z.string().uuid()@@ -46,6 +47,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {filters: z.array(PkiFilterRuleSchema),enabled: z.boolean(),projectId: z.string().uuid(),+ applicationId: z.string().uuid().nullable(),notificationConfig: NotificationConfigSchema.nullable(),channels: z.array(z.object({@@ -69,13 +71,13 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...req.body});await server.services.auditLog.createAuditLog({...req.auditLogInfo,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,event: {type: EventType.CREATE_PKI_ALERT,metadata: {@@ -103,6 +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().optional().describe("Project ID"),applicationId: z.string().uuid().optional(),search: z.string().optional(),eventType: z.nativeEnum(PkiAlertEventType).optional(),@@ -121,6 +124,8 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {alertBefore: z.string().optional(),filters: z.array(PkiFilterRuleSchema),enabled: z.boolean(),+ projectId: z.string().uuid(),+ applicationId: z.string().uuid().nullable(),notificationConfig: NotificationConfigSchema.nullable(),channels: z.array(z.object({@@ -153,7 +158,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...req.query});@@ -186,6 +191,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {filters: z.array(PkiFilterRuleSchema),enabled: z.boolean(),projectId: z.string().uuid(),+ applicationId: z.string().uuid().nullable(),notificationConfig: NotificationConfigSchema.nullable(),channels: z.array(z.object({@@ -253,6 +259,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {filters: z.array(PkiFilterRuleSchema),enabled: z.boolean(),projectId: z.string().uuid(),+ applicationId: z.string().uuid().nullable(),notificationConfig: NotificationConfigSchema.nullable(),channels: z.array(z.object({@@ -323,6 +330,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {filters: z.array(PkiFilterRuleSchema),enabled: z.boolean(),projectId: z.string().uuid(),+ applicationId: z.string().uuid().nullable(),notificationConfig: NotificationConfigSchema.nullable(),channels: z.array(z.object({@@ -427,6 +435,7 @@ 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().optional().describe("Project ID"),filters: z.array(PkiFilterRuleSchema),alertBefore: z.string()@@ -461,7 +470,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...req.body});@@ -481,6 +490,7 @@ 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().optional().describe("Project ID for permission check"),url: z.string().url()@@ -497,7 +507,7 @@ export const registerPkiAlertRouter = async (server: FastifyZodProvider) => {},handler: async (req) => {const result = await server.services.pkiAlertV2.testWebhookConfig({- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,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.tsindex e1e0eb4654..aa72ddb8f2 100644--- a/backend/src/server/routes/v2/pki-templates-router.ts+++ b/backend/src/server/routes/v2/pki-templates-router.ts@@ -26,6 +26,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>operationId: "createPkiTemplate",tags: [ApiDocsTags.PkiCertificateTemplates],body: z.object({+ projectId: z.string().optional(),name: slugSchema(),caName: slugSchema({ field: "caName" }),commonName: validateTemplateRegexField,@@ -51,7 +52,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...req.body});@@ -73,6 +74,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>templateName: slugSchema()}),body: z.object({+ projectId: z.string().optional(),name: slugSchema().optional(),caName: slugSchema(),commonName: validateTemplateRegexField.optional(),@@ -102,7 +104,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,templateName: req.params.templateName,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...req.body});@@ -123,6 +125,9 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>params: z.object({templateName: z.string().min(1)}),+ querystring: z.object({+ projectId: z.string().optional()+ }),response: {200: z.object({certificateTemplate: CertificateTemplatesSchema@@ -137,7 +142,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,templateName: req.params.templateName,- projectId: req.certManagerProjectId+ projectId: req.internalCertManagerProjectId});return { certificateTemplate };@@ -157,6 +162,9 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>params: z.object({templateName: slugSchema()}),+ querystring: z.object({+ projectId: z.string().optional()+ }),response: {200: z.object({certificateTemplate: CertificateTemplatesSchema.extend({@@ -173,7 +181,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,templateName: req.params.templateName,- projectId: req.certManagerProjectId+ projectId: req.internalCertManagerProjectId});return { certificateTemplate };@@ -191,6 +199,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>operationId: "listPkiTemplates",tags: [ApiDocsTags.PkiCertificateTemplates],querystring: z.object({+ projectId: z.string().optional(),limit: z.coerce.number().default(100),offset: z.coerce.number().default(0)}),@@ -210,7 +219,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...req.query});@@ -232,6 +241,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>templateName: slugSchema()}),body: z.object({+ projectId: z.string().optional(),commonName: validateTemplateRegexField,ttl: z.string().refine((val) => ms(val) > 0, "TTL must be a positive number"),keyUsages: z.nativeEnum(CertKeyUsage).array().optional(),@@ -258,7 +268,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,templateName: req.params.templateName,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...req.body});@@ -280,6 +290,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>templateName: slugSchema()}),body: z.object({+ projectId: z.string().optional(),ttl: z.string().refine((val) => ms(val) > 0, "TTL must be a positive number"),csr: z.string().trim().min(1).max(4096)}),@@ -300,7 +311,7 @@ export const registerPkiTemplatesRouter = async (server: FastifyZodProvider) =>actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,templateName: req.params.templateName,- projectId: req.certManagerProjectId,+ projectId: req.internalCertManagerProjectId,...req.body});diff --git a/backend/src/services/approval-policy/approval-policy-dal.ts b/backend/src/services/approval-policy/approval-policy-dal.tsindex d85331c029..8a8b5efb9a 100644--- a/backend/src/services/approval-policy/approval-policy-dal.ts+++ b/backend/src/services/approval-policy/approval-policy-dal.ts@@ -64,7 +64,7 @@ export const approvalPolicyDALFactory = (db: TDbClient) => {const findByProjectId = async (policyType: ApprovalPolicyType,projectId: string,- options?: { applicationId?: string | null }+ options?: { scopeType?: string | null; scopeId?: string | null }) => {try {const dbInstance = db.replicaNode();@@ -72,10 +72,13 @@ export const approvalPolicyDALFactory = (db: TDbClient) => {.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 });+ if (options?.scopeType === null) {+ void baseQuery.whereNull("scopeType");+ } else if (typeof options?.scopeType === "string") {+ void baseQuery.where({ scopeType: options.scopeType });+ if (typeof options?.scopeId === "string") {+ void baseQuery.where({ scopeId: options.scopeId });+ }}const policies = await baseQuery;diff --git a/backend/src/services/approval-policy/approval-policy-enums.ts b/backend/src/services/approval-policy/approval-policy-enums.tsindex 1ea3e65e6d..9cd8f4f831 100644--- a/backend/src/services/approval-policy/approval-policy-enums.ts+++ b/backend/src/services/approval-policy/approval-policy-enums.ts@@ -4,6 +4,11 @@ export enum ApprovalPolicyType {CertCodeSigning = "cert-code-signing"}+export enum ApprovalPolicyScope {+ Project = "project",+ PkiApplication = "pki-application"+}+export enum ApproverType {Group = "group",User = "user"diff --git a/backend/src/services/approval-policy/approval-policy-schemas.ts b/backend/src/services/approval-policy/approval-policy-schemas.tsindex 653a47d8ce..fbdebde190 100644--- a/backend/src/services/approval-policy/approval-policy-schemas.ts+++ b/backend/src/services/approval-policy/approval-policy-schemas.ts@@ -9,7 +9,7 @@ import {} from "@app/db/schemas";import { ms } from "@app/lib/ms";-import { ApproverType } from "./approval-policy-enums";+import { ApprovalPolicyScope, ApproverType } from "./approval-policy-enums";const ApprovalPolicyStepSchema = z.object({name: z.string().min(1).max(128).nullable().optional(),@@ -39,7 +39,8 @@ export const BaseApprovalPolicySchema = ApprovalPoliciesSchema.extend({});export const BaseCreateApprovalPolicySchema = z.object({- projectId: z.string().uuid(),+ scope: z.nativeEnum(ApprovalPolicyScope),+ scopeId: z.string().uuid(),name: z.string().min(1).max(128),maxRequestTtl: MaxRequestTtlSchema.nullable().optional(),steps: ApprovalPolicyStepSchema.array(),@@ -76,7 +77,8 @@ export const BaseApprovalRequestSchema = ApprovalRequestsSchema.extend({});export const BaseCreateApprovalRequestSchema = z.object({- projectId: z.string().uuid(),+ scope: z.nativeEnum(ApprovalPolicyScope),+ scopeId: z.string().uuid(),justification: z.string().max(256).nullable().optional(),requestDuration: z.string()diff --git a/backend/src/services/approval-policy/approval-policy-service.ts b/backend/src/services/approval-policy/approval-policy-service.tsindex 9cc915b782..45f5acc5f7 100644--- a/backend/src/services/approval-policy/approval-policy-service.ts+++ b/backend/src/services/approval-policy/approval-policy-service.ts@@ -27,6 +27,7 @@ import { ActorType } from "@app/services/auth/auth-type";import { TCertificateRequestDALFactory } from "@app/services/certificate-request/certificate-request-dal";import { TCertificateApprovalService } from "@app/services/certificate-v3/certificate-approval-fns";import { TNotificationServiceFactory } from "@app/services/notification/notification-service";+import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";import { TMembershipDALFactory } from "../membership/membership-dal";import { TProjectMembershipDALFactory } from "../project-membership/project-membership-dal";@@ -36,6 +37,7 @@ import {TApprovalPolicyStepsDALFactory} from "./approval-policy-dal";import {+ ApprovalPolicyScope,ApprovalPolicyType,ApprovalRequestApprovalDecision,ApprovalRequestGrantStatus,@@ -80,6 +82,7 @@ type TApprovalPolicyServiceFactoryDep = {>;projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findProjectMembershipsByUserIds">;membershipDAL: Pick<TMembershipDALFactory, "find">;+ pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;certificateApprovalService: TCertificateApprovalService;certificateRequestDAL: Pick<TCertificateRequestDALFactory, "updateById" | "findById">;};@@ -99,15 +102,34 @@ export const approvalPolicyServiceFactory = ({permissionService,projectMembershipDAL,membershipDAL,+ pkiApplicationDAL,certificateApprovalService,certificateRequestDAL}: TApprovalPolicyServiceFactoryDep) => {const $notifyApprovers = (step: ApprovalPolicyStep, request: TApprovalRequests) =>notifyApproversForStep(step, request, { userGroupMembershipDAL, notificationService });+ const $resolveScope = async (+ scope: ApprovalPolicyScope,+ scopeId: string+ ): Promise<{ projectId: string; scopeType: string | null; scopeId: string | null }> => {+ if (scope === ApprovalPolicyScope.Project) {+ return { projectId: scopeId, scopeType: null, scopeId: null };+ }+ if (scope === ApprovalPolicyScope.PkiApplication) {+ const app = await pkiApplicationDAL.findById(scopeId);+ if (!app) {+ throw new NotFoundError({ message: `Application ${scopeId} not found` });+ }+ return { projectId: app.projectId, scopeType: ApprovalPolicyScope.PkiApplication, scopeId };+ }+ throw new BadRequestError({ message: `Unsupported scope: ${String(scope)}` });+ };+const $assertCanManagePolicy = async (projectId: string,- applicationId: string | null | undefined,+ scopeType: string | null | undefined,+ scopeId: string | null | undefined,actor: OrgServiceActor,resourceAction: ResourcePermissionApprovalPolicyActions) => {@@ -122,7 +144,7 @@ export const approvalPolicyServiceFactory = ({if (hasRole(ProjectMembershipRole.Admin)) return;- if (!applicationId) {+ if (scopeType !== ApprovalPolicyScope.PkiApplication || !scopeId) {throw new ForbiddenRequestError({ message: "User has insufficient privileges" });}@@ -131,7 +153,7 @@ export const approvalPolicyServiceFactory = ({actorId: actor.id,projectId,resourceType: ResourceType.CertificateApplication,- resourceId: applicationId,+ resourceId: scopeId,actorAuthMethod: actor.authMethod,actorOrgId: actor.orgId});@@ -189,22 +211,31 @@ export const approvalPolicyServiceFactory = ({const create = async (policyType: ApprovalPolicyType,{- projectId,+ scope,+ scopeId: inputScopeId,name,maxRequestTtl,conditions,constraints,steps,- bypassForMachineIdentities,- applicationId+ bypassForMachineIdentities}: TCreatePolicyDTO,actor: OrgServiceActor) => {- await $assertCanManagePolicy(projectId, applicationId, actor, ResourcePermissionApprovalPolicyActions.Create);+ const resolved = await $resolveScope(scope, inputScopeId);+ const { projectId, scopeType: dbScopeType, scopeId: dbScopeId } = resolved;++ await $assertCanManagePolicy(+ projectId,+ dbScopeType,+ dbScopeId,+ actor,+ ResourcePermissionApprovalPolicyActions.Create+ );const allApprovers = steps.flatMap((step) => step.approvers ?? []);- if (applicationId) {- await $verifyApplicationApproverMembership(allApprovers, projectId, applicationId);+ if (dbScopeType === ApprovalPolicyScope.PkiApplication && dbScopeId) {+ await $verifyApplicationApproverMembership(allApprovers, projectId, dbScopeId);} else {const approverUserIds = allApprovers.filter((approver) => approver.type === ApproverType.User)@@ -223,7 +254,8 @@ export const approvalPolicyServiceFactory = ({constraints: { version: 1, constraints },type: policyType,bypassForMachineIdentities: bypassForMachineIdentities ?? false,- applicationId: applicationId ?? null+ scopeType: dbScopeType,+ scopeId: dbScopeId},tx);@@ -269,10 +301,12 @@ export const approvalPolicyServiceFactory = ({const list = async (policyType: ApprovalPolicyType,- projectId: string,- actor: OrgServiceActor,- options?: { applicationId?: string | null }+ scope: ApprovalPolicyScope,+ inputScopeId: string,+ actor: OrgServiceActor) => {+ const { projectId, scopeType: dbScopeType, scopeId: dbScopeId } = await $resolveScope(scope, inputScopeId);+const { hasRole } = await permissionService.getProjectPermission({actor: actor.type,actorAuthMethod: actor.authMethod,@@ -287,10 +321,11 @@ export const approvalPolicyServiceFactory = ({}const policies = await approvalPolicyDAL.findByProjectId(policyType, projectId, {- applicationId: options?.applicationId+ scopeType: dbScopeType,+ scopeId: dbScopeId});- return { policies };+ return { policies, projectId };};const getById = async (policyId: string, actor: OrgServiceActor) => {@@ -301,7 +336,8 @@ export const approvalPolicyServiceFactory = ({await $assertCanManagePolicy(policy.projectId,- policy.applicationId,+ policy.scopeType ?? null,+ policy.scopeId ?? null,actor,ResourcePermissionApprovalPolicyActions.Read);@@ -313,15 +349,7 @@ export const approvalPolicyServiceFactory = ({const updateById = async (policyId: string,- {- name,- maxRequestTtl,- conditions,- constraints,- steps,- bypassForMachineIdentities,- applicationId- }: TUpdatePolicyDTO,+ { name, maxRequestTtl, conditions, constraints, steps, bypassForMachineIdentities }: TUpdatePolicyDTO,actor: OrgServiceActor) => {const policy = await approvalPolicyDAL.findById(policyId);@@ -329,21 +357,21 @@ export const approvalPolicyServiceFactory = ({throw new ForbiddenRequestError({ message: "Policy not found" });}- const targetAppId = applicationId !== undefined ? applicationId : policy.applicationId;+ const policyScopeType = policy.scopeType ?? null;+ const policyScopeId = policy.scopeId ?? null;+await $assertCanManagePolicy(policy.projectId,- policy.applicationId,+ policyScopeType,+ policyScopeId,actor,ResourcePermissionApprovalPolicyActions.Edit);- if (applicationId !== undefined && applicationId !== policy.applicationId) {- await $assertCanManagePolicy(policy.projectId, targetAppId, actor, ResourcePermissionApprovalPolicyActions.Edit);- }if (steps !== undefined) {const allApprovers = steps.flatMap((step) => step.approvers ?? []);- if (targetAppId) {- await $verifyApplicationApproverMembership(allApprovers, policy.projectId, targetAppId);+ if (policyScopeType === ApprovalPolicyScope.PkiApplication && policyScopeId) {+ await $verifyApplicationApproverMembership(allApprovers, policy.projectId, policyScopeId);} else {const approverUserIds = allApprovers.filter((approver) => approver.type === ApproverType.User)@@ -375,10 +403,6 @@ export const approvalPolicyServiceFactory = ({updateDoc.bypassForMachineIdentities = bypassForMachineIdentities;}- if (applicationId !== undefined) {- updateDoc.applicationId = applicationId;- }-const updated = await approvalPolicyDAL.updateById(policyId, updateDoc, tx);if (steps !== undefined) {@@ -432,7 +456,8 @@ export const approvalPolicyServiceFactory = ({await $assertCanManagePolicy(policy.projectId,- policy.applicationId,+ policy.scopeType ?? null,+ policy.scopeId ?? null,actor,ResourcePermissionApprovalPolicyActions.Delete);@@ -472,7 +497,8 @@ export const approvalPolicyServiceFactory = ({machineIdentityId,requesterName,requesterEmail,- applicationId: policy.applicationId ?? null+ scopeType: policy.scopeType ?? null,+ scopeId: policy.scopeId ?? null},{approvalRequestDAL,@@ -494,7 +520,8 @@ export const approvalPolicyServiceFactory = ({const createRequest = async (policyType: ApprovalPolicyType,{- projectId,+ scope,+ scopeId: inputScopeId,requestData,requestDuration,justification,@@ -508,6 +535,8 @@ export const approvalPolicyServiceFactory = ({},actor: OrgServiceActor) => {+ const { projectId } = await $resolveScope(scope, inputScopeId);+const { permission } = await permissionService.getProjectPermission({actor: actor.type,actorAuthMethod: actor.authMethod,@@ -838,10 +867,12 @@ export const approvalPolicyServiceFactory = ({const listRequests = async (policyType: ApprovalPolicyType,- projectId: string,- actor: OrgServiceActor,- options?: { applicationId?: string | null }+ scope: ApprovalPolicyScope,+ inputScopeId: string,+ actor: OrgServiceActor) => {+ const { projectId, scopeType: dbScopeType, scopeId: dbScopeId } = await $resolveScope(scope, inputScopeId);+const { permission } = await permissionService.getProjectPermission({actor: actor.type,actorAuthMethod: actor.authMethod,@@ -857,15 +888,14 @@ export const approvalPolicyServiceFactory = ({);const requests = await approvalRequestDAL.findByProjectId(policyType, projectId, {- applicationId: options?.applicationId+ scopeType: dbScopeType,+ scopeId: dbScopeId});- // If user has read permission, return all requestsif (hasReadPermission) {- return { requests };+ return { requests, projectId };}- // Otherwise, filter to only requests where user is requester or approverconst userGroups = await userGroupMembershipDAL.findGroupMembershipsByUserIdInOrg(actor.id, actor.orgId);const userGroupIds = new Set(userGroups.map((g) => g.groupId));@@ -879,7 +909,6 @@ export const approvalPolicyServiceFactory = ({continue;}- // Check if user is an eligible approver for any stepconst isApprover = request.steps.some((step) =>step.approvers.some((approver) =>@@ -893,7 +922,7 @@ export const approvalPolicyServiceFactory = ({}}- return { requests: filteredRequests };+ return { requests: filteredRequests, projectId };};const cancelRequest = async (requestId: string, actor: OrgServiceActor) => {@@ -919,7 +948,14 @@ export const approvalPolicyServiceFactory = ({return { request: { ...updatedRequest, steps } };};- const listGrants = async (policyType: ApprovalPolicyType, projectId: string, actor: OrgServiceActor) => {+ const listGrants = async (+ policyType: ApprovalPolicyType,+ scope: ApprovalPolicyScope,+ inputScopeId: string,+ actor: OrgServiceActor+ ) => {+ const { projectId } = await $resolveScope(scope, inputScopeId);+const { permission } = await permissionService.getProjectPermission({actor: actor.type,actorAuthMethod: actor.authMethod,@@ -946,7 +982,7 @@ export const approvalPolicyServiceFactory = ({return grant;});- return { grants: updatedGrants };+ return { grants: updatedGrants, projectId };};const getGrantById = async (grantId: string, actor: OrgServiceActor) => {@@ -1006,14 +1042,15 @@ export const approvalPolicyServiceFactory = ({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 requestScopeType = (request as { scopeType?: string | null } | null)?.scopeType ?? null;+ const requestScopeId = (request as { scopeId?: string | null } | null)?.scopeId ?? null;+ if (requestScopeType === ApprovalPolicyScope.PkiApplication && requestScopeId) {const { permission: resourcePerm } = await permissionService.getResourcePermission({actor: actor.type,actorId: actor.id,projectId: grant.projectId,resourceType: ResourceType.CertificateApplication,- resourceId: requestApplicationId,+ resourceId: requestScopeId,actorAuthMethod: actor.authMethod,actorOrgId: actor.orgId});diff --git a/backend/src/services/approval-policy/approval-policy-types.ts b/backend/src/services/approval-policy/approval-policy-types.tsindex 6d91e2eea0..72b343d2bd 100644--- a/backend/src/services/approval-policy/approval-policy-types.ts+++ b/backend/src/services/approval-policy/approval-policy-types.ts@@ -6,7 +6,7 @@ import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import { TCertificateRequestDALFactory } from "@app/services/certificate-request/certificate-request-dal";import { TCertificateApprovalService } from "@app/services/certificate-v3/certificate-approval-fns";-import { ApprovalPolicyType, ApproverType } from "./approval-policy-enums";+import { ApprovalPolicyScope, ApprovalPolicyType, ApproverType } from "./approval-policy-enums";import {TCertRequestPolicy,TCertRequestPolicyConditions,@@ -58,14 +58,14 @@ export interface ApprovalPolicyStep {// Policy DTOsexport interface TCreatePolicyDTO {- projectId: TApprovalPolicy["projectId"];+ scope: ApprovalPolicyScope;+ scopeId: string;name: TApprovalPolicy["name"];maxRequestTtl?: TApprovalPolicy["maxRequestTtl"];conditions: TApprovalPolicy["conditions"]["conditions"];constraints: TApprovalPolicy["constraints"]["constraints"];steps: ApprovalPolicyStep[];bypassForMachineIdentities?: boolean;- applicationId?: string | null;}export interface TUpdatePolicyDTO {@@ -75,12 +75,12 @@ export interface TUpdatePolicyDTO {constraints?: TApprovalPolicy["constraints"]["constraints"];steps?: ApprovalPolicyStep[];bypassForMachineIdentities?: boolean;- applicationId?: string | null;}// Request DTOsexport interface TCreateRequestDTO {- projectId: TApprovalRequest["projectId"];+ scope: ApprovalPolicyScope;+ scopeId: string;requestData: TApprovalRequest["requestData"]["requestData"];justification?: TApprovalRequest["justification"];requestDuration?: string | null;diff --git a/backend/src/services/approval-policy/approval-request-dal.ts b/backend/src/services/approval-policy/approval-request-dal.tsindex 53e5d3ab9b..850b28f3cb 100644--- a/backend/src/services/approval-policy/approval-request-dal.ts+++ b/backend/src/services/approval-policy/approval-request-dal.ts@@ -71,16 +71,19 @@ export const approvalRequestDALFactory = (db: TDbClient) => {const findByProjectId = async (policyType: ApprovalPolicyType,projectId: string,- options?: { applicationId?: string | null }+ options?: { scopeType?: string | null; scopeId?: string | null }) => {try {const dbInstance = db.replicaNode();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 });+ if (options?.scopeType === null) {+ void baseQuery.whereNull("scopeType");+ } else if (typeof options?.scopeType === "string") {+ void baseQuery.where({ scopeType: options.scopeType });+ if (typeof options?.scopeId === "string") {+ void baseQuery.where({ scopeId: options.scopeId });+ }}const requests = await baseQuery;diff --git a/backend/src/services/approval-policy/approval-request-fns.ts b/backend/src/services/approval-policy/approval-request-fns.tsindex 44536d7bf4..acd657e200 100644--- a/backend/src/services/approval-policy/approval-request-fns.ts+++ b/backend/src/services/approval-policy/approval-request-fns.ts@@ -31,7 +31,8 @@ export interface TCreateApprovalRequestWithStepsParams {machineIdentityId?: string | null;requesterName: string;requesterEmail: string;- applicationId?: string | null;+ scopeType?: string | null;+ scopeId?: string | null;}export type TApprovalRequestWithSteps = TApprovalRequests & {@@ -66,7 +67,8 @@ export const createApprovalRequestWithSteps = async (machineIdentityId,requesterName,requesterEmail,- applicationId+ scopeType,+ scopeId}: TCreateApprovalRequestWithStepsParams,dependencies: {approvalRequestDAL: Pick<TApprovalRequestDALFactory, "create" | "transaction">;@@ -93,7 +95,8 @@ export const createApprovalRequestWithSteps = async (currentStep: 1,requestData: { version: 1, requestData },expiresAt,- applicationId: applicationId ?? null+ scopeType: scopeType ?? null,+ scopeId: scopeId ?? 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.tsindex 6c36e81fea..752e4ac3b1 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@@ -1,6 +1,7 @@import { logger } from "@app/lib/logger";import { CertificateRequestStatus } from "@app/services/certificate-request/certificate-request-types";+import { ApprovalPolicyScope } from "../approval-policy-enums";import {TApprovalRequestFactoryCanAccess,TApprovalRequestFactoryMatchPolicy,@@ -30,8 +31,10 @@ export const certRequestPolicyFactory: TApprovalResourceFactory<const policies = await approvalPolicyDAL.findByProjectId(policyType, projectId);const inputAppId = inputs.applicationId ?? null;+ const expectedScopeType = inputAppId ? ApprovalPolicyScope.PkiApplication : null;+ const expectedScopeId = inputAppId ?? null;const candidates = (policies as TCertRequestPolicy[]).filter(- (p) => p.isActive && (p.applicationId ?? null) === inputAppId+ (p) => p.isActive && (p.scopeType ?? null) === expectedScopeType && (p.scopeId ?? null) === expectedScopeId);const matched = candidates.find((p) =>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.tsindex 55c19265e3..7d04f31e23 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@@ -74,14 +74,12 @@ export const CreateCertRequestPolicySchema = BaseCreateApprovalPolicySchema.exteconditions: CertRequestPolicyConditionsSchema,constraints: CertRequestPolicyConstraintsSchema.optional().default({})- .transform((val) => val ?? {}),- applicationId: z.string().uuid().nullable().optional()+ .transform((val) => val ?? {})});export const UpdateCertRequestPolicySchema = BaseUpdateApprovalPolicySchema.extend({conditions: CertRequestPolicyConditionsSchema.optional(),- constraints: CertRequestPolicyConstraintsSchema.optional(),- applicationId: z.string().uuid().nullable().optional()+ constraints: CertRequestPolicyConstraintsSchema.optional()});export const CertRequestRequestSchema = BaseApprovalRequestSchema.extend({diff --git a/backend/src/services/certificate-authority/deprecated-certificate-authority-schemas.ts b/backend/src/services/certificate-authority/deprecated-certificate-authority-schemas.tsindex 984e34c8d2..5ecc50a4b8 100644--- a/backend/src/services/certificate-authority/deprecated-certificate-authority-schemas.ts+++ b/backend/src/services/certificate-authority/deprecated-certificate-authority-schemas.ts@@ -18,11 +18,7 @@ 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")- .optional()- .describe(CertificateAuthorities.CREATE(type).projectId),+ projectId: z.string().uuid("Project ID must be valid").describe(CertificateAuthorities.CREATE(type).projectId),enableDirectIssuance: z.boolean().describe(CertificateAuthorities.CREATE(type).enableDirectIssuance),status: z.nativeEnum(CaStatus).describe(CertificateAuthorities.CREATE(type).status)});@@ -30,11 +26,7 @@ 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")- .optional()- .describe(CertificateAuthorities.UPDATE(type).projectId),+ projectId: z.string().uuid("Project ID must be valid").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.tsindex 09fd9b41d1..7a99175409 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, "findOne" | "updateById" | "findById" | "transaction">;+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "findById" | "transaction" | "findProjectBySlug">;kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;caSigningConfigDAL: Pick<TCaSigningConfigDALFactory, "findByCaId" | "create" | "deleteById" | "transaction">;@@ -278,7 +278,18 @@ export const internalCertificateAuthorityServiceFactory = ({crlDistributionPointUrls,...dto}: TCreateCaDTO) => {- const { projectId } = dto;+ let projectId: string;+ if (dto.isInternal) {+ projectId = dto.projectId;+ } else if (dto.projectId) {+ projectId = dto.projectId;+ } else if (dto.projectSlug) {+ 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;+ } else {+ throw new BadRequestError({ message: "Either projectId or projectSlug is required" });+ }if (!dto.isInternal) {const { permission } = await permissionService.getProjectPermission({actor: dto.actor,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.tsindex cbf19ed950..70413cd3a1 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,8 @@ export type TCreateCaDTO =}| ({isInternal: false;- projectId: string;+ projectId?: string;+ projectSlug?: string;type: InternalCaType;friendlyName?: string;name?: string;diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.tsindex c13be1c065..4de72673c3 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, "findOne" | "updateById" | "findById" | "transaction">;+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "findById" | "transaction" | "findProjectBySlug">;kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findPkiSyncIdsByCertificateId">;@@ -549,7 +549,8 @@ export const certificateServiceFactory = ({* Import certificate*/const importCert = async ({- projectId,+ projectId: projectIdInput,+ projectSlug,pkiCollectionId,actorId,actorAuthMethod,@@ -562,6 +563,17 @@ export const certificateServiceFactory = ({}: TImportCertDTO) => {const collectionId = pkiCollectionId;+ const resolveProjectId = async (): Promise<string> => {+ if (projectIdInput) return projectIdInput;+ if (projectSlug) {+ const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);+ if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });+ return project.id;+ }+ throw new BadRequestError({ message: "Either projectId or projectSlug is required" });+ };+ const projectId = await resolveProjectId();+const { permission } = await permissionService.getProjectPermission({actor,actorId,diff --git a/backend/src/services/certificate/certificate-types.ts b/backend/src/services/certificate/certificate-types.tsindex 120020d569..c06a25b8a3 100644--- a/backend/src/services/certificate/certificate-types.ts+++ b/backend/src/services/certificate/certificate-types.ts@@ -139,7 +139,8 @@ export type TGetCertBodyDTO = {} & Omit<TProjectPermission, "projectId">;export type TImportCertDTO = {- projectId: string;+ projectId?: string;+ projectSlug?: string;friendlyName?: string;pkiCollectionId?: string;diff --git a/backend/src/services/pki-application/pki-application-membership-service.ts b/backend/src/services/pki-application/pki-application-membership-service.tsindex eb213253be..cd086c9e81 100644--- a/backend/src/services/pki-application/pki-application-membership-service.ts+++ b/backend/src/services/pki-application/pki-application-membership-service.ts@@ -183,6 +183,7 @@ export const pkiApplicationMembershipServiceFactory = ({const listMembers = async ({applicationId,+ kind,projectId,actor,actorId,@@ -210,17 +211,25 @@ export const pkiApplicationMembershipServiceFactory = ({scopeResourceId: applicationId});- if (memberships.length === 0) return [];+ const filteredMemberships = kind+ ? memberships.filter((m) => {+ if (kind === "user") return Boolean(m.actorUserId);+ if (kind === "identity") return Boolean(m.actorIdentityId);+ return Boolean(m.actorGroupId);+ })+ : memberships;++ if (filteredMemberships.length === 0) return [];const roles = await membershipRoleDAL.find({- $in: { membershipId: memberships.map((m) => m.id) }+ $in: { membershipId: filteredMemberships.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 userIds = filteredMemberships.map((m) => m.actorUserId).filter((v): v is string => Boolean(v));+ const identityIds = filteredMemberships.map((m) => m.actorIdentityId).filter((v): v is string => Boolean(v));+ const groupIds = filteredMemberships.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([]),@@ -232,7 +241,7 @@ export const pkiApplicationMembershipServiceFactory = ({const identityById = new Map(identities.map((i) => [i.id, i]));const groupById = new Map(groups.map((g) => [g.id, g]));- return memberships.map((m) => {+ return filteredMemberships.map((m) => {const r = rolesByMembership.get(m.id);let details: TApplicationMember["details"] = null;@@ -273,9 +282,36 @@ export const pkiApplicationMembershipServiceFactory = ({});};+ const $findMembershipByMember = async (+ applicationId: string,+ projectId: string,+ kind: "user" | "identity" | "group",+ memberId: string+ ) => {+ const where: Record<string, unknown> = {+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.CertificateApplication,+ scopeResourceId: applicationId+ };+ if (kind === "user") where.actorUserId = memberId;+ else if (kind === "identity") where.actorIdentityId = memberId;+ else where.actorGroupId = memberId;++ const matches = await membershipDAL.find(where);+ const membership = matches[0];+ if (!membership) {+ throw new NotFoundError({+ message: `No application membership found for ${kind} '${memberId}' on application '${applicationId}'.`+ });+ }+ return membership;+ };+const updateMemberRole = async ({applicationId,- membershipId,+ kind,+ memberId,role,projectId,actor,@@ -304,22 +340,18 @@ export const pkiApplicationMembershipServiceFactory = ({});}- 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.` });- }+ const membership = await $findMembershipByMember(applicationId, projectId, kind, memberId);return membershipDAL.transaction(async (tx) => {- const updatedRoles = await membershipRoleDAL.update({ membershipId }, { role, customRoleId: null }, tx);+ const updatedRoles = await membershipRoleDAL.update(+ { membershipId: membership.id },+ { role, customRoleId: null },+ tx+ );const updated = updatedRoles[0];return {- membershipId,+ membershipId: membership.id,applicationId,actorUserId: membership.actorUserId ?? null,actorIdentityId: membership.actorIdentityId ?? null,@@ -334,7 +366,8 @@ export const pkiApplicationMembershipServiceFactory = ({const removeMember = async ({applicationId,- membershipId,+ kind,+ memberId,projectId,actor,actorId,@@ -356,22 +389,14 @@ export const pkiApplicationMembershipServiceFactory = ({);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.` });- }+ const membership = await $findMembershipByMember(applicationId, projectId, kind, memberId);await membershipDAL.transaction(async (tx) => {- await membershipRoleDAL.delete({ membershipId }, tx);- await membershipDAL.deleteById(membershipId, tx);+ await membershipRoleDAL.delete({ membershipId: membership.id }, tx);+ await membershipDAL.deleteById(membership.id, tx);});- return { membershipId, applicationId };+ return { membershipId: membership.id, applicationId };};return { addMember, listMembers, updateMemberRole, removeMember };diff --git a/backend/src/services/pki-application/pki-application-service.ts b/backend/src/services/pki-application/pki-application-service.tsindex 43c46ebeb2..12fe084901 100644--- a/backend/src/services/pki-application/pki-application-service.ts+++ b/backend/src/services/pki-application/pki-application-service.ts@@ -12,6 +12,9 @@ import {} from "@app/ee/services/permission/resource-permission";import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";+import { TApprovalPolicyDALFactory } from "../approval-policy/approval-policy-dal";+import { ApprovalPolicyScope } from "../approval-policy/approval-policy-enums";+import { TApprovalRequestDALFactory } from "../approval-policy/approval-request-dal";import { TMembershipDALFactory } from "../membership/membership-dal";import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";import { TPkiApplicationDALFactory } from "./pki-application-dal";@@ -46,6 +49,8 @@ type TPkiApplicationServiceFactoryDep = {>;membershipDAL: Pick<TMembershipDALFactory, "find" | "delete" | "findResourceMembershipsForActor">;membershipRoleDAL: Pick<TMembershipRoleDALFactory, "delete">;+ approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "delete">;+ approvalRequestDAL: Pick<TApprovalRequestDALFactory, "delete">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;};@@ -56,6 +61,8 @@ export const pkiApplicationServiceFactory = ({pkiApplicationProfileDAL,membershipDAL,membershipRoleDAL,+ approvalPolicyDAL,+ approvalRequestDAL,permissionService}: TPkiApplicationServiceFactoryDep) => {const $loadProjectPermission = (@@ -347,6 +354,8 @@ export const pkiApplicationServiceFactory = ({await membershipRoleDAL.delete({ $in: { membershipId: ids } }, tx);await membershipDAL.delete({ $in: { id: ids } }, tx);}+ await approvalRequestDAL.delete({ scopeType: ApprovalPolicyScope.PkiApplication, scopeId: applicationId }, tx);+ await approvalPolicyDAL.delete({ scopeType: ApprovalPolicyScope.PkiApplication, scopeId: applicationId }, tx);await pkiApplicationDAL.deleteById(applicationId, tx);});diff --git a/backend/src/services/pki-application/pki-application-types.ts b/backend/src/services/pki-application/pki-application-types.tsindex b75e5286ad..7f3529fff3 100644--- a/backend/src/services/pki-application/pki-application-types.ts+++ b/backend/src/services/pki-application/pki-application-types.ts@@ -96,17 +96,22 @@ export type TAddApplicationMemberDTO = {role: string;} & TProjectPermission;+export type TApplicationMemberKind = "user" | "identity" | "group";+export type TListApplicationMembersDTO = {applicationId: string;+ kind?: TApplicationMemberKind;} & TProjectPermission;export type TUpdateApplicationMemberRoleDTO = {applicationId: string;- membershipId: string;+ kind: TApplicationMemberKind;+ memberId: string;role: string;} & TProjectPermission;export type TRemoveApplicationMemberDTO = {applicationId: string;- membershipId: string;+ kind: TApplicationMemberKind;+ memberId: string;} & TProjectPermission;diff --git a/frontend/src/hooks/api/approvalPolicies/index.tsx b/frontend/src/hooks/api/approvalPolicies/index.tsxindex 926d421dec..b22f5ed295 100644--- a/frontend/src/hooks/api/approvalPolicies/index.tsx+++ b/frontend/src/hooks/api/approvalPolicies/index.tsx@@ -6,6 +6,7 @@ export {} from "./mutations";export { approvalPolicyQuery } from "./queries";export {+ ApprovalPolicyScope,type ApprovalPolicyStep,ApprovalPolicyType,ApproverType,diff --git a/frontend/src/hooks/api/approvalPolicies/queries.tsx b/frontend/src/hooks/api/approvalPolicies/queries.tsxindex 25fe9c6dd4..435b03e1ea 100644--- a/frontend/src/hooks/api/approvalPolicies/queries.tsx+++ b/frontend/src/hooks/api/approvalPolicies/queries.tsx@@ -28,8 +28,8 @@ export const approvalPolicyQuery = {policies: TApprovalPolicy[];}>(`/api/v1/approval-policies/${params.policyType}`, {params: {- projectId: params.projectId,- ...(params.applicationId && { applicationId: params.applicationId })+ scope: params.scope,+ id: params.scopeId}});return data.policies;diff --git a/frontend/src/hooks/api/approvalPolicies/types.ts b/frontend/src/hooks/api/approvalPolicies/types.tsindex 873f43b897..3bd1da764c 100644--- a/frontend/src/hooks/api/approvalPolicies/types.ts+++ b/frontend/src/hooks/api/approvalPolicies/types.ts@@ -4,6 +4,11 @@ export enum ApprovalPolicyType {CertCodeSigning = "cert-code-signing"}+export enum ApprovalPolicyScope {+ Project = "project",+ PkiApplication = "pki-application"+}+export enum ApproverType {Group = "group",User = "user"@@ -66,14 +71,16 @@ export type TApprovalPolicy = {};steps: ApprovalPolicyStep[];bypassForMachineIdentities?: boolean;- applicationId?: string | null;+ scopeType?: ApprovalPolicyScope | string | null;+ scopeId?: string | null;createdAt: string;updatedAt: string;};export type TCreateApprovalPolicyDTO = {policyType: ApprovalPolicyType;- projectId: string;+ scope: ApprovalPolicyScope;+ scopeId: string;name: string;maxRequestTtl?: string | null;conditions: PamAccessPolicyConditions | CertRequestPolicyConditions | CodeSigningPolicyConditions;@@ -83,7 +90,6 @@ export type TCreateApprovalPolicyDTO = {| CodeSigningPolicyConstraints;steps: ApprovalPolicyStep[];bypassForMachineIdentities?: boolean;- applicationId?: string;};export type TUpdateApprovalPolicyDTO = {@@ -110,8 +116,8 @@ export type TGetApprovalPolicyByIdDTO = {export type TListApprovalPoliciesDTO = {policyType: ApprovalPolicyType;- projectId: string;- applicationId?: string;+ scope: ApprovalPolicyScope;+ scopeId: string;};export type TDeleteApprovalPolicyDTO = {diff --git a/frontend/src/hooks/api/approvalRequests/queries.tsx b/frontend/src/hooks/api/approvalRequests/queries.tsxindex 80de955750..7b4290af7a 100644--- a/frontend/src/hooks/api/approvalRequests/queries.tsx+++ b/frontend/src/hooks/api/approvalRequests/queries.tsx@@ -28,8 +28,8 @@ export const approvalRequestQuery = {requests: TApprovalRequest[];}>(`/api/v1/approval-policies/${params.policyType}/requests`, {params: {- projectId: params.projectId,- ...(params.applicationId ? { applicationId: params.applicationId } : {})+ scope: params.scope,+ id: params.scopeId}});return data.requests;diff --git a/frontend/src/hooks/api/approvalRequests/types.ts b/frontend/src/hooks/api/approvalRequests/types.tsindex f88a7e0487..64ff16be79 100644--- a/frontend/src/hooks/api/approvalRequests/types.ts+++ b/frontend/src/hooks/api/approvalRequests/types.ts@@ -1,4 +1,4 @@-import { ApprovalPolicyType, ApproverType } from "../approvalPolicies";+import { ApprovalPolicyScope, ApprovalPolicyType, ApproverType } from "../approvalPolicies";export enum ApprovalRequestStatus {Pending = "pending",@@ -96,7 +96,8 @@ export type TApprovalRequest = {id: string;projectId: string;policyId: string;- applicationId?: string | null;+ scopeType?: ApprovalPolicyScope | string | null;+ scopeId?: string | null;type: ApprovalPolicyType;status: ApprovalRequestStatus;requesterId: string;@@ -115,7 +116,8 @@ export type TApprovalRequest = {export type TCreateApprovalRequestDTO = {policyType: ApprovalPolicyType;- projectId: string;+ scope: ApprovalPolicyScope;+ scopeId: string;justification?: string | null;requestDuration?: string | null;requestData: PamAccessRequestData | CertRequestRequestData | CodeSigningRequestData;@@ -128,8 +130,8 @@ export type TGetApprovalRequestByIdDTO = {export type TListApprovalRequestsDTO = {policyType: ApprovalPolicyType;- projectId: string;- applicationId?: string;+ scope: ApprovalPolicyScope;+ scopeId: string;};export type TApproveApprovalRequestDTO = {diff --git a/frontend/src/hooks/api/certManagerAccess/index.ts b/frontend/src/hooks/api/certManagerAccess/index.tsindex 41fee67462..45a91d256f 100644--- a/frontend/src/hooks/api/certManagerAccess/index.ts+++ b/frontend/src/hooks/api/certManagerAccess/index.ts@@ -25,5 +25,5 @@ export const rolesBase = (type?: string, projectId?: string): string =>export const availableIdentitiesUrl = (type?: string, projectId?: string): string =>isCertManagerProject(type)- ? "/api/v1/cert-manager/access/identities/available"+ ? "/api/v1/cert-manager/access/available-identities": `/api/v1/projects/${projectId ?? ""}/memberships/available-identities`;diff --git a/frontend/src/hooks/api/pkiApplications/mutations.ts b/frontend/src/hooks/api/pkiApplications/mutations.tsindex 2ec0c67c40..0f16419c06 100644--- a/frontend/src/hooks/api/pkiApplications/mutations.ts+++ b/frontend/src/hooks/api/pkiApplications/mutations.ts@@ -94,13 +94,19 @@ export const useDetachPkiApplicationProfile = () => {});};+const memberPathSegment = (kind: "user" | "identity" | "group") => {+ if (kind === "user") return "users";+ if (kind === "identity") return "identities";+ return "groups";+};+export const useAddPkiApplicationMember = () => {const qc = useQueryClient();return useMutation({- mutationFn: async ({ applicationId, ...body }: TAddPkiApplicationMemberDTO) => {+ mutationFn: async ({ applicationId, kind, memberId, role }: TAddPkiApplicationMemberDTO) => {const { data } = await apiRequest.post<{ membership: TPkiApplicationMember }>(- `${BASE_URL}/${applicationId}/memberships`,- body+ `${BASE_URL}/${applicationId}/${memberPathSegment(kind)}/${memberId}`,+ { role });return data.membership;},@@ -113,12 +119,13 @@ export const useUpdatePkiApplicationMemberRole = () => {return useMutation({mutationFn: async ({applicationId,- membershipId,- ...body+ kind,+ memberId,+ role}: TUpdatePkiApplicationMemberRoleDTO) => {const { data } = await apiRequest.patch<{ membership: TPkiApplicationMember }>(- `${BASE_URL}/${applicationId}/memberships/${membershipId}`,- body+ `${BASE_URL}/${applicationId}/${memberPathSegment(kind)}/${memberId}`,+ { role });return data.membership;},@@ -129,11 +136,11 @@ export const useUpdatePkiApplicationMemberRole = () => {export const useRemovePkiApplicationMember = () => {const qc = useQueryClient();return useMutation({- mutationFn: async ({ applicationId, membershipId }: TRemovePkiApplicationMemberDTO) => {+ mutationFn: async ({ applicationId, kind, memberId }: TRemovePkiApplicationMemberDTO) => {const { data } = await apiRequest.delete<{membershipId: string;applicationId: string;- }>(`${BASE_URL}/${applicationId}/memberships/${membershipId}`);+ }>(`${BASE_URL}/${applicationId}/${memberPathSegment(kind)}/${memberId}`);return data;},onSuccess: () => invalidateAll(qc)diff --git a/frontend/src/hooks/api/pkiApplications/queries.ts b/frontend/src/hooks/api/pkiApplications/queries.tsindex 0a496ccc97..f09138ff9b 100644--- a/frontend/src/hooks/api/pkiApplications/queries.ts+++ b/frontend/src/hooks/api/pkiApplications/queries.ts@@ -116,10 +116,22 @@ 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;+ const [users, identities, groups] = await Promise.all([+ apiRequest.get<{ memberships: TPkiApplicationMember[] }>(+ `${BASE_URL}/${applicationId}/users`+ ),+ apiRequest.get<{ memberships: TPkiApplicationMember[] }>(+ `${BASE_URL}/${applicationId}/identities`+ ),+ apiRequest.get<{ memberships: TPkiApplicationMember[] }>(+ `${BASE_URL}/${applicationId}/groups`+ )+ ]);+ return [+ ...users.data.memberships,+ ...identities.data.memberships,+ ...groups.data.memberships+ ];},enabled: Boolean(applicationId)});diff --git a/frontend/src/hooks/api/pkiApplications/types.ts b/frontend/src/hooks/api/pkiApplications/types.tsindex 4350fc15e2..d7a8a0416c 100644--- a/frontend/src/hooks/api/pkiApplications/types.ts+++ b/frontend/src/hooks/api/pkiApplications/types.ts@@ -107,23 +107,26 @@ export type TDetachPkiApplicationProfileDTO = {profileId: string;};+export type TPkiApplicationMemberKind = "user" | "identity" | "group";+export type TAddPkiApplicationMemberDTO = {applicationId: string;- userId?: string;- identityId?: string;- groupId?: string;+ kind: TPkiApplicationMemberKind;+ memberId: string;role: string;};export type TUpdatePkiApplicationMemberRoleDTO = {applicationId: string;- membershipId: string;+ kind: TPkiApplicationMemberKind;+ memberId: string;role: string;};export type TRemovePkiApplicationMemberDTO = {applicationId: string;- membershipId: string;+ kind: TPkiApplicationMemberKind;+ memberId: string;};export type TListPkiApplicationsResponse = {diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/CertManagerNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/CertManagerNav.tsxindex d34f385d66..a4d5bef959 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/CertManagerNav.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/CertManagerNav.tsx@@ -16,7 +16,11 @@ import {import { ResourceIcon, 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 {+ approvalPolicyQuery,+ ApprovalPolicyScope,+ ApprovalPolicyType+} from "@app/hooks/api/approvalPolicies";import { approvalRequestQuery } from "@app/hooks/api/approvalRequests";import { ApprovalRequestStatus } from "@app/hooks/api/approvalRequests/types";import { useGetPkiAlertsV2 } from "@app/hooks/api/pkiAlertsV2";@@ -47,11 +51,19 @@ export const CertManagerNav = ({enabled: isCertManagerAdmin && Boolean(projectId)});const { data: policies } = useQuery({- ...approvalPolicyQuery.list({ projectId, policyType: ApprovalPolicyType.CertRequest }),+ ...approvalPolicyQuery.list({+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId,+ policyType: ApprovalPolicyType.CertRequest+ }),enabled: isCertManagerAdmin && Boolean(projectId)});const { data: pendingRequestsCount = 0 } = useQuery({- ...approvalRequestQuery.list({ projectId, policyType: ApprovalPolicyType.CertRequest }),+ ...approvalRequestQuery.list({+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId,+ policyType: ApprovalPolicyType.CertRequest+ }),enabled: Boolean(projectId),select: (requests) => requests.filter((r) => r.status === ApprovalRequestStatus.Pending).length});@@ -60,7 +72,7 @@ export const CertManagerNav = ({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 hasLegacyPolicies = Boolean(policies?.some((p) => !p.scopeType));const hasAnyLegacy = hasLegacyAlerts || hasLegacySyncs || hasLegacyPolicies;const overviewItems: NavItem[] = [diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsxindex 8f682491fc..bddbfc0cc6 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/ProjectNavLink.tsx@@ -71,7 +71,7 @@ export const ProjectNavLink = ({<item.icon className="size-4" /><span>{item.label}</span>{Boolean(item.badgeCount) && (- <Badge variant="warning" isSquare>+ <Badge variant="warning" isSquare className="ml-auto">{item.badgeCount}</Badge>)}diff --git a/frontend/src/layouts/PkiManagerLayout/components/CertManagerInstanceBanner.tsx b/frontend/src/layouts/PkiManagerLayout/components/CertManagerInstanceBanner.tsxindex 0488955df5..8309f38085 100644--- a/frontend/src/layouts/PkiManagerLayout/components/CertManagerInstanceBanner.tsx+++ b/frontend/src/layouts/PkiManagerLayout/components/CertManagerInstanceBanner.tsx@@ -1,7 +1,8 @@+import { faWarning } from "@fortawesome/free-solid-svg-icons";+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { useParams } from "@tanstack/react-router";-import { Info } from "lucide-react";-import { Alert, Button } from "@app/components/v3";+import { Button } from "@app/components/v2";import { useOrgPermission } from "@app/context";import {OrgPermissionCertManagerActions,@@ -28,25 +29,25 @@ export const CertManagerInstanceBanner = () => {const otherCount = Math.max(0, data.projects.length - 1);const isViewingActive = activeProject?.id === projectId;- const variant = isViewingActive ? "info" : "warning";const message = isViewingActive? `Your organization has ${otherCount} other Cert Manager ${otherCount === 1 ? "workspace" : "workspaces"}, consolidate to a single workspace, multi-project Cert Manager will be deprecated soon.`: `Legacy Cert Manager instance (active is ${activeProject?.name ?? "not set"}) — consolidate to a single instance, multi-project Cert Manager will be deprecated soon.`;return (<>- <div className="px-12 py-3">- <Alert variant={variant} className="flex items-center justify-between gap-3 py-2">- <div className="flex items-center gap-2 text-sm">- <Info className="size-4 shrink-0" />- <span>{message}</span>- </div>- {canManage && (- <Button size="xs" variant="outline" onClick={() => handlePopUpOpen("activeInstance")}>- Manage instances- </Button>- )}- </Alert>+ <div className="flex w-full items-center border-b border-yellow/50 bg-yellow/30 px-4 py-2 text-sm text-yellow-200">+ <FontAwesomeIcon icon={faWarning} className="mr-2.5 text-base text-yellow" />+ <span>{message}</span>+ {canManage && (+ <Button+ size="xs"+ variant="outline_bg"+ className="ml-auto"+ onClick={() => handlePopUpOpen("activeInstance")}+ >+ Manage instances+ </Button>+ )}</div><ActiveInstanceModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />diff --git a/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ApplicationSelect.tsx b/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ApplicationSelect.tsxindex ce734bfe44..d621cc3e8a 100644--- a/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ApplicationSelect.tsx+++ b/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ApplicationSelect.tsx@@ -46,19 +46,20 @@ const ApplicationSelectInner = ({return (<div className="mr-2 flex min-w-16 items-center gap-1 pr-1 pl-1"><Popover open={open} onOpenChange={setOpen}>- <PopoverAnchor className="absolute left-18" />- <Link- to={- `/organizations/${orgId}/projects/cert-manager/${projectId}/applications/${applicationName}` as never- }- className="group flex cursor-pointer items-center gap-x-2 overflow-hidden text-sm text-white"- >- <ResourceIcon className="size-[14px] shrink-0 text-project" />- <span className="truncate">{displayName}</span>- <Badge variant="project" className="hidden lg:inline-flex">- Application- </Badge>- </Link>+ <PopoverAnchor asChild>+ <Link+ to={+ `/organizations/${orgId}/projects/cert-manager/${projectId}/applications/${applicationName}` as never+ }+ className="group flex cursor-pointer items-center gap-x-2 overflow-hidden text-sm text-white"+ >+ <ResourceIcon className="size-[14px] shrink-0 text-project" />+ <span className="truncate">{displayName}</span>+ <Badge variant="project" className="hidden lg:inline-flex">+ Application+ </Badge>+ </Link>+ </PopoverAnchor><PopoverTrigger asChild><IconButton variant="ghost" size="xs" aria-label="switch-application"><ChevronsUpDown />diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsxindex 33710e9211..62dba7e402 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/AddApplicationMemberModal.tsx@@ -1,6 +1,5 @@import { useMemo, useState } from "react";import { HardDriveIcon, UserIcon, UsersIcon } from "lucide-react";-import { twMerge } from "tailwind-merge";import { z } from "zod";import { createNotification } from "@app/components/notifications";@@ -8,6 +7,7 @@ import { FilterableSelect, FormControl } from "@app/components/v2";import { CreatableSelect } from "@app/components/v2/CreatableSelect";import {Button,+ ButtonGroup,Dialog,DialogContent,DialogDescription,@@ -168,7 +168,6 @@ export const AddApplicationMemberModal = ({const existing = selectedUsers.filter((u) => !u.isNew);const newInviteEmails = selectedUsers.filter((u) => u.isNew).map((u) => u.value);- let invitedMemberships: CertManagerInviteResponse["memberships"] = [];if (newInviteEmails.length > 0 || existing.length > 0) {const usernames = [...newInviteEmails,@@ -179,29 +178,37 @@ export const AddApplicationMemberModal = ({}).filter((x): x is string => Boolean(x))];- const { data } = await apiRequest.post<CertManagerInviteResponse>(- "/api/v1/cert-manager/access/users",- { usernames, roleSlugs: ["member"] }- );- invitedMemberships = data.memberships ?? [];+ await apiRequest.post<CertManagerInviteResponse>("/api/v1/cert-manager/access/users", {+ usernames,+ roleSlugs: ["member"]+ });}const userIds: string[] = [];existing.forEach((u) => userIds.push(u.value));if (newInviteEmails.length > 0) {const refreshed = (await usersQuery.refetch()).data ?? [];+ const unresolved: string[] = [];newInviteEmails.forEach((email) => {- const fromResponse = invitedMemberships.find((m) => Boolean(m.userId));const fromOrg = refreshed.find((o) => o.user.email === email || o.user.username === email || o.inviteEmail === email);- if (fromOrg?.user.id) userIds.push(fromOrg.user.id);- else if (fromResponse?.userId) userIds.push(fromResponse.userId);+ if (fromOrg?.user.id) {+ userIds.push(fromOrg.user.id);+ return;+ }+ unresolved.push(email);});+ if (unresolved.length > 0) {+ createNotification({+ type: "warning",+ text: `Invited ${unresolved.length === 1 ? "user" : "users"} but couldn't add to the Application yet: ${unresolved.join(", ")}. Refresh and add them once they appear in the org.`+ });+ }}await runSequential(userIds, async (userId) => {- await addMember.mutateAsync({ applicationId, userId, role });+ await addMember.mutateAsync({ applicationId, kind: "user", memberId: userId, role });});};@@ -234,14 +241,14 @@ export const AddApplicationMemberModal = ({});await runSequential(identityIds, async (identityId) => {- await addMember.mutateAsync({ applicationId, identityId, role });+ await addMember.mutateAsync({ applicationId, kind: "identity", memberId: identityId, role });});};const submitGroups = async () => {if (selectedGroups.length === 0) return;await runSequential(selectedGroups, async (item) => {- await addMember.mutateAsync({ applicationId, groupId: item.value, role });+ await addMember.mutateAsync({ applicationId, kind: "group", memberId: item.value, role });});};@@ -291,28 +298,26 @@ export const AddApplicationMemberModal = ({</DialogHeader><div className="space-y-4">- <div className="flex gap-1 rounded-md border border-mineshaft-600 bg-mineshaft-800 p-1">+ <ButtonGroup className="w-full">{TYPE_OPTIONS.map((opt) => {const Icon = opt.icon;const active = type === opt.value;return (- <button+ <Buttonkey={opt.value}type="button"+ variant={active ? "project" : "outline"}+ size="sm"+ className="flex-1"onClick={() => setType(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"- )}+ aria-pressed={active}>- <Icon size={14} />+ <Icon />{opt.label}- </button>+ </Button>);})}- </div>+ </ButtonGroup>{type === "user" && (<FormControldiff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationMembersTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationMembersTab.tsxindex 019394ca5d..46e7715396 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationMembersTab.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationMembersTab.tsx@@ -64,11 +64,13 @@ const displayPrimary = (m: TPkiApplicationMember): string => {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;+const memberRef = (+ m: TPkiApplicationMember+): { kind: "user" | "identity" | "group"; memberId: string } => {+ if (m.actorUserId) return { kind: "user", memberId: m.actorUserId };+ if (m.actorIdentityId) return { kind: "identity", memberId: m.actorIdentityId };+ if (m.actorGroupId) return { kind: "group", memberId: m.actorGroupId };+ throw new Error("Membership has no associated user, identity, or group.");};export const ApplicationMembersTab = ({ members, applicationId }: Props) => {@@ -118,12 +120,10 @@ export const ApplicationMembersTab = ({ members, applicationId }: Props) => {<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>@@ -135,7 +135,7 @@ export const ApplicationMembersTab = ({ members, applicationId }: Props) => {try {await updateRole.mutateAsync({applicationId,- membershipId: m.membershipId,+ ...memberRef(m),role});createNotification({ type: "success", text: "Role updated" });@@ -205,7 +205,7 @@ export const ApplicationMembersTab = ({ members, applicationId }: Props) => {try {await removeMember.mutateAsync({applicationId,- membershipId: m.membershipId+ ...memberRef(m)});createNotification({ type: "success", text: "Member removed" });handlePopUpClose("removeMember");diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsxindex 5c52de936c..f9b6c2d7a7 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ApplicationSettingsTab.tsx@@ -54,10 +54,10 @@ import {TooltipContent,TooltipTrigger} from "@app/components/v3";-import { useProject } from "@app/context";import { usePopUp } from "@app/hooks";import {approvalPolicyQuery,+ ApprovalPolicyScope,ApprovalPolicyType,CertRequestPolicyConditions,TApprovalPolicy,@@ -116,12 +116,11 @@ const ApplicationPoliciesTable = ({onEdit,onDelete}: ApplicationPoliciesTableProps) => {- const { currentProject } = useProject();const { data: policies = [], isPending } = useQuery(approvalPolicyQuery.list({policyType: ApprovalPolicyType.CertRequest,- projectId: currentProject?.id ?? "",- applicationId+ scope: ApprovalPolicyScope.PkiApplication,+ scopeId: applicationId}));@@ -176,7 +175,7 @@ const ApplicationPoliciesTable = ({<TableCell isTruncatable><div className="flex items-center gap-x-2"><span className="font-medium text-foreground">{policy.name}</span>- {!policy.applicationId ? (+ {policy.scopeType !== ApprovalPolicyScope.PkiApplication ? (<Badge variant="neutral" className="uppercase">Legacy</Badge>@@ -469,7 +468,7 @@ export const ApplicationSettingsTab = ({ application, profiles }: Props) => {<Card><CardHeader className="grid-cols-[1fr_auto]"><CardTitle>General</CardTitle>- <CardDescription>Edit core metadata for this Application.</CardDescription>+ <CardDescription>Edit application metadata.</CardDescription><CardAction className="col-start-2 row-span-2 row-start-1 self-start justify-self-end"><IconButtonvariant="ghost"diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningPolicyTab/components/CodeSigningPoliciesTable.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningPolicyTab/components/CodeSigningPoliciesTable.tsxindex 1b21dabfa4..fbd11f1ddd 100644--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningPolicyTab/components/CodeSigningPoliciesTable.tsx+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningPolicyTab/components/CodeSigningPoliciesTable.tsx@@ -29,6 +29,7 @@ import {import { useProject } from "@app/context";import {approvalPolicyQuery,+ ApprovalPolicyScope,ApprovalPolicyType,TApprovalPolicy} from "@app/hooks/api/approvalPolicies";@@ -48,7 +49,8 @@ export const CodeSigningPoliciesTable = ({ handlePopUpOpen }: Props) => {const { data: policies = [], isPending: isPoliciesLoading } = useQuery(approvalPolicyQuery.list({policyType: ApprovalPolicyType.CertCodeSigning,- projectId+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId}));diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningPolicyTab/components/CodeSigningPolicyModal.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningPolicyTab/components/CodeSigningPolicyModal.tsxindex 62d2ae3fb1..268f15f348 100644--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningPolicyTab/components/CodeSigningPolicyModal.tsx+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningPolicyTab/components/CodeSigningPolicyModal.tsx@@ -8,6 +8,7 @@ import { createNotification } from "@app/components/notifications";import { Button, Modal, ModalContent } from "@app/components/v2";import { useProject } from "@app/context";import {+ ApprovalPolicyScope,ApprovalPolicyType,TApprovalPolicy,useCreateApprovalPolicy,@@ -136,7 +137,8 @@ export const CodeSigningPolicyModal = ({ popUp, handlePopUpToggle }: Props) => {} else {await createPolicy({policyType: ApprovalPolicyType.CertCodeSigning,- projectId: currentProject.id,+ scope: ApprovalPolicyScope.Project,+ scopeId: currentProject.id,conditions: [],...cleanedData});diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningRequestsTab/CodeSigningRequestsTab.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningRequestsTab/CodeSigningRequestsTab.tsxindex 5e530550b2..9bad5f5334 100644--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningRequestsTab/CodeSigningRequestsTab.tsx+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningRequestsTab/CodeSigningRequestsTab.tsx@@ -44,7 +44,11 @@ import {ProjectPermissionSub} from "@app/context/ProjectPermissionContext";import { usePagination } from "@app/hooks";-import { ApprovalPolicyType, ApproverType } from "@app/hooks/api/approvalPolicies";+import {+ ApprovalPolicyScope,+ ApprovalPolicyType,+ ApproverType+} from "@app/hooks/api/approvalPolicies";import {approvalRequestQuery,ApprovalRequestStatus,@@ -111,7 +115,8 @@ export const CodeSigningRequestsTab = () => {const { data: requests = [], isPending: isRequestsLoading } = useQuery(approvalRequestQuery.list({policyType: ApprovalPolicyType.CertCodeSigning,- projectId+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId}));diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningRequestsTab/RequestSigningAccessModal.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningRequestsTab/RequestSigningAccessModal.tsxindex 5deb28b424..8320977c50 100644--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningRequestsTab/RequestSigningAccessModal.tsx+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/CodeSigningRequestsTab/RequestSigningAccessModal.tsx@@ -19,6 +19,7 @@ import {import { useProject } from "@app/context";import {approvalPolicyQuery,+ ApprovalPolicyScope,ApprovalPolicyType,TApprovalPolicy} from "@app/hooks/api/approvalPolicies";@@ -92,7 +93,8 @@ const Content = ({ onOpenChange }: Props) => {const { data: policies = [] } = useQuery(approvalPolicyQuery.list({policyType: ApprovalPolicyType.CertCodeSigning,- projectId+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId}));@@ -185,7 +187,8 @@ const Content = ({ onOpenChange }: Props) => {await createApprovalRequest({policyType: ApprovalPolicyType.CertCodeSigning,- projectId,+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId,justification: formData.justification || null,requestData: {signerId: selectedSigner.id,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.tsxindex 2ee0022748..2c6dd2b176 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@@ -29,6 +29,7 @@ import {import { useProject } from "@app/context";import {approvalPolicyQuery,+ ApprovalPolicyScope,ApprovalPolicyType,CertRequestPolicyConditions,TApprovalPolicy@@ -50,8 +51,8 @@ export const PoliciesTable = ({ handlePopUpOpen, applicationId }: Props) => {const { data: policies = [], isPending: isPoliciesLoading } = useQuery(approvalPolicyQuery.list({policyType: ApprovalPolicyType.CertRequest,- projectId,- applicationId+ scope: applicationId ? ApprovalPolicyScope.PkiApplication : ApprovalPolicyScope.Project,+ scopeId: applicationId || projectId}));@@ -88,7 +89,7 @@ export const PoliciesTable = ({ handlePopUpOpen, applicationId }: Props) => {<Td><div className="flex items-center gap-x-2"><span className="text-sm font-medium text-mineshaft-100">{policy.name}</span>- {!policy.applicationId && (+ {policy.scopeType !== ApprovalPolicyScope.PkiApplication && (<span className="rounded bg-mineshaft-600 px-2 py-0.5 text-[10px] tracking-wide text-mineshaft-200 uppercase">Legacy</span>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.tsxindex 815f0afcb7..0fd047424e 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@@ -8,6 +8,7 @@ import { createNotification } from "@app/components/notifications";import { Button, Modal, ModalContent } from "@app/components/v2";import { useProject } from "@app/context";import {+ ApprovalPolicyScope,ApprovalPolicyType,CertRequestPolicyConditions,TApprovalPolicy,@@ -120,8 +121,8 @@ export const PolicyModal = ({ popUp, handlePopUpToggle, applicationId }: Props)} else {await createPolicy({policyType: ApprovalPolicyType.CertRequest,- projectId: currentProject.id,- ...(applicationId && { applicationId }),+ scope: applicationId ? ApprovalPolicyScope.PkiApplication : ApprovalPolicyScope.Project,+ scopeId: applicationId || currentProject.id,...data});createNotification({diff --git a/frontend/src/pages/cert-manager/ApprovalsPage/components/RequestsTab/RequestsTab.tsx b/frontend/src/pages/cert-manager/ApprovalsPage/components/RequestsTab/RequestsTab.tsxindex 6111665b27..a0fe7f0856 100644--- a/frontend/src/pages/cert-manager/ApprovalsPage/components/RequestsTab/RequestsTab.tsx+++ b/frontend/src/pages/cert-manager/ApprovalsPage/components/RequestsTab/RequestsTab.tsx@@ -40,7 +40,11 @@ import { Badge } from "@app/components/v3";import { useOrganization, useProject, useProjectPermission, useUser } from "@app/context";import { getUserTablePreference, PreferenceKey } from "@app/helpers/userTablePreferences";import { usePagination } from "@app/hooks";-import { ApprovalPolicyType, ApproverType } from "@app/hooks/api/approvalPolicies";+import {+ ApprovalPolicyScope,+ ApprovalPolicyType,+ ApproverType+} from "@app/hooks/api/approvalPolicies";import {approvalRequestQuery,ApprovalRequestStatus,@@ -104,7 +108,8 @@ export const RequestsTab = () => {const { data: requests = [], isPending: isRequestsLoading } = useQuery(approvalRequestQuery.list({policyType: ApprovalPolicyType.CertRequest,- projectId+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId}));diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerModal.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerModal.tsxindex f5af615026..88102524ab 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerModal.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerModal.tsx@@ -16,7 +16,11 @@ import {SelectItem,TextArea} from "@app/components/v2";-import { approvalPolicyQuery, ApprovalPolicyType } from "@app/hooks/api/approvalPolicies";+import {+ approvalPolicyQuery,+ ApprovalPolicyScope,+ ApprovalPolicyType+} from "@app/hooks/api/approvalPolicies";import { useListWorkspaceCertificates } from "@app/hooks/api/projects";import { useCreateSigner } from "@app/hooks/api/signers";import { slugSchema } from "@app/lib/schemas";@@ -55,7 +59,8 @@ export const CreateSignerModal = ({ isOpen, onOpenChange, projectId }: Props) =>const { data: policies = [], isPending: isPoliciesLoading } = useQuery(approvalPolicyQuery.list({policyType: ApprovalPolicyType.CertCodeSigning,- projectId+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId}));diff --git a/frontend/src/pages/cert-manager/DashboardPage/route-index.tsx b/frontend/src/pages/cert-manager/DashboardPage/route-index.tsxindex a91fd8d56e..735af833d7 100644--- a/frontend/src/pages/cert-manager/DashboardPage/route-index.tsx+++ b/frontend/src/pages/cert-manager/DashboardPage/route-index.tsx@@ -1,11 +1,22 @@import { createFileRoute, redirect } from "@tanstack/react-router";+import { fetchUserProjectPermissions, roleQueryKeys } from "@app/hooks/api/roles/queries";+export const Route = createFileRoute("/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/")({- beforeLoad: ({ params }) => {+ beforeLoad: async ({ params, context }) => {+ const data = await context.queryClient.ensureQueryData({+ queryKey: roleQueryKeys.getUserProjectPermissions({ projectId: params.projectId }),+ queryFn: () => fetchUserProjectPermissions({ projectId: params.projectId })+ });++ const isAdmin = data.memberships?.some((m) => m.roles.some((r) => r.role === "admin"));+throw redirect({- to: "/organizations/$orgId/projects/cert-manager/$projectId/overview",+ to: isAdmin+ ? "/organizations/$orgId/projects/cert-manager/$projectId/overview"+ : "/organizations/$orgId/projects/cert-manager/$projectId/applications",params});}diff --git a/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx b/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsxindex 9c85895ac9..c3c5a1c5a0 100644--- a/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx+++ b/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx@@ -33,11 +33,12 @@ import {TableRow} from "@app/components/v3";import { useDebounce } from "@app/hooks";-import { ApprovalPolicyType } from "@app/hooks/api/approvalPolicies";+import { ApprovalPolicyScope, ApprovalPolicyType } from "@app/hooks/api/approvalPolicies";import {approvalRequestQuery,ApprovalRequestStatus,CertRequestRequestData,+ CodeSigningRequestData,TApprovalRequest} from "@app/hooks/api/approvalRequests";import { useListPkiApplications } from "@app/hooks/api/pkiApplications";@@ -94,6 +95,17 @@ const isCertRequestData = (data: unknown): data is { requestData: CertRequestReq);};+const isCodeSigningData = (data: unknown): data is { requestData: CodeSigningRequestData } => {+ return Boolean(+ data &&+ typeof data === "object" &&+ "requestData" in data &&+ data.requestData &&+ typeof data.requestData === "object" &&+ "signerName" in (data.requestData as object)+ );+};+export const RequestsPage = () => {const { projectId, orgId } = useParams({ strict: false }) as {projectId?: string;@@ -109,6 +121,12 @@ export const RequestsPage = () => {const [searchInput, setSearchInput] = useState("");const [debouncedSearch] = useDebounce(searchInput, 300);+ const [signingStatusFilters, setSigningStatusFilters] = useState<Set<StatusFilter>>(+ () => new Set<StatusFilter>(["pending"])+ );+ const [signingSearchInput, setSigningSearchInput] = useState("");+ const [debouncedSigningSearch] = useDebounce(signingSearchInput, 300);+const toggleStatusFilter = (key: StatusFilter) => {setStatusFilters((prev) => {const next = new Set(prev);@@ -119,10 +137,29 @@ export const RequestsPage = () => {};const isFiltered = statusFilters.size > 0;+ const toggleSigningStatusFilter = (key: StatusFilter) => {+ setSigningStatusFilters((prev) => {+ const next = new Set(prev);+ if (next.has(key)) next.delete(key);+ else next.add(key);+ return next;+ });+ };+ const isSigningFiltered = signingStatusFilters.size > 0;+const { data: requests = [], isPending: isRequestsLoading } = useQuery(approvalRequestQuery.list({policyType: ApprovalPolicyType.CertRequest,- projectId: projectId ?? ""+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId ?? ""+ })+ );++ const { data: signingRequests = [], isPending: isSigningRequestsLoading } = useQuery(+ approvalRequestQuery.list({+ policyType: ApprovalPolicyType.CertCodeSigning,+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId ?? ""}));@@ -158,21 +195,23 @@ export const RequestsPage = () => {});}, [requests, statusFilters, debouncedSearch]);- const counts = useMemo(() => {- const result: Record<StatusFilter, number> = { pending: 0, approved: 0, rejected: 0 };- (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]);+ const filteredSigning = useMemo(() => {+ const norm = debouncedSigningSearch.trim().toLowerCase();+ const activeFilters = STATUS_FILTERS.filter((f) => signingStatusFilters.has(f.key));+ const matchesStatus = (s: ApprovalRequestStatus) =>+ activeFilters.length === 0 || activeFilters.some((f) => f.matches(s));++ return (signingRequests as TApprovalRequest[])+ .filter((r) => matchesStatus(r.status as ApprovalRequestStatus))+ .filter((r) => {+ if (!norm) return true;+ const signerName = isCodeSigningData(r.requestData)+ ? (r.requestData.requestData.signerName ?? "")+ : "";+ const requester = `${r.requesterName} ${r.requesterEmail}`;+ return signerName.toLowerCase().includes(norm) || requester.toLowerCase().includes(norm);+ });+ }, [signingRequests, signingStatusFilters, debouncedSigningSearch]);return (<>@@ -246,7 +285,7 @@ export const RequestsPage = () => {toggleStatusFilter(f.key);}}>- {f.label} ({counts[f.key]})+ {f.label}</DropdownMenuCheckboxItem>))}</DropdownMenuContent>@@ -293,7 +332,9 @@ export const RequestsPage = () => {: null;const cn = certData?.certificateRequest?.commonName ?? "—";const profile = certData?.profileName ?? "—";- const app = r.applicationId ? appById.get(r.applicationId) : null;+ const requestAppId =+ r.scopeType === ApprovalPolicyScope.PkiApplication ? r.scopeId : null;+ const app = requestAppId ? appById.get(requestAppId) : null;const badge = STATUS_BADGE[r.status as ApprovalRequestStatus] ?? {label: r.status,variant: "neutral" as const@@ -359,20 +400,120 @@ export const RequestsPage = () => {<CardHeader><CardTitle>Signing Requests</CardTitle><CardDescription>- Code-signing requests live on the Code Signing page. Visit Signers to review- pending signing operations.+ Code-signing approval workflows triggered by a Signer policy.</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>+ <div className="my-4 flex gap-2">+ <InputGroup className="flex-1">+ <InputGroupAddon>+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ placeholder="Search by signer or requester…"+ value={signingSearchInput}+ onChange={(e) => setSigningSearchInput(e.target.value)}+ />+ </InputGroup>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="Filter by status"+ variant={isSigningFiltered ? "project" : "outline"}+ >+ <FilterIcon className="size-4" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuLabel>Filter by status</DropdownMenuLabel>+ {STATUS_FILTERS.map((f) => (+ <DropdownMenuCheckboxItem+ key={f.key}+ checked={signingStatusFilters.has(f.key)}+ onClick={(e) => {+ e.preventDefault();+ toggleSigningStatusFilter(f.key);+ }}+ >+ {f.label}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>++ {isSigningRequestsLoading && (+ <Empty>+ <EmptyHeader>+ <EmptyTitle>Loading…</EmptyTitle>+ </EmptyHeader>+ </Empty>+ )}+ {!isSigningRequestsLoading && filteredSigning.length === 0 && (+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>+ {signingStatusFilters.size === 1 && signingStatusFilters.has("pending")+ ? "No requests pending review"+ : "No requests"}+ </EmptyTitle>+ <EmptyDescription>+ Code-signing approval workflows from any Signer will appear here.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ )}+ {!isSigningRequestsLoading && filteredSigning.length > 0 && (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Signer</TableHead>+ <TableHead>Requester</TableHead>+ <TableHead>Status</TableHead>+ <TableHead>Requested</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {filteredSigning.map((r) => {+ const signingData = isCodeSigningData(r.requestData)+ ? r.requestData.requestData+ : null;+ const signerName = signingData?.signerName ?? "—";+ const badge = STATUS_BADGE[r.status as ApprovalRequestStatus] ?? {+ label: r.status,+ variant: "neutral" as const+ };++ return (+ <TableRow+ key={r.id}+ className="cursor-pointer"+ onClick={() =>+ navigate({+ to: `/organizations/${orgId}/projects/cert-manager/${projectId}/approvals/${r.id}` as never,+ search: {+ policyType: ApprovalPolicyType.CertCodeSigning,+ from: "root-requests"+ } as never+ } as never)+ }+ >+ <TableCell isTruncatable className="font-mono">+ {signerName}+ </TableCell>+ <TableCell>{r.requesterName || r.requesterEmail || "—"}</TableCell>+ <TableCell>+ <Badge variant={badge.variant}>{badge.label}</Badge>+ </TableCell>+ <TableCell className="text-accent">+ {formatRelative(r.createdAt)}+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ )}</CardContent></Card></TabPanel>diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal.tsxindex 32eb2303c0..a37c8f332b 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal.tsx+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal.tsx@@ -14,7 +14,11 @@ import {SelectItem,TextArea} from "@app/components/v2";-import { approvalPolicyQuery, ApprovalPolicyType } from "@app/hooks/api/approvalPolicies";+import {+ approvalPolicyQuery,+ ApprovalPolicyScope,+ ApprovalPolicyType+} from "@app/hooks/api/approvalPolicies";import { TSigner, useUpdateSigner } from "@app/hooks/api/signers";import { slugSchema } from "@app/lib/schemas";@@ -39,7 +43,8 @@ export const EditSignerModal = ({ isOpen, onOpenChange, signer, projectId }: Proconst { data: policies = [], isPending: isPoliciesLoading } = useQuery(approvalPolicyQuery.list({policyType: ApprovalPolicyType.CertCodeSigning,- projectId+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId}));diff --git a/frontend/src/pages/pam/ApprovalsPage/components/ApprovalRequestTab/ApprovalRequestTab.tsx b/frontend/src/pages/pam/ApprovalsPage/components/ApprovalRequestTab/ApprovalRequestTab.tsxindex ada1ebc970..3fcaea14eb 100644--- a/frontend/src/pages/pam/ApprovalsPage/components/ApprovalRequestTab/ApprovalRequestTab.tsx+++ b/frontend/src/pages/pam/ApprovalsPage/components/ApprovalRequestTab/ApprovalRequestTab.tsx@@ -40,7 +40,11 @@ import { Badge } from "@app/components/v3";import { useOrganization, useProject, useProjectPermission, useUser } from "@app/context";import { getUserTablePreference, PreferenceKey } from "@app/helpers/userTablePreferences";import { usePagination } from "@app/hooks";-import { ApprovalPolicyType, ApproverType } from "@app/hooks/api/approvalPolicies";+import {+ ApprovalPolicyScope,+ ApprovalPolicyType,+ ApproverType+} from "@app/hooks/api/approvalPolicies";import {approvalRequestQuery,ApprovalRequestStatus,@@ -104,7 +108,8 @@ export const ApprovalRequestTab = () => {const { data: requests = [], isPending: isRequestsLoading } = useQuery(approvalRequestQuery.list({policyType: ApprovalPolicyType.PamAccess,- projectId+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId}));diff --git a/frontend/src/pages/pam/ApprovalsPage/components/PolicyTab/components/PoliciesTable.tsx b/frontend/src/pages/pam/ApprovalsPage/components/PolicyTab/components/PoliciesTable.tsxindex 12eeb57337..593c8d9a5c 100644--- a/frontend/src/pages/pam/ApprovalsPage/components/PolicyTab/components/PoliciesTable.tsx+++ b/frontend/src/pages/pam/ApprovalsPage/components/PolicyTab/components/PoliciesTable.tsx@@ -35,6 +35,7 @@ import { getMemberLabel } from "@app/helpers/members";import { useGetWorkspaceUsers, useListWorkspaceGroups } from "@app/hooks/api";import {approvalPolicyQuery,+ ApprovalPolicyScope,ApprovalPolicyType,ApproverType,PamAccessPolicyConditions,@@ -58,7 +59,8 @@ export const PoliciesTable = ({ handlePopUpOpen }: Props) => {const { data: policies = [], isPending: isPoliciesLoading } = useQuery(approvalPolicyQuery.list({policyType: ApprovalPolicyType.PamAccess,- projectId+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId}));diff --git a/frontend/src/pages/pam/ApprovalsPage/components/PolicyTab/components/PolicyModal.tsx b/frontend/src/pages/pam/ApprovalsPage/components/PolicyTab/components/PolicyModal.tsxindex c8c1522fda..333a156f24 100644--- a/frontend/src/pages/pam/ApprovalsPage/components/PolicyTab/components/PolicyModal.tsx+++ b/frontend/src/pages/pam/ApprovalsPage/components/PolicyTab/components/PolicyModal.tsx@@ -7,6 +7,7 @@ import { createNotification } from "@app/components/notifications";import { Button, Modal, ModalContent } from "@app/components/v2";import { useProject } from "@app/context";import {+ ApprovalPolicyScope,ApprovalPolicyType,PamAccessPolicyConditions,PamAccessPolicyConstraints,@@ -128,7 +129,8 @@ export const PolicyModal = ({ popUp, handlePopUpToggle }: Props) => {} else {await createPolicy({policyType: ApprovalPolicyType.PamAccess,- projectId: currentProject.id,+ scope: ApprovalPolicyScope.Project,+ scopeId: currentProject.id,...data});createNotification({diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamRequestAccountAccessModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamRequestAccountAccessModal.tsxindex ca9a1de846..4ac29acd7e 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamRequestAccountAccessModal.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamRequestAccountAccessModal.tsx@@ -18,7 +18,7 @@ import {} from "@app/components/v2";import { Alert, AlertDescription, AlertTitle } from "@app/components/v3";import { useProject } from "@app/context";-import { ApprovalPolicyType } from "@app/hooks/api/approvalPolicies";+import { ApprovalPolicyScope, ApprovalPolicyType } from "@app/hooks/api/approvalPolicies";import { useCreateApprovalRequest } from "@app/hooks/api/approvalRequests/mutations";type Props = {@@ -113,7 +113,8 @@ const Content = ({try {await createApprovalRequest({policyType: ApprovalPolicyType.PamAccess,- projectId,+ scope: ApprovalPolicyScope.Project,+ scopeId: projectId,justification: formData.justification || null,requestData: {accessDuration: formData.accessDuration,