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
PKI code signing revamp
Carlos Monastyrski90737806f2b2
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex d57f51c23d..1943188ba8 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -163,7 +163,9 @@ import { TSecretSyncServiceFactory } from "@app/services/secret-sync/secret-syncimport { TSecretTagServiceFactory } from "@app/services/secret-tag/secret-tag-service";import { TSecretValidationRuleServiceFactory } from "@app/services/secret-validation-rule/secret-validation-rule-service";import { TServiceTokenServiceFactory } from "@app/services/service-token/service-token-service";+import { TSignerPolicyServiceFactory } from "@app/services/signer/signer-policy-service";import { TSignerServiceFactory } from "@app/services/signer/signer-service";+import { TSignerMembershipServiceFactory } from "@app/services/signer-membership";import { TSlackServiceFactory } from "@app/services/slack/slack-service";import { TSuperAdminServiceFactory } from "@app/services/super-admin/super-admin-service";import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";@@ -335,6 +337,8 @@ declare module "fastify" {certificateProfile: TCertificateProfileServiceFactory;pkiApplication: TPkiApplicationServiceFactory;pkiApplicationMembership: TPkiApplicationMembershipServiceFactory;+ signerMembership: TSignerMembershipServiceFactory;+ signerPolicy: TSignerPolicyServiceFactory;pkiApplicationEnrollment: TPkiApplicationEnrollmentServiceFactory;certManagerProjectResolver: TCertManagerProjectResolverFactory;certManagerInstance: TCertManagerInstanceServiceFactory;diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 6ad92d6f4a..a78a0e5840 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -407,6 +407,9 @@ import {TPkiScepTransactions,TPkiScepTransactionsInsert,TPkiScepTransactionsUpdate,+ TPkiSignerIssuanceJobs,+ TPkiSignerIssuanceJobsInsert,+ TPkiSignerIssuanceJobsUpdate,TPkiSigners,TPkiSignersInsert,TPkiSignersUpdate,@@ -1045,6 +1048,11 @@ declare module "knex/types/tables" {TPkiDiscoveryScanHistoryUpdate>;[TableName.PkiSigners]: KnexOriginal.CompositeTableType<TPkiSigners, TPkiSignersInsert, TPkiSignersUpdate>;+ [TableName.PkiSignerIssuanceJobs]: KnexOriginal.CompositeTableType<+ TPkiSignerIssuanceJobs,+ TPkiSignerIssuanceJobsInsert,+ TPkiSignerIssuanceJobsUpdate+ >;[TableName.PkiSigningOperations]: KnexOriginal.CompositeTableType<TPkiSigningOperations,TPkiSigningOperationsInsert,diff --git a/backend/src/db/migrations/20260528124443_signer-revamp.ts b/backend/src/db/migrations/20260528124443_signer-revamp.tsnew file mode 100644index 0000000000..2cf678d751--- /dev/null+++ b/backend/src/db/migrations/20260528124443_signer-revamp.ts@@ -0,0 +1,295 @@+/* eslint-disable no-await-in-loop */+import { Knex } from "knex";++import { TableName } from "../schemas";++const DEFAULT_RENEW_BEFORE_DAYS = 7;+const DEFAULT_CERT_TTL_DAYS = 365;+const SIGNER_SCOPE_TYPE = "signer";+const CERT_CODE_SIGNING_POLICY_TYPE = "cert-code-signing";+const SIGNER_ISSUANCE_JOBS_TABLE = "pki_signer_issuance_jobs";++type SignerRow = {+ id: string;+ projectId: string;+ name: string;+ approvalPolicyId: string | null;+ certificateId: string | null;+ caId: string | null;+ commonName: string | null;+ certificateTtlDays: number | null;+ renewBeforeDays: number | null;+};++export async function up(knex: Knex): Promise<void> {+ const hasCaId = await knex.schema.hasColumn(TableName.PkiSigners, "caId");+ const hasCommonName = await knex.schema.hasColumn(TableName.PkiSigners, "commonName");+ const hasTtl = await knex.schema.hasColumn(TableName.PkiSigners, "certificateTtlDays");+ const hasRenewBefore = await knex.schema.hasColumn(TableName.PkiSigners, "renewBeforeDays");+ const hasFailureReason = await knex.schema.hasColumn(TableName.PkiSigners, "failureReason");+ const hasKeyAlgorithm = await knex.schema.hasColumn(TableName.PkiSigners, "keyAlgorithm");++ if (!hasCaId || !hasCommonName || !hasTtl || !hasRenewBefore || !hasFailureReason || !hasKeyAlgorithm) {+ await knex.schema.alterTable(TableName.PkiSigners, (t) => {+ if (!hasCaId) {+ t.uuid("caId").nullable();+ t.foreign("caId").references("id").inTable(TableName.CertificateAuthority).onDelete("SET NULL");+ t.index("caId");+ }+ if (!hasCommonName) t.string("commonName", 256).nullable();+ if (!hasTtl) t.integer("certificateTtlDays").nullable();+ if (!hasRenewBefore) t.integer("renewBeforeDays").nullable();+ if (!hasFailureReason) t.text("failureReason").nullable();+ if (!hasKeyAlgorithm) t.string("keyAlgorithm", 64).notNullable().defaultTo("RSA_2048");+ });+ }++ await knex.schema.alterTable(TableName.PkiSigners, (t) => {+ t.uuid("certificateId").nullable().alter();+ });++ if (!(await knex.schema.hasColumn(TableName.ApprovalRequestGrants, "grantedByUserId"))) {+ await knex.schema.alterTable(TableName.ApprovalRequestGrants, (t) => {+ t.uuid("grantedByUserId").nullable();+ t.foreign("grantedByUserId").references("id").inTable(TableName.Users).onDelete("SET NULL");+ t.index("grantedByUserId");+ });+ }++ if (!(await knex.schema.hasTable(SIGNER_ISSUANCE_JOBS_TABLE))) {+ await knex.schema.createTable(SIGNER_ISSUANCE_JOBS_TABLE, (t) => {+ t.uuid("id").primary().defaultTo(knex.raw("gen_random_uuid()"));++ t.uuid("signerId").notNullable();+ t.foreign("signerId").references("id").inTable(TableName.PkiSigners).onDelete("CASCADE");+ t.index("signerId");++ t.uuid("caId").notNullable();+ t.foreign("caId").references("id").inTable(TableName.CertificateAuthority).onDelete("CASCADE");++ t.string("caType", 64).notNullable();+ t.string("status", 32).notNullable();++ t.string("commonName", 256).notNullable();+ t.integer("certificateTtlDays").notNullable();+ t.string("keyAlgorithm", 64).notNullable().defaultTo("RSA_2048");++ t.binary("encryptedPrivateKey");+ t.binary("encryptedCsr");++ t.jsonb("externalOrderRef");++ t.integer("attempts").notNullable().defaultTo(0);+ t.integer("maxAttempts").notNullable().defaultTo(100);+ t.timestamp("nextPollAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());+ t.timestamp("lastAttemptAt", { useTz: true });++ t.text("failureReason");++ t.uuid("certificateId");+ t.foreign("certificateId").references("id").inTable(TableName.Certificate).onDelete("SET NULL");++ t.timestamps(true, true, true);++ t.index(["status", "nextPollAt"], "pki_signer_issuance_jobs_status_nextPollAt_idx");+ });+ }++ await knex(TableName.ApprovalRequests)+ .where({ type: "cert-code-signing" })+ .andWhereRaw(`("requestData" -> 'version') IS DISTINCT FROM to_jsonb(1)`)+ .del();++ const signers = (await knex(TableName.PkiSigners).select<SignerRow[]>(+ "id",+ "projectId",+ "name",+ "approvalPolicyId",+ "certificateId",+ "caId",+ "commonName",+ "certificateTtlDays",+ "renewBeforeDays"+ )) as SignerRow[];++ for (const signer of signers) {+ await knex.transaction(async (tx) => {+ const project = await tx(TableName.Project)+ .where({ id: signer.projectId })+ .first<{ orgId: string } | undefined>("orgId");+ if (!project) return;++ const EMPTY_JSONB = JSON.stringify({});++ let policyId: string;+ if (!signer.approvalPolicyId) {+ const [created] = await tx(TableName.ApprovalPolicies)+ .insert({+ projectId: signer.projectId,+ organizationId: project.orgId,+ type: CERT_CODE_SIGNING_POLICY_TYPE,+ name: `signer:${signer.id}`,+ scopeType: SIGNER_SCOPE_TYPE,+ scopeId: signer.id,+ conditions: EMPTY_JSONB,+ constraints: EMPTY_JSONB+ })+ .returning<{ id: string }[]>("id");+ policyId = created.id;+ await tx(TableName.PkiSigners).where({ id: signer.id }).update({ approvalPolicyId: policyId });+ } else {+ const otherCount = await tx(TableName.PkiSigners)+ .where({ approvalPolicyId: signer.approvalPolicyId })+ .andWhereNot({ id: signer.id })+ .count<{ count: string }[]>("id as count")+ .first();+ const isShared = Number(otherCount?.count ?? 0) > 0;+ if (isShared) {+ const oldPolicy = await tx(TableName.ApprovalPolicies).where({ id: signer.approvalPolicyId }).first<+ | {+ name: string;+ constraints: unknown;+ conditions: unknown;+ maxRequestTtl: string | null;+ enforcementLevel: string | null;+ }+ | undefined+ >("name", "constraints", "conditions", "maxRequestTtl", "enforcementLevel");+ const [created] = await tx(TableName.ApprovalPolicies)+ .insert({+ projectId: signer.projectId,+ organizationId: project.orgId,+ type: CERT_CODE_SIGNING_POLICY_TYPE,+ name: `signer:${signer.id}`,+ scopeType: SIGNER_SCOPE_TYPE,+ scopeId: signer.id,+ constraints: oldPolicy?.constraints ?? EMPTY_JSONB,+ conditions: oldPolicy?.conditions ?? EMPTY_JSONB,+ maxRequestTtl: oldPolicy?.maxRequestTtl ?? null,+ enforcementLevel: oldPolicy?.enforcementLevel ?? "hard"+ })+ .returning<{ id: string }[]>("id");+ policyId = created.id;++ const oldSteps = await tx(TableName.ApprovalPolicySteps)+ .where({ policyId: signer.approvalPolicyId })+ .select("stepNumber", "requiredApprovals", "name", "notifyApprovers");+ for (const step of oldSteps) {+ await tx(TableName.ApprovalPolicySteps).insert({+ policyId,+ stepNumber: step.stepNumber,+ requiredApprovals: step.requiredApprovals,+ name: (step.name as string) ?? null,+ notifyApprovers: (step.notifyApprovers as boolean) ?? false+ });+ }++ await tx(TableName.PkiSigners).where({ id: signer.id }).update({ approvalPolicyId: policyId });+ } else {+ await tx(TableName.ApprovalPolicies)+ .where({ id: signer.approvalPolicyId })+ .update({ scopeType: SIGNER_SCOPE_TYPE, scopeId: signer.id });+ policyId = signer.approvalPolicyId;+ }+ }++ const stepIds = (await tx(TableName.ApprovalPolicySteps).where({ policyId }).select<{ id: string }[]>("id")).map(+ (r) => r.id+ );+ if (stepIds.length > 0) {+ await tx(TableName.ApprovalPolicyStepApprovers).whereIn("policyStepId", stepIds).delete();+ }++ if (signer.certificateId) {+ const cert = await tx(TableName.Certificate)+ .where({ id: signer.certificateId })+ .first<+ { caId: string | null; commonName: string; notBefore: Date; notAfter: Date } | undefined+ >("caId", "commonName", "notBefore", "notAfter");++ if (cert) {+ const patch: Record<string, unknown> = {};+ if (!signer.commonName) patch.commonName = cert.commonName;+ if (!signer.certificateTtlDays) {+ const msSpan = new Date(cert.notAfter).getTime() - new Date(cert.notBefore).getTime();+ const days = Math.max(1, Math.round(msSpan / (24 * 60 * 60 * 1000)));+ patch.certificateTtlDays = Number.isFinite(days) && days > 0 ? days : DEFAULT_CERT_TTL_DAYS;+ }+ if (!signer.renewBeforeDays) patch.renewBeforeDays = DEFAULT_RENEW_BEFORE_DAYS;+ if (!signer.caId && cert.caId) {+ const ca = await tx(TableName.CertificateAuthority)+ .where({ id: cert.caId, projectId: signer.projectId })+ .first<{ id: string } | undefined>("id");+ if (ca) patch.caId = ca.id;+ }+ if (Object.keys(patch).length > 0) {+ await tx(TableName.PkiSigners).where({ id: signer.id }).update(patch);+ }+ } else if (!signer.renewBeforeDays) {+ await tx(TableName.PkiSigners)+ .where({ id: signer.id })+ .update({ renewBeforeDays: DEFAULT_RENEW_BEFORE_DAYS });+ }+ } else if (!signer.renewBeforeDays) {+ await tx(TableName.PkiSigners).where({ id: signer.id }).update({ renewBeforeDays: DEFAULT_RENEW_BEFORE_DAYS });+ }+ });+ }++ const signerMemberships = (await knex(TableName.Membership)+ .where({ scope: "resource", scopeResourceType: SIGNER_SCOPE_TYPE })+ .select<{ id: string }[]>("id")) as { id: string }[];+ if (signerMemberships.length > 0) {+ const ids = signerMemberships.map((m) => m.id);+ await knex(TableName.MembershipRole).whereIn("membershipId", ids).delete();+ await knex(TableName.Membership).whereIn("id", ids).delete();+ }++ await knex.schema.alterTable(TableName.PkiSigners, (t) => {+ t.uuid("approvalPolicyId").notNullable().alter();+ });+}++export async function down(knex: Knex): Promise<void> {+ await knex.schema.dropTableIfExists(SIGNER_ISSUANCE_JOBS_TABLE);++ if (await knex.schema.hasColumn(TableName.ApprovalRequestGrants, "grantedByUserId")) {+ await knex.schema.alterTable(TableName.ApprovalRequestGrants, (t) => {+ t.dropIndex("grantedByUserId");+ t.dropForeign(["grantedByUserId"]);+ t.dropColumn("grantedByUserId");+ });+ }++ await knex.schema.alterTable(TableName.PkiSigners, (t) => {+ t.uuid("approvalPolicyId").nullable().alter();+ });++ const orphans = await knex(TableName.PkiSigners).whereNull("certificateId").count<{ count: string }[]>("id as count");+ const orphanCount = Number(orphans?.[0]?.count ?? 0);+ if (orphanCount === 0) {+ await knex.schema.alterTable(TableName.PkiSigners, (t) => {+ t.uuid("certificateId").notNullable().alter();+ });+ }++ const hasKeyAlgorithm = await knex.schema.hasColumn(TableName.PkiSigners, "keyAlgorithm");+ const hasFailureReason = await knex.schema.hasColumn(TableName.PkiSigners, "failureReason");+ const hasRenewBefore = await knex.schema.hasColumn(TableName.PkiSigners, "renewBeforeDays");+ const hasTtl = await knex.schema.hasColumn(TableName.PkiSigners, "certificateTtlDays");+ const hasCommonName = await knex.schema.hasColumn(TableName.PkiSigners, "commonName");+ const hasCaId = await knex.schema.hasColumn(TableName.PkiSigners, "caId");++ await knex.schema.alterTable(TableName.PkiSigners, (t) => {+ if (hasKeyAlgorithm) t.dropColumn("keyAlgorithm");+ if (hasFailureReason) t.dropColumn("failureReason");+ if (hasRenewBefore) t.dropColumn("renewBeforeDays");+ if (hasTtl) t.dropColumn("certificateTtlDays");+ if (hasCommonName) t.dropColumn("commonName");+ if (hasCaId) {+ t.dropIndex("caId");+ t.dropForeign(["caId"]);+ t.dropColumn("caId");+ }+ });+}diff --git a/backend/src/db/schemas/approval-policies.ts b/backend/src/db/schemas/approval-policies.tsindex f358b620a4..7833dc4ec7 100644--- a/backend/src/db/schemas/approval-policies.ts+++ b/backend/src/db/schemas/approval-policies.ts@@ -20,9 +20,9 @@ export const ApprovalPoliciesSchema = z.object({createdAt: z.date(),updatedAt: z.date(),bypassForMachineIdentities: z.boolean().default(false).nullable().optional(),- enforcementLevel: z.string().default("hard"),scopeType: z.string().nullable().optional(),- scopeId: z.string().uuid().nullable().optional()+ scopeId: z.string().uuid().nullable().optional(),+ enforcementLevel: z.string().default("hard")});export type TApprovalPolicies = z.infer<typeof ApprovalPoliciesSchema>;diff --git a/backend/src/db/schemas/approval-request-grants.ts b/backend/src/db/schemas/approval-request-grants.tsindex ed8f3b827c..6981e797d2 100644--- a/backend/src/db/schemas/approval-request-grants.ts+++ b/backend/src/db/schemas/approval-request-grants.ts@@ -22,7 +22,8 @@ export const ApprovalRequestGrantsSchema = z.object({revokedAt: z.date().nullable().optional(),granteeMachineIdentityId: z.string().uuid().nullable().optional(),isBreakGlass: z.boolean().default(false),- bypassReason: z.string().nullable().optional()+ bypassReason: z.string().nullable().optional(),+ grantedByUserId: z.string().uuid().nullable().optional()});export type TApprovalRequestGrants = z.infer<typeof ApprovalRequestGrantsSchema>;diff --git a/backend/src/db/schemas/certificate-requests.ts b/backend/src/db/schemas/certificate-requests.tsindex 697e1508ed..c9a80c4f43 100644--- a/backend/src/db/schemas/certificate-requests.ts+++ b/backend/src/db/schemas/certificate-requests.ts@@ -40,8 +40,8 @@ export const CertificateRequestsSchema = z.object({state: z.string().nullable().optional(),locality: z.string().nullable().optional(),encryptedPrivateKey: zodBuffer.nullable().optional(),- pendingMessage: z.string().nullable().optional(),- applicationId: z.string().uuid().nullable().optional()+ applicationId: z.string().uuid().nullable().optional(),+ pendingMessage: z.string().nullable().optional()});export type TCertificateRequests = z.infer<typeof CertificateRequestsSchema>;diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex cccb8a51a3..1e058b909c 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -164,6 +164,7 @@ export * from "./pki-est-enrollment-configs";export * from "./pki-scep-dynamic-challenges";export * from "./pki-scep-enrollment-configs";export * from "./pki-scep-transactions";+export * from "./pki-signer-issuance-jobs";export * from "./pki-signers";export * from "./pki-signing-operations";export * from "./pki-subscribers";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 52f479e66e..ebc5f7ad73 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -292,6 +292,7 @@ export enum TableName {// Code SigningPkiSigners = "pki_signers",+ PkiSignerIssuanceJobs = "pki_signer_issuance_jobs",PkiSigningOperations = "pki_signing_operations",CaSigningConfig = "ca_signing_configs",@@ -361,7 +362,8 @@ export enum ApplicationMembershipRole {}export enum ResourceType {- CertificateApplication = "certificate-application"+ CertificateApplication = "certificate-application",+ Signer = "signer"}export enum SecretEncryptionAlgo {diff --git a/backend/src/db/schemas/pki-acme-auths.ts b/backend/src/db/schemas/pki-acme-auths.tsindex 51fab740f6..0faa4dd784 100644--- a/backend/src/db/schemas/pki-acme-auths.ts+++ b/backend/src/db/schemas/pki-acme-auths.ts@@ -18,7 +18,7 @@ export const PkiAcmeAuthsSchema = z.object({certificateId: z.string().uuid().nullable().optional(),createdAt: z.date(),updatedAt: z.date(),- wildcard: z.boolean().default(false)+ wildcard: z.boolean().default(false).nullable().optional()});export type TPkiAcmeAuths = z.infer<typeof PkiAcmeAuthsSchema>;diff --git a/backend/src/db/schemas/pki-signer-issuance-jobs.ts b/backend/src/db/schemas/pki-signer-issuance-jobs.tsnew file mode 100644index 0000000000..119731b481--- /dev/null+++ b/backend/src/db/schemas/pki-signer-issuance-jobs.ts@@ -0,0 +1,36 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { zodBuffer } from "@app/lib/zod";++import { TImmutableDBKeys } from "./models";++export const PkiSignerIssuanceJobsSchema = z.object({+ id: z.string().uuid(),+ signerId: z.string().uuid(),+ caId: z.string().uuid(),+ caType: z.string(),+ status: z.string(),+ commonName: z.string(),+ certificateTtlDays: z.number(),+ keyAlgorithm: z.string().default("RSA_2048"),+ encryptedPrivateKey: zodBuffer.nullable().optional(),+ encryptedCsr: zodBuffer.nullable().optional(),+ externalOrderRef: z.unknown().nullable().optional(),+ attempts: z.number().default(0),+ maxAttempts: z.number().default(100),+ nextPollAt: z.date(),+ lastAttemptAt: z.date().nullable().optional(),+ failureReason: z.string().nullable().optional(),+ certificateId: z.string().uuid().nullable().optional(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TPkiSignerIssuanceJobs = z.infer<typeof PkiSignerIssuanceJobsSchema>;+export type TPkiSignerIssuanceJobsInsert = Omit<z.input<typeof PkiSignerIssuanceJobsSchema>, TImmutableDBKeys>;+export type TPkiSignerIssuanceJobsUpdate = Partial<Omit<z.input<typeof PkiSignerIssuanceJobsSchema>, TImmutableDBKeys>>;diff --git a/backend/src/db/schemas/pki-signers.ts b/backend/src/db/schemas/pki-signers.tsindex 44ece44210..d51e2db3fb 100644--- a/backend/src/db/schemas/pki-signers.ts+++ b/backend/src/db/schemas/pki-signers.ts@@ -13,11 +13,17 @@ export const PkiSignersSchema = z.object({name: z.string(),description: z.string().nullable().optional(),status: z.string().default("active"),- certificateId: z.string().uuid(),- approvalPolicyId: z.string().uuid().nullable().optional(),+ certificateId: z.string().uuid().nullable().optional(),+ approvalPolicyId: z.string().uuid(),lastSignedAt: z.date().nullable().optional(),createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ caId: z.string().uuid().nullable().optional(),+ commonName: z.string().nullable().optional(),+ certificateTtlDays: z.number().nullable().optional(),+ renewBeforeDays: z.number().nullable().optional(),+ failureReason: z.string().nullable().optional(),+ keyAlgorithm: z.string().default("RSA_2048")});export type TPkiSigners = z.infer<typeof PkiSignersSchema>;diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex ae8fe769b7..725991f874 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -833,6 +833,17 @@ export enum EventType {GET_PKI_SIGNER_PUBLIC_KEY = "get-pki-signer-public-key",GET_PKI_SIGNING_OPERATIONS = "get-pki-signing-operations",PKI_SIGNER_SIGN = "pki-signer-sign",+ ENABLE_PKI_SIGNER = "enable-pki-signer",+ DISABLE_PKI_SIGNER = "disable-pki-signer",+ REISSUE_PKI_SIGNER_CERTIFICATE = "reissue-pki-signer-certificate",+ EXPORT_PKI_SIGNER_CERTIFICATE = "export-pki-signer-certificate",+ UPDATE_PKI_SIGNER_APPROVAL_POLICY = "update-pki-signer-approval-policy",+ PKI_SIGNER_REQUEST_TO_SIGN = "pki-signer-request-to-sign",+ PKI_SIGNER_PRE_APPROVE_SIGNING = "pki-signer-pre-approve-signing",+ PKI_SIGNER_REVOKE_REQUEST = "pki-signer-revoke-request",+ ADD_PKI_SIGNER_MEMBER = "add-pki-signer-member",+ UPDATE_PKI_SIGNER_MEMBER = "update-pki-signer-member",+ REMOVE_PKI_SIGNER_MEMBER = "remove-pki-signer-member",SCEP_ENROLLMENT = "scep-enrollment",SCEP_RENEWAL = "scep-renewal",SCEP_DYNAMIC_CHALLENGE_GENERATED = "scep-dynamic-challenge-generated",@@ -4764,7 +4775,9 @@ interface CreatePkiSignerEvent {metadata: {signerId: string;name: string;- certificateId: string;+ certificateId?: string | null;+ caId?: string | null;+ commonName?: string | null;approvalPolicyId?: string | null;};}@@ -4827,6 +4840,107 @@ interface PkiSignerSignEvent {};}+interface EnablePkiSignerEvent {+ type: EventType.ENABLE_PKI_SIGNER;+ metadata: {+ signerId: string;+ name: string;+ };+}++interface DisablePkiSignerEvent {+ type: EventType.DISABLE_PKI_SIGNER;+ metadata: {+ signerId: string;+ name: string;+ };+}++interface ReissuePkiSignerCertificateEvent {+ type: EventType.REISSUE_PKI_SIGNER_CERTIFICATE;+ metadata: {+ signerId: string;+ name: string;+ caId: string;+ commonName?: string;+ };+}++interface ExportPkiSignerCertificateEvent {+ type: EventType.EXPORT_PKI_SIGNER_CERTIFICATE;+ metadata: {+ signerId: string;+ name: string;+ serialNumber: string;+ };+}++interface UpdatePkiSignerApprovalPolicyEvent {+ type: EventType.UPDATE_PKI_SIGNER_APPROVAL_POLICY;+ metadata: {+ signerId: string;+ stepCount: number;+ };+}++interface PkiSignerRequestToSignEvent {+ type: EventType.PKI_SIGNER_REQUEST_TO_SIGN;+ metadata: {+ signerId: string;+ requestId?: string;+ };+}++interface PkiSignerPreApproveSigningEvent {+ type: EventType.PKI_SIGNER_PRE_APPROVE_SIGNING;+ metadata: {+ signerId: string;+ requestId?: string;+ granteeUserId?: string;+ granteeIdentityId?: string;+ };+}++interface PkiSignerRevokeRequestEvent {+ type: EventType.PKI_SIGNER_REVOKE_REQUEST;+ metadata: {+ signerId: string;+ requestId: string;+ };+}++interface AddPkiSignerMemberEvent {+ type: EventType.ADD_PKI_SIGNER_MEMBER;+ metadata: {+ signerId: string;+ kind: string;+ role?: string;+ added?: number;+ userIds?: string[];+ identityId?: string;+ groupId?: string;+ };+}++interface UpdatePkiSignerMemberEvent {+ type: EventType.UPDATE_PKI_SIGNER_MEMBER;+ metadata: {+ signerId: string;+ kind: string;+ memberId: string;+ role: string;+ };+}++interface RemovePkiSignerMemberEvent {+ type: EventType.REMOVE_PKI_SIGNER_MEMBER;+ metadata: {+ signerId: string;+ kind: string;+ memberId: string;+ };+}+interface OidcGroupMembershipMappingAssignUserEvent {type: EventType.OIDC_GROUP_MEMBERSHIP_MAPPING_ASSIGN_USER;metadata: {@@ -7532,6 +7646,17 @@ export type Event =| GetPkiSignerPublicKeyEvent| GetPkiSigningOperationsEvent| PkiSignerSignEvent+ | EnablePkiSignerEvent+ | DisablePkiSignerEvent+ | ReissuePkiSignerCertificateEvent+ | ExportPkiSignerCertificateEvent+ | UpdatePkiSignerApprovalPolicyEvent+ | PkiSignerRequestToSignEvent+ | PkiSignerPreApproveSigningEvent+ | PkiSignerRevokeRequestEvent+ | AddPkiSignerMemberEvent+ | UpdatePkiSignerMemberEvent+ | RemovePkiSignerMemberEvent| OidcGroupMembershipMappingAssignUserEvent| OidcGroupMembershipMappingRemoveUserEvent| CreateKmipClientEventdiff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.tsindex bc8a9e31c5..83b3cb22cb 100644--- a/backend/src/ee/services/permission/default-roles.ts+++ b/backend/src/ee/services/permission/default-roles.ts@@ -51,6 +51,7 @@ import {ResourcePermissionCertificateActions,ResourcePermissionPkiSyncActions,ResourcePermissionSet,+ ResourcePermissionSignerActions,ResourcePermissionSub} from "@app/ee/services/permission/resource-permission";@@ -333,13 +334,7 @@ const buildAdminPermissionRules = () => {);can(- [- ProjectPermissionCodeSigningActions.Read,- ProjectPermissionCodeSigningActions.Create,- ProjectPermissionCodeSigningActions.Edit,- ProjectPermissionCodeSigningActions.Delete,- ProjectPermissionCodeSigningActions.Sign- ],+ [ProjectPermissionCodeSigningActions.Read, ProjectPermissionCodeSigningActions.Create],ProjectPermissionSub.CodeSigners);@@ -1097,3 +1092,95 @@ export const applicationAdminPermissions = buildApplicationAdminPermissionRules(export const applicationOperatorPermissions = buildApplicationOperatorPermissionRules();export const applicationAuditorPermissions = buildApplicationAuditorPermissionRules();export const applicationProjectAdminFallbackPermissions = buildApplicationProjectAdminFallbackRules();++const buildSignerAdminPermissionRules = () => {+ const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);++ can(+ [+ ResourcePermissionSignerActions.Read,+ ResourcePermissionSignerActions.Edit,+ ResourcePermissionSignerActions.Delete,+ ResourcePermissionSignerActions.EnableDisable,+ ResourcePermissionSignerActions.ManageMembers,+ ResourcePermissionSignerActions.ManagePolicy,+ ResourcePermissionSignerActions.Sign,+ ResourcePermissionSignerActions.RequestSign,+ ResourcePermissionSignerActions.PreApprove,+ ResourcePermissionSignerActions.RevokeRequest,+ ResourcePermissionSignerActions.ReissueCertificate,+ ResourcePermissionSignerActions.ExportCertificate+ ],+ ResourcePermissionSub.Signer+ );++ can(+ [+ ProjectPermissionMemberActions.Read,+ ProjectPermissionMemberActions.Create,+ ProjectPermissionMemberActions.Edit,+ ProjectPermissionMemberActions.Delete+ ],+ ResourcePermissionSub.Member+ );++ can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);++ return rules;+};++const buildSignerOperatorPermissionRules = () => {+ const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);++ can(+ [+ ResourcePermissionSignerActions.Read,+ ResourcePermissionSignerActions.Sign,+ ResourcePermissionSignerActions.RequestSign,+ ResourcePermissionSignerActions.ExportCertificate+ ],+ ResourcePermissionSub.Signer+ );++ can([ProjectPermissionMemberActions.Read], ResourcePermissionSub.Member);+ can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);++ return rules;+};++const buildSignerAuditorPermissionRules = () => {+ const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);++ can(+ [ResourcePermissionSignerActions.Read, ResourcePermissionSignerActions.ExportCertificate],+ ResourcePermissionSub.Signer+ );++ can([ProjectPermissionMemberActions.Read], ResourcePermissionSub.Member);+ can([ProjectPermissionAuditLogsActions.Read], ProjectPermissionSub.AuditLogs);++ return rules;+};++const buildSignerProjectAdminFallbackRules = () => {+ const { can, rules } = new AbilityBuilder<MongoAbility<ResourcePermissionSet>>(createMongoAbility);++ can([ResourcePermissionSignerActions.Read], ResourcePermissionSub.Signer);++ can(+ [+ ProjectPermissionMemberActions.Read,+ ProjectPermissionMemberActions.Create,+ ProjectPermissionMemberActions.Edit,+ ProjectPermissionMemberActions.Delete+ ],+ ResourcePermissionSub.Member+ );++ return rules;+};++export const signerAdminPermissions = buildSignerAdminPermissionRules();+export const signerOperatorPermissions = buildSignerOperatorPermissionRules();+export const signerAuditorPermissions = buildSignerAuditorPermissionRules();+export const signerProjectAdminFallbackPermissions = buildSignerProjectAdminFallbackRules();diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.tsindex d29f4acba3..4c35dcd1a4 100644--- a/backend/src/ee/services/permission/permission-service.ts+++ b/backend/src/ee/services/permission/permission-service.ts@@ -10,6 +10,7 @@ import {OrganizationActionScope,OrgMembershipRole,ProjectMembershipRole,+ ResourceType,ServiceTokenScopes,TProjects} from "@app/db/schemas";@@ -24,6 +25,10 @@ import {projectMemberPermissions,projectNoAccessPermissions,projectViewerPermission,+ signerAdminPermissions,+ signerAuditorPermissions,+ signerOperatorPermissions,+ signerProjectAdminFallbackPermissions,sshHostBootstrapPermissions} from "@app/ee/services/permission/default-roles";import { ResourcePermissionSet } from "@app/ee/services/permission/resource-permission";@@ -126,33 +131,53 @@ const buildProjectPermissionRules = (projectUserRoles: TBuildProjectPermissionDTreturn rules;};-const buildResourcePermissionRules = (appUserRoles: TBuildProjectPermissionDTO) => {+const resolveResourceRoleRules = (resourceType: ResourceType, role: string) => {+ if (resourceType === ResourceType.Signer) {+ switch (role) {+ case ApplicationMembershipRole.Admin:+ return signerAdminPermissions;+ case ApplicationMembershipRole.Operator:+ return signerOperatorPermissions;+ case ApplicationMembershipRole.Auditor:+ return signerAuditorPermissions;+ case ApplicationMembershipRole.Custom:+ throw new BadRequestError({ message: "Custom resource-level roles are not supported yet" });+ default:+ throw new NotFoundError({ name: "SignerRoleInvalid", message: `Signer role '${role}' not found` });+ }+ }++ switch (role) {+ case ApplicationMembershipRole.Admin:+ return applicationAdminPermissions;+ case ApplicationMembershipRole.Operator:+ return applicationOperatorPermissions;+ case ApplicationMembershipRole.Auditor:+ return applicationAuditorPermissions;+ case ApplicationMembershipRole.Custom:+ throw new BadRequestError({ message: "Custom resource-level roles are not supported yet" });+ default:+ throw new NotFoundError({+ name: "ApplicationRoleInvalid",+ message: `Application role '${role}' not found`+ });+ }+};++const buildResourcePermissionRules = (appUserRoles: TBuildProjectPermissionDTO, resourceType: ResourceType) => {const rules = appUserRoles- .map(({ role }) => {- switch (role) {- case ApplicationMembershipRole.Admin:- return applicationAdminPermissions;- case ApplicationMembershipRole.Operator:- return applicationOperatorPermissions;- case ApplicationMembershipRole.Auditor:- return applicationAuditorPermissions;- case ApplicationMembershipRole.Custom:- throw new BadRequestError({- message: "Custom resource-level roles are not supported yet"- });- default:- throw new NotFoundError({- name: "ApplicationRoleInvalid",- message: `Application role '${role}' not found`- });- }- })+ .map(({ role }) => resolveResourceRoleRules(resourceType, role)).reduce((prev, curr) => prev.concat(curr), [] as RawRuleOf<MongoAbility<ResourcePermissionSet>>[]).sort((a, b) => Number(Boolean(a.inverted)) - Number(Boolean(b.inverted)));return rules;};+const resolveResourceProjectAdminFallback = (resourceType: ResourceType) => {+ if (resourceType === ResourceType.Signer) return signerProjectAdminFallbackPermissions;+ return applicationProjectAdminFallbackPermissions;+};+type MembershipWithRoles = {roles?: Array<{role: string;@@ -696,15 +721,15 @@ export const permissionServiceFactory = ({actorType: actor});+ const fallbackRules = resolveResourceProjectAdminFallback(resourceType);+if (resourceMemberships?.length) {const permissionFromRoles = flattenActiveRolesFromMemberships(resourceMemberships,ApplicationMembershipRole.Custom);- const resourceRules = buildResourcePermissionRules(permissionFromRoles);- const mergedRules = isProjectAdmin- ? [...resourceRules, ...applicationProjectAdminFallbackPermissions]- : resourceRules;+ const resourceRules = buildResourcePermissionRules(permissionFromRoles, resourceType);+ const mergedRules = isProjectAdmin ? [...resourceRules, ...fallbackRules] : resourceRules;const permission = createMongoAbility<ResourcePermissionSet>(mergedRules, { conditionsMatcher });const hasRole = (role: string) => membershipsHaveActiveRole(resourceMemberships, role);@@ -718,7 +743,7 @@ export const permissionServiceFactory = ({}if (isProjectAdmin) {- const permission = createMongoAbility<ResourcePermissionSet>(applicationProjectAdminFallbackPermissions, {+ const permission = createMongoAbility<ResourcePermissionSet>(fallbackRules, {conditionsMatcher});return {diff --git a/backend/src/ee/services/permission/resource-permission.ts b/backend/src/ee/services/permission/resource-permission.tsindex b8ce1dfceb..bb5b1cc663 100644--- a/backend/src/ee/services/permission/resource-permission.ts+++ b/backend/src/ee/services/permission/resource-permission.ts@@ -21,7 +21,23 @@ export enum ResourcePermissionSub {ApprovalRequests = "approval-requests",ApprovalRequestGrants = "approval-request-grants",Member = "member",- Role = "role"+ Role = "role",+ Signer = "signer"+}++export enum ResourcePermissionSignerActions {+ Read = "read",+ Edit = "edit",+ Delete = "delete",+ EnableDisable = "enable-disable",+ ManageMembers = "manage-members",+ ManagePolicy = "manage-policy",+ Sign = "sign",+ RequestSign = "request-sign",+ PreApprove = "pre-approve",+ RevokeRequest = "revoke-request",+ ReissueCertificate = "reissue-certificate",+ ExportCertificate = "export-certificate"}export enum ResourcePermissionApplicationActions {@@ -79,6 +95,7 @@ export type ResourcePermissionSet =| [ProjectPermissionApprovalRequestGrantActions, ResourcePermissionSub.ApprovalRequestGrants]| [ProjectPermissionMemberActions, ResourcePermissionSub.Member]| [ProjectPermissionActions, ResourcePermissionSub.Role]+ | [ResourcePermissionSignerActions, ResourcePermissionSub.Signer]| [ProjectPermissionCertificateProfileActions, ProjectPermissionSub.CertificateProfiles]| [ProjectPermissionAuditLogsActions, ProjectPermissionSub.AuditLogs];diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.tsindex 750cf517b7..accf85b9f3 100644--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts@@ -887,7 +887,7 @@ export const pkiAcmeServiceFactory = ({status: 201,body: buildAcmeOrderResource({profileId,- order+ order: order as Parameters<typeof buildAcmeOrderResource>[0]["order"]}),headers: {Location: buildUrl(profileId, `/orders/${order.id}`),diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.tsindex c69b91e310..fa40e5ad87 100644--- a/backend/src/lib/cron/cron-job.ts+++ b/backend/src/lib/cron/cron-job.ts@@ -31,7 +31,9 @@ export const CronJobName = {DigiCertOrderPolling: "digicert-order-polling",ProjectEnvHardDelete: "project-env-hard-delete",DigiCertRevocationSync: "digicert-revocation-sync",- CaCrlRotation: "ca-crl-rotation"+ CaCrlRotation: "ca-crl-rotation",+ SignerDailyAutoRenewal: "signer-daily-auto-renewal",+ SignerIssuancePolling: "signer-issuance-polling"} as const;// ── tuning constants ──────────────────────────────────────────────────────────diff --git a/backend/src/lib/crypto/sign/signing.ts b/backend/src/lib/crypto/sign/signing.tsindex 28df6ec5e3..ae576aa658 100644--- a/backend/src/lib/crypto/sign/signing.ts+++ b/backend/src/lib/crypto/sign/signing.ts@@ -93,10 +93,11 @@ export const signingService = (algorithm: AsymmetricKeyAlgorithm): TAsymmetricSi// We will support more in the futureswitch (keyAlgorithm) {case AsymmetricKeyAlgorithm.ECC_NIST_P256:- return {- full: "prime256v1",- short: "p256"- };+ return { full: "prime256v1", short: "p256" };+ case AsymmetricKeyAlgorithm.ECC_NIST_P384:+ return { full: "secp384r1", short: "p384" };+ case AsymmetricKeyAlgorithm.ECC_NIST_P521:+ return { full: "secp521r1", short: "p521" };default:throw new Error(`Unsupported EC curve: ${keyAlgorithm}`);}@@ -347,6 +348,8 @@ export const signingService = (algorithm: AsymmetricKeyAlgorithm): TAsymmetricSi(data: Buffer, signature: Buffer, publicKey: Buffer, hashAlgorithm: SupportedHashAlgorithm) => Promise<boolean>> = {[AsymmetricKeyAlgorithm.ECC_NIST_P256]: $verifyEccDigest,+ [AsymmetricKeyAlgorithm.ECC_NIST_P384]: $verifyEccDigest,+ [AsymmetricKeyAlgorithm.ECC_NIST_P521]: $verifyEccDigest,[AsymmetricKeyAlgorithm.RSA_4096]: $verifyRsaDigest};@@ -360,6 +363,8 @@ export const signingService = (algorithm: AsymmetricKeyAlgorithm): TAsymmetricSi) => Promise<Buffer>> = {[AsymmetricKeyAlgorithm.ECC_NIST_P256]: $signEccDigest,+ [AsymmetricKeyAlgorithm.ECC_NIST_P384]: $signEccDigest,+ [AsymmetricKeyAlgorithm.ECC_NIST_P521]: $signEccDigest,[AsymmetricKeyAlgorithm.RSA_4096]: $signRsaDigest};diff --git a/backend/src/lib/crypto/sign/types.ts b/backend/src/lib/crypto/sign/types.tsindex aa81b40570..aa003a4a2c 100644--- a/backend/src/lib/crypto/sign/types.ts+++ b/backend/src/lib/crypto/sign/types.ts@@ -16,7 +16,9 @@ export type TAsymmetricSignVerifyFns = {// Supported asymmetric key typesexport enum AsymmetricKeyAlgorithm {RSA_4096 = "RSA_4096",- ECC_NIST_P256 = "ECC_NIST_P256"+ ECC_NIST_P256 = "ECC_NIST_P256",+ ECC_NIST_P384 = "ECC_NIST_P384",+ ECC_NIST_P521 = "ECC_NIST_P521"}export const AsymmetricKeyAlgorithmEnum = z.enum(diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex 1c631bb901..6017c7e5cd 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -99,7 +99,8 @@ export enum QueueName {AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",AuditLogClickHouseBatch = "audit-log-clickhouse-batch",PamDiscoveryScan = "pam-discovery-scan",- CaAutoRenewal = "ca-auto-renewal"+ CaAutoRenewal = "ca-auto-renewal",+ SignerAutoRenewal = "signer-auto-renewal"}export enum QueueJobs {@@ -171,7 +172,8 @@ export enum QueueJobs {CaAdcsInstall = "ca-adcs-install-job",CertificateCleanup = "certificate-cleanup-job",DailySecretSyncRetry = "daily-secret-sync-retry-job",- DigiCertOrderPolling = "digicert-order-polling-job"+ DigiCertOrderPolling = "digicert-order-polling-job",+ SignerDailyAutoRenewal = "signer-daily-auto-renewal"}export type TQueueOptions = {@@ -485,6 +487,10 @@ export type TQueueJobTypes = {name: QueueJobs.CaAdcsInstall;payload: { caId: string; maxPathLength?: number };};+ [QueueName.SignerAutoRenewal]: {+ name: QueueJobs.SignerDailyAutoRenewal;+ payload: undefined;+ };};const SECRET_SCANNING_QUEUES = [diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.tsindex 7893ff9a58..a64285acbf 100644--- a/backend/src/server/plugins/error-handler.ts+++ b/backend/src/server/plugins/error-handler.ts@@ -256,11 +256,10 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider.status(error.status).send({reqId: req.id,- error: error.name,status: error.status,type: `urn:ietf:params:acme:error:${error.type}`,- detail: error.message- // TODO: add subproblems if they exist+ detail: error.message,+ ...(error.subproblems && error.subproblems.length > 0 ? { subproblems: error.subproblems } : {})});} else if (error instanceof PolicyViolationError) {void res.status(HttpStatusCodes.Forbidden).send({diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 2c5ba47595..fe6f0b58db 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -471,6 +471,11 @@ import { secretValidationRuleServiceFactory } from "@app/services/secret-validatimport { serviceTokenDALFactory } from "@app/services/service-token/service-token-dal";import { serviceTokenServiceFactory } from "@app/services/service-token/service-token-service";import { signerDALFactory, signerServiceFactory, signingOperationDALFactory } from "@app/services/signer";+import { signerAutoRenewalQueueFactory } from "@app/services/signer/signer-auto-renewal-queue";+import { signerIssuanceJobDALFactory } from "@app/services/signer/signer-issuance-job-dal";+import { signerIssuanceServiceFactory } from "@app/services/signer/signer-issuance-service";+import { signerPolicyServiceFactory } from "@app/services/signer/signer-policy-service";+import { signerMembershipServiceFactory } from "@app/services/signer-membership";import { projectSlackConfigDALFactory } from "@app/services/slack/project-slack-config-dal";import { slackIntegrationDALFactory } from "@app/services/slack/slack-integration-dal";import { slackServiceFactory } from "@app/services/slack/slack-service";@@ -1349,6 +1354,7 @@ export const registerRoutes = async (const signerDAL = signerDALFactory(db);const signingOperationDAL = signingOperationDALFactory(db);+ const signerIssuanceJobDAL = signerIssuanceJobDALFactory(db);const instanceRelayConfigDAL = instanceRelayConfigDalFactory(db);const orgRelayConfigDAL = orgRelayConfigDalFactory(db);@@ -1484,6 +1490,19 @@ export const registerRoutes = async (approvalPolicyDAL});+ const signerMembershipService = signerMembershipServiceFactory({+ signerDAL,+ membershipDAL,+ membershipRoleDAL,+ permissionService,+ userDAL,+ identityDAL,+ groupDAL,+ userGroupMembershipDAL,+ identityGroupMembershipDAL,+ approvalPolicyDAL+ });+const certManagerProjectResolver = certManagerProjectResolverFactory({orgDAL,projectDAL@@ -3043,16 +3062,62 @@ export const registerRoutes = async (permissionService});+ const signerIssuanceService = signerIssuanceServiceFactory({+ signerIssuanceJobDAL,+ signerDAL,+ certificateAuthorityDAL,+ certificateBodyDAL,+ certificateSecretDAL,+ projectDAL,+ kmsService,+ certificateIssuanceQueue,+ cronJob+ });+const signerService = signerServiceFactory({signerDAL,signingOperationDAL,certificateDAL,+ certificateBodyDAL,certificateSecretDAL,+ certificateAuthorityDAL,+ signerIssuanceService,+ internalCertificateAuthorityService,projectDAL,kmsService,permissionService,approvalPolicyDAL,- approvalRequestGrantsDAL+ approvalPolicyStepsDAL,+ approvalPolicyStepApproversDAL,+ approvalRequestDAL,+ approvalRequestGrantsDAL,+ membershipDAL,+ membershipRoleDAL+ });++ const signerAutoRenewalQueue = signerAutoRenewalQueueFactory({+ queueService,+ cronJob,+ signerDAL,+ signerService+ });++ const signerPolicyService = signerPolicyServiceFactory({+ signerDAL,+ approvalPolicyDAL,+ approvalPolicyStepsDAL,+ approvalPolicyStepApproversDAL,+ approvalRequestDAL,+ approvalRequestStepsDAL,+ approvalRequestStepEligibleApproversDAL,+ approvalRequestGrantsDAL,+ membershipDAL,+ membershipRoleDAL,+ userGroupMembershipDAL,+ identityGroupMembershipDAL,+ userDAL,+ identityDAL,+ permissionService});const pkiTemplateService = pkiTemplatesServiceFactory({@@ -3430,6 +3495,8 @@ export const registerRoutes = async (digicertCaQueue.init();digicertRevocationSyncQueue.init();caAutoRenewalQueue.startDailyAutoRenewalJob();+ signerAutoRenewalQueue.start();+ signerIssuanceService.start();await microsoftTeamsService.start();await eventBusService.init();@@ -3513,6 +3580,8 @@ export const registerRoutes = async (certificateProfile: certificateProfileService,pkiApplication: pkiApplicationService,pkiApplicationMembership: pkiApplicationMembershipService,+ signerMembership: signerMembershipService,+ signerPolicy: signerPolicyService,pkiApplicationEnrollment: pkiApplicationEnrollmentService,certManagerProjectResolver,certManagerInstance: certManagerInstanceService,diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.tsindex f6e6a1eb56..2c5107ea33 100644--- a/backend/src/server/routes/v1/index.ts+++ b/backend/src/server/routes/v1/index.ts@@ -83,6 +83,7 @@ import { registerSecretRequestsRouter } from "./secret-requests-router";import { registerSecretSharingRouter } from "./secret-sharing-router";import { registerSecretTagRouter } from "./secret-tag-router";import { registerSecretValidationRuleRouter } from "./secret-validation-rule-router";+import { registerSignerMembershipRoutes } from "./signer-membership-router";import { registerSignerRouter } from "./signer-router";import { registerSlackRouter } from "./slack-router";import { registerSsoRouter } from "./sso-router";@@ -229,6 +230,7 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {await pkiRouter.register(registerCertManagerInstanceRouter);await pkiRouter.register(registerCertManagerExportRouter);await pkiRouter.register(registerSignerRouter, { prefix: "/signers" });+ await pkiRouter.register(registerSignerMembershipRoutes, { prefix: "/signers" });await pkiRouter.register(registerCertificateCleanupRouter, { prefix: "/certificate-cleanup" });await pkiRouter.register(registerCertificateInventoryViewRouter, { prefix: "/certificate-inventory-views" });await pkiRouter.register(registerCertManagerAccessRouter, { prefix: "/access" });diff --git a/backend/src/server/routes/v1/signer-membership-router.ts b/backend/src/server/routes/v1/signer-membership-router.tsnew file mode 100644index 0000000000..a070022268--- /dev/null+++ b/backend/src/server/routes/v1/signer-membership-router.ts@@ -0,0 +1,783 @@+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 { SignerMemberKind } from "@app/services/signer-membership";++const SignerIdParamsSchema = z.object({ signerId: z.string().uuid() });++const SignerMemberSchema = z.object({+ membershipId: z.string().uuid(),+ signerId: 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()+});++const EffectiveSignerMemberSchema = z.object({+ actorUserId: z.string().uuid().nullable(),+ actorIdentityId: z.string().uuid().nullable(),+ role: z.string(),+ viaGroupIds: z.array(z.string().uuid()),+ isDirect: z.boolean(),+ details: z+ .object({+ name: z.string().nullable(),+ email: z.string().nullable().optional(),+ username: z.string().nullable().optional(),+ authMethod: z.string().nullable().optional()+ })+ .nullable()+});++const RoleBodySchema = z.object({ role: z.string().min(1) });++const AddUsersBodySchema = z+ .object({+ userIds: z.string().uuid().array().default([]),+ emails: z+ .string()+ .email()+ .array()+ .default([])+ .refine((val) => val.every((el) => el === el.toLowerCase()), "Email must be lowercase"),+ role: z.string().min(1).default("operator")+ })+ .refine((val) => val.userIds.length + val.emails.length > 0, {+ message: "Provide at least one userId or email."+ });++const AddUsersResponseSchema = z.object({+ memberships: z.array(SignerMemberSchema),+ skipped: z.array(z.string()),+ unresolved: z.array(z.string())+});++export const registerSignerMembershipRoutes = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/:signerId/users",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listSignerUserMembers",+ tags: [ApiDocsTags.PkiSigners],+ description: "List user members of a signer",+ params: SignerIdParamsSchema,+ response: { 200: z.object({ memberships: z.array(SignerMemberSchema) }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const memberships = await server.services.signerMembership.listMembers({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ kind: SignerMemberKind.User+ });+ return { memberships };+ }+ });++ server.route({+ method: "POST",+ url: "/:signerId/users",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "addSignerUserMembers",+ tags: [ApiDocsTags.PkiSigners],+ description: "Add user members to a signer",+ params: SignerIdParamsSchema,+ body: AddUsersBodySchema,+ response: { 200: AddUsersResponseSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const result = await server.services.signerMembership.addUserMembers({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ userIds: req.body.userIds,+ emails: req.body.emails,+ role: req.body.role+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.ADD_PKI_SIGNER_MEMBER,+ metadata: {+ signerId: req.params.signerId,+ kind: SignerMemberKind.User,+ role: req.body.role,+ added: result.memberships.length,+ userIds: result.memberships.map((m) => m.actorUserId).filter((id): id is string => Boolean(id))+ }+ }+ });++ return result;+ }+ });++ server.route({+ method: "PATCH",+ url: "/:signerId/users/:userId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "updateSignerUserRole",+ tags: [ApiDocsTags.PkiSigners],+ description: "Update a user member's role on a signer",+ params: z.object({ signerId: z.string().uuid(), userId: z.string().uuid() }),+ body: RoleBodySchema,+ response: { 200: z.object({ membership: SignerMemberSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const membership = await server.services.signerMembership.updateMemberRole({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ kind: SignerMemberKind.User,+ memberId: req.params.userId,+ role: req.body.role+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.UPDATE_PKI_SIGNER_MEMBER,+ metadata: {+ signerId: req.params.signerId,+ kind: SignerMemberKind.User,+ memberId: req.params.userId,+ role: req.body.role+ }+ }+ });++ return { membership };+ }+ });++ server.route({+ method: "DELETE",+ url: "/:signerId/users/:userId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "removeSignerUserMember",+ tags: [ApiDocsTags.PkiSigners],+ description: "Remove a user from a signer",+ params: z.object({ signerId: z.string().uuid(), userId: z.string().uuid() }),+ response: { 200: z.object({ membershipId: z.string().uuid(), signerId: z.string().uuid() }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const result = await server.services.signerMembership.removeMember({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ kind: SignerMemberKind.User,+ memberId: req.params.userId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.REMOVE_PKI_SIGNER_MEMBER,+ metadata: { signerId: req.params.signerId, kind: SignerMemberKind.User, memberId: req.params.userId }+ }+ });++ return { membershipId: result.membershipId, signerId: result.signerId };+ }+ });++ server.route({+ method: "GET",+ url: "/:signerId/identities",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listSignerIdentityMembers",+ tags: [ApiDocsTags.PkiSigners],+ description: "List machine identity members of a signer",+ params: SignerIdParamsSchema,+ response: { 200: z.object({ memberships: z.array(SignerMemberSchema) }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const memberships = await server.services.signerMembership.listMembers({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ kind: SignerMemberKind.Identity+ });+ return { memberships };+ }+ });++ server.route({+ method: "POST",+ url: "/:signerId/identities",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "addSignerIdentityMember",+ tags: [ApiDocsTags.PkiSigners],+ description: "Add a machine identity to a signer",+ params: SignerIdParamsSchema,+ body: z.object({ identityId: z.string().uuid(), role: z.string().min(1).default("operator") }),+ response: { 200: SignerMemberSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const membership = await server.services.signerMembership.addMember({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ identityId: req.body.identityId,+ role: req.body.role+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.ADD_PKI_SIGNER_MEMBER,+ metadata: {+ signerId: req.params.signerId,+ kind: SignerMemberKind.Identity,+ role: req.body.role,+ identityId: req.body.identityId+ }+ }+ });++ return membership;+ }+ });++ server.route({+ method: "PATCH",+ url: "/:signerId/identities/:identityId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "updateSignerIdentityRole",+ tags: [ApiDocsTags.PkiSigners],+ description: "Update a machine identity's role on a signer",+ params: z.object({ signerId: z.string().uuid(), identityId: z.string().uuid() }),+ body: RoleBodySchema,+ response: { 200: z.object({ membership: SignerMemberSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const membership = await server.services.signerMembership.updateMemberRole({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ kind: SignerMemberKind.Identity,+ memberId: req.params.identityId,+ role: req.body.role+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.UPDATE_PKI_SIGNER_MEMBER,+ metadata: {+ signerId: req.params.signerId,+ kind: SignerMemberKind.Identity,+ memberId: req.params.identityId,+ role: req.body.role+ }+ }+ });++ return { membership };+ }+ });++ server.route({+ method: "DELETE",+ url: "/:signerId/identities/:identityId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "removeSignerIdentityMember",+ tags: [ApiDocsTags.PkiSigners],+ description: "Remove a machine identity from a signer",+ params: z.object({ signerId: z.string().uuid(), identityId: z.string().uuid() }),+ response: { 200: z.object({ membershipId: z.string().uuid(), signerId: z.string().uuid() }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const result = await server.services.signerMembership.removeMember({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ kind: SignerMemberKind.Identity,+ memberId: req.params.identityId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.REMOVE_PKI_SIGNER_MEMBER,+ metadata: { signerId: req.params.signerId, kind: SignerMemberKind.Identity, memberId: req.params.identityId }+ }+ });++ return { membershipId: result.membershipId, signerId: result.signerId };+ }+ });++ server.route({+ method: "GET",+ url: "/:signerId/groups",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listSignerGroupMembers",+ tags: [ApiDocsTags.PkiSigners],+ description: "List group members of a signer",+ params: SignerIdParamsSchema,+ response: { 200: z.object({ memberships: z.array(SignerMemberSchema) }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const memberships = await server.services.signerMembership.listMembers({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ kind: SignerMemberKind.Group+ });+ return { memberships };+ }+ });++ server.route({+ method: "POST",+ url: "/:signerId/groups",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "addSignerGroupMember",+ tags: [ApiDocsTags.PkiSigners],+ description: "Add a group to a signer",+ params: SignerIdParamsSchema,+ body: z.object({ groupId: z.string().uuid(), role: z.string().min(1).default("operator") }),+ response: { 200: SignerMemberSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const membership = await server.services.signerMembership.addMember({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ groupId: req.body.groupId,+ role: req.body.role+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.ADD_PKI_SIGNER_MEMBER,+ metadata: {+ signerId: req.params.signerId,+ kind: SignerMemberKind.Group,+ role: req.body.role,+ groupId: req.body.groupId+ }+ }+ });++ return membership;+ }+ });++ server.route({+ method: "PATCH",+ url: "/:signerId/groups/:groupId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "updateSignerGroupRole",+ tags: [ApiDocsTags.PkiSigners],+ description: "Update a group's role on a signer",+ params: z.object({ signerId: z.string().uuid(), groupId: z.string().uuid() }),+ body: RoleBodySchema,+ response: { 200: z.object({ membership: SignerMemberSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const membership = await server.services.signerMembership.updateMemberRole({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ kind: SignerMemberKind.Group,+ memberId: req.params.groupId,+ role: req.body.role+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.UPDATE_PKI_SIGNER_MEMBER,+ metadata: {+ signerId: req.params.signerId,+ kind: SignerMemberKind.Group,+ memberId: req.params.groupId,+ role: req.body.role+ }+ }+ });++ return { membership };+ }+ });++ server.route({+ method: "DELETE",+ url: "/:signerId/groups/:groupId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "removeSignerGroupMember",+ tags: [ApiDocsTags.PkiSigners],+ description: "Remove a group from a signer",+ params: z.object({ signerId: z.string().uuid(), groupId: z.string().uuid() }),+ response: { 200: z.object({ membershipId: z.string().uuid(), signerId: z.string().uuid() }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const result = await server.services.signerMembership.removeMember({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ kind: SignerMemberKind.Group,+ memberId: req.params.groupId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.REMOVE_PKI_SIGNER_MEMBER,+ metadata: { signerId: req.params.signerId, kind: SignerMemberKind.Group, memberId: req.params.groupId }+ }+ });++ return { membershipId: result.membershipId, signerId: result.signerId };+ }+ });++ server.route({+ method: "GET",+ url: "/:signerId/effective-users",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listSignerEffectiveUserMembers",+ tags: [ApiDocsTags.PkiSigners],+ description:+ "List users that can act on this signer either directly or via a group that's a signer member. Role is the highest the user holds across all paths.",+ params: SignerIdParamsSchema,+ response: { 200: z.object({ members: z.array(EffectiveSignerMemberSchema) }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const members = await server.services.signerMembership.listEffectiveMembers({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ kind: "user"+ });+ return { members };+ }+ });++ server.route({+ method: "GET",+ url: "/:signerId/effective-identities",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listSignerEffectiveIdentityMembers",+ tags: [ApiDocsTags.PkiSigners],+ description:+ "List machine identities that can act on this signer either directly or via a group that's a signer member.",+ params: SignerIdParamsSchema,+ response: { 200: z.object({ members: z.array(EffectiveSignerMemberSchema) }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const members = await server.services.signerMembership.listEffectiveMembers({+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.internalCertManagerProjectId,+ signerId: req.params.signerId,+ kind: "identity"+ });+ return { members };+ }+ });++ server.route({+ method: "GET",+ url: "/:signerId/members",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listSignerMembers",+ tags: [ApiDocsTags.PkiSigners],+ description: "List all members on a signer (users, identities, and groups combined).",+ params: SignerIdParamsSchema,+ response: { 200: z.object({ memberships: z.array(SignerMemberSchema) }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const projectId = req.internalCertManagerProjectId;+ const memberships = await server.services.signerMembership.listMembers({+ signerId: req.params.signerId,+ projectId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });+ return { memberships };+ }+ });++ server.route({+ method: "POST",+ url: "/:signerId/members",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "addSignerMember",+ tags: [ApiDocsTags.PkiSigners],+ description:+ "Add a member to a signer. Provide exactly one of `userId`, `identityId`, or `groupId` together with the desired `role`.",+ params: SignerIdParamsSchema,+ body: z+ .object({+ userId: z.string().uuid().optional(),+ identityId: z.string().uuid().optional(),+ groupId: z.string().uuid().optional(),+ role: z.string().min(1)+ })+ .refine(+ (b) => [b.userId, b.identityId, b.groupId].filter(Boolean).length === 1,+ "Provide exactly one of userId, identityId, or groupId."+ ),+ response: { 200: SignerMemberSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const projectId = req.internalCertManagerProjectId;+ const membership = await server.services.signerMembership.addMember({+ signerId: req.params.signerId,+ userId: req.body.userId,+ identityId: req.body.identityId,+ groupId: req.body.groupId,+ role: req.body.role,+ projectId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ // eslint-disable-next-line no-nested-ternary+ const memberKind = req.body.userId+ ? SignerMemberKind.User+ : req.body.identityId+ ? SignerMemberKind.Identity+ : SignerMemberKind.Group;+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId,+ event: {+ type: EventType.ADD_PKI_SIGNER_MEMBER,+ metadata: {+ signerId: req.params.signerId,+ kind: memberKind,+ role: req.body.role,+ userIds: req.body.userId ? [req.body.userId] : undefined,+ identityId: req.body.identityId,+ groupId: req.body.groupId+ }+ }+ });++ return membership;+ }+ });++ const MembershipParamsSchema = z.object({+ signerId: z.string().uuid(),+ membershipId: z.string().uuid()+ });++ server.route({+ method: "PATCH",+ url: "/:signerId/members/:membershipId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "updateSignerMemberRole",+ tags: [ApiDocsTags.PkiSigners],+ description: "Change a member's role on a signer.",+ params: MembershipParamsSchema,+ body: RoleBodySchema,+ response: { 200: SignerMemberSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const projectId = req.internalCertManagerProjectId;+ const { kind, memberId } = await server.services.signerMembership.resolveMembership({+ signerId: req.params.signerId,+ membershipId: req.params.membershipId,+ projectId+ });+ const membership = await server.services.signerMembership.updateMemberRole({+ signerId: req.params.signerId,+ kind,+ memberId,+ role: req.body.role,+ projectId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId,+ event: {+ type: EventType.UPDATE_PKI_SIGNER_MEMBER,+ metadata: { signerId: req.params.signerId, kind, memberId, role: req.body.role }+ }+ });++ return membership;+ }+ });++ server.route({+ method: "DELETE",+ url: "/:signerId/members/:membershipId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "removeSignerMember",+ tags: [ApiDocsTags.PkiSigners],+ description: "Remove a member from a signer.",+ params: MembershipParamsSchema,+ response: {+ 200: z.object({ membershipId: z.string().uuid(), signerId: z.string().uuid() })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const projectId = req.internalCertManagerProjectId;+ const { kind, memberId } = await server.services.signerMembership.resolveMembership({+ signerId: req.params.signerId,+ membershipId: req.params.membershipId,+ projectId+ });+ const result = await server.services.signerMembership.removeMember({+ signerId: req.params.signerId,+ kind,+ memberId,+ projectId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId,+ event: {+ type: EventType.REMOVE_PKI_SIGNER_MEMBER,+ metadata: { signerId: req.params.signerId, kind, memberId }+ }+ });++ return { membershipId: result.membershipId, signerId: result.signerId };+ }+ });+};diff --git a/backend/src/server/routes/v1/signer-router.ts b/backend/src/server/routes/v1/signer-router.tsindex 63fc374ec0..bfb1cbb41d 100644--- a/backend/src/server/routes/v1/signer-router.ts+++ b/backend/src/server/routes/v1/signer-router.ts@@ -9,9 +9,20 @@ import { openApiHidden, slugSchema } from "@app/server/lib/schemas";import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";-import { SignerStatus, SigningOperationStatus } from "@app/services/signer/signer-enums";+import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";+import { SigningOperationStatus } from "@app/services/signer/signer-enums";import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";+const SIGNER_KEY_ALGORITHM_VALUES = [+ CertKeyAlgorithm.RSA_2048,+ CertKeyAlgorithm.RSA_3072,+ CertKeyAlgorithm.RSA_4096,+ CertKeyAlgorithm.ECDSA_P256,+ CertKeyAlgorithm.ECDSA_P384,+ CertKeyAlgorithm.ECDSA_P521+] as const;+const SignerKeyAlgorithmEnum = z.enum(SIGNER_KEY_ALGORITHM_VALUES);+export const registerSignerRouter = async (server: FastifyZodProvider) => {server.route({method: "POST",@@ -26,8 +37,41 @@ export const registerSignerRouter = async (server: FastifyZodProvider) => {projectId: z.string().trim().optional().describe(openApiHidden()),name: slugSchema({ min: 1, max: 64, field: "name" }),description: z.string().trim().max(256).optional(),- certificateId: z.string().uuid(),- approvalPolicyId: z.string().uuid().optional()+ caId: z.string().uuid().optional(),+ commonName: z.string().trim().min(1).max(256).optional(),+ certificateTtlDays: z.number().int().min(1).max(3650).optional(),+ renewBeforeDays: z.number().int().min(1).max(30).nullable().optional(),+ keyAlgorithm: SignerKeyAlgorithmEnum.optional(),+ certificateId: z.string().uuid().optional(),+ approvalPolicyId: z.string().uuid().optional(),+ members: z+ .array(+ z.object({+ kind: z.enum(["user", "identity", "group"]),+ id: z.string().uuid(),+ role: z.string().min(1)+ })+ )+ .optional(),+ approvalPolicy: z+ .object({+ steps: z.array(+ z.object({+ stepNumber: z.number().int().min(1),+ name: z.string().trim().max(64).nullable().optional(),+ requiredApprovals: z.number().int().min(1),+ approverUserIds: z.array(z.string().uuid()).default([]),+ approverGroupIds: z.array(z.string().uuid()).default([])+ })+ ),+ constraints: z+ .object({+ maxSignings: z.number().int().min(1).nullable().optional(),+ maxWindowDuration: z.string().nullable().optional()+ })+ .optional()+ })+ .optional()}),response: {200: PkiSignersSchema@@ -180,6 +224,44 @@ export const registerSignerRouter = async (server: FastifyZodProvider) => {}});+ server.route({+ method: "GET",+ url: "/:signerId/my-permissions",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "getSignerMyPermissions",+ tags: [ApiDocsTags.PkiSigners],+ description: "Get the caller's effective per-signer capabilities",+ params: z.object({ signerId: z.string().uuid() }),+ response: {+ 200: z.object({+ canRead: z.boolean(),+ canEdit: z.boolean(),+ canDelete: z.boolean(),+ canEnableDisable: z.boolean(),+ canManageMembers: z.boolean(),+ canManagePolicy: z.boolean(),+ canSign: z.boolean(),+ canRequestSign: z.boolean(),+ canPreApprove: z.boolean(),+ canReissueCertificate: z.boolean(),+ canExportCertificate: z.boolean()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ return server.services.pkiSigner.getMyPermissions({+ signerId: req.params.signerId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });+ }+ });+server.route({method: "PATCH",url: "/:signerId",@@ -195,9 +277,7 @@ export const registerSignerRouter = async (server: FastifyZodProvider) => {body: z.object({name: slugSchema({ min: 1, max: 64, field: "name" }).optional(),description: z.string().trim().max(256).nullable().optional(),- status: z.nativeEnum(SignerStatus).optional(),- certificateId: z.string().uuid().optional(),- approvalPolicyId: z.string().uuid().nullable().optional()+ renewBeforeDays: z.number().int().min(1).max(30).nullable().optional()}),response: {200: PkiSignersSchema@@ -404,6 +484,419 @@ export const registerSignerRouter = async (server: FastifyZodProvider) => {}});+ server.route({+ method: "POST",+ url: "/:signerId/enable",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "enableSigner",+ tags: [ApiDocsTags.PkiSigners],+ description: "Enable a disabled signer",+ params: z.object({ signerId: z.string().uuid() }),+ response: { 200: PkiSignersSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const signer = await server.services.pkiSigner.enable({+ signerId: req.params.signerId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: signer.projectId,+ event: {+ type: EventType.ENABLE_PKI_SIGNER,+ metadata: { signerId: signer.id, name: signer.name }+ }+ });++ return signer;+ }+ });++ server.route({+ method: "POST",+ url: "/:signerId/disable",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "disableSigner",+ tags: [ApiDocsTags.PkiSigners],+ description: "Disable an active signer",+ params: z.object({ signerId: z.string().uuid() }),+ response: { 200: PkiSignersSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const signer = await server.services.pkiSigner.disable({+ signerId: req.params.signerId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: signer.projectId,+ event: {+ type: EventType.DISABLE_PKI_SIGNER,+ metadata: { signerId: signer.id, name: signer.name }+ }+ });++ return signer;+ }+ });++ server.route({+ method: "POST",+ url: "/:signerId/certificate/reissue",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "reissueSignerCertificate",+ tags: [ApiDocsTags.PkiSigners],+ description: "Re-issue the signer's certificate (optionally from a different CA)",+ params: z.object({ signerId: z.string().uuid() }),+ body: z.object({+ caId: z.string().uuid(),+ commonName: z.string().trim().min(1).max(256).optional(),+ certificateTtlDays: z.number().int().min(1).max(3650).optional()+ }),+ response: { 200: PkiSignersSchema }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const signer = await server.services.pkiSigner.reissueCertificate({+ signerId: req.params.signerId,+ ...req.body,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: signer.projectId,+ event: {+ type: EventType.REISSUE_PKI_SIGNER_CERTIFICATE,+ metadata: {+ signerId: signer.id,+ name: signer.name,+ caId: req.body.caId,+ commonName: req.body.commonName+ }+ }+ });++ return signer;+ }+ });++ server.route({+ method: "GET",+ url: "/:signerId/certificate",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "exportSignerCertificate",+ tags: [ApiDocsTags.PkiSigners],+ description: "Export the signer's leaf certificate as PEM",+ params: z.object({ signerId: z.string().uuid() }),+ response: {+ 200: z.object({+ certificatePem: z.string(),+ serialNumber: z.string(),+ signerName: z.string()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const { certificatePem, serialNumber, signerName, projectId } = await server.services.pkiSigner.exportCertificate(+ {+ signerId: req.params.signerId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ }+ );++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId,+ event: {+ type: EventType.EXPORT_PKI_SIGNER_CERTIFICATE,+ metadata: { signerId: req.params.signerId, name: signerName, serialNumber }+ }+ });++ return { certificatePem, serialNumber, signerName };+ }+ });++ server.route({+ method: "GET",+ url: "/:signerId/approval-policy",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "getSignerApprovalPolicy",+ tags: [ApiDocsTags.PkiSigners],+ description: "Read the signer's approval policy (steps, approvers, limits)",+ params: z.object({ signerId: z.string().uuid() }),+ response: {+ 200: z.object({+ id: z.string().uuid(),+ signerId: z.string().uuid(),+ hasSteps: z.boolean(),+ steps: z.array(z.any()),+ constraints: z.object({+ maxSignings: z.number().nullable(),+ maxWindowDuration: z.string().nullable()+ })+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ return server.services.signerPolicy.getPolicy({+ signerId: req.params.signerId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });+ }+ });++ server.route({+ method: "PATCH",+ url: "/:signerId/approval-policy",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "updateSignerApprovalPolicy",+ tags: [ApiDocsTags.PkiSigners],+ description: "Edit the signer's approval policy (steps, approvers, limits)",+ params: z.object({ signerId: z.string().uuid() }),+ body: z.object({+ steps: z.array(+ z.object({+ stepNumber: z.number().int().min(1),+ name: z.string().trim().max(64).nullable().optional(),+ requiredApprovals: z.number().int().min(1),+ approverUserIds: z.array(z.string().uuid()).default([]),+ approverGroupIds: z.array(z.string().uuid()).default([])+ })+ ),+ constraints: z+ .object({+ maxSignings: z.number().int().min(1).nullable().optional(),+ maxWindowDuration: z.string().nullable().optional()+ })+ .optional()+ })+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const policy = await server.services.signerPolicy.updatePolicy({+ signerId: req.params.signerId,+ ...req.body,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.UPDATE_PKI_SIGNER_APPROVAL_POLICY,+ metadata: { signerId: req.params.signerId, stepCount: req.body.steps.length }+ }+ });++ return policy;+ }+ });++ server.route({+ method: "GET",+ url: "/:signerId/requests",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listSignerRequests",+ tags: [ApiDocsTags.PkiSigners],+ description: "List signing approval requests for a signer",+ params: z.object({ signerId: z.string().uuid() }),+ querystring: z.object({+ statuses: z+ .string()+ .optional()+ .transform((v) =>+ v+ ? v+ .split(",")+ .map((s) => s.trim())+ .filter((s): s is "pending" | "approved" | "expired" | "revoked" =>+ ["pending", "approved", "expired", "revoked"].includes(s)+ )+ : undefined+ ),+ offset: z.coerce.number().int().min(0).default(0),+ limit: z.coerce.number().int().min(1).max(100).default(25)+ })+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ return server.services.signerPolicy.listRequests({+ signerId: req.params.signerId,+ statuses: req.query.statuses,+ offset: req.query.offset,+ limit: req.query.limit,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });+ }+ });++ server.route({+ method: "POST",+ url: "/:signerId/requests",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "requestToSign",+ tags: [ApiDocsTags.PkiSigners],+ description: "Open a request to sign with this signer (operator self-serve)",+ params: z.object({ signerId: z.string().uuid() }),+ body: z.object({+ justification: z.string().trim().min(1).max(2048),+ requestedSignings: z.number().int().min(1).optional(),+ requestedWindowStart: z.string().datetime().optional(),+ requestedWindowEnd: z.string().datetime().optional()+ })+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const request = await server.services.signerPolicy.requestToSign({+ signerId: req.params.signerId,+ ...req.body,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.PKI_SIGNER_REQUEST_TO_SIGN,+ metadata: { signerId: req.params.signerId, requestId: request?.id }+ }+ });++ return request;+ }+ });++ server.route({+ method: "POST",+ url: "/:signerId/requests/pre-approve",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "preApproveSigning",+ tags: [ApiDocsTags.PkiSigners],+ description: "Pre-approve signing for a member (admin only)",+ params: z.object({ signerId: z.string().uuid() }),+ body: z.object({+ granteeUserId: z.string().uuid().optional(),+ granteeIdentityId: z.string().uuid().optional(),+ justification: z.string().trim().min(1).max(2048),+ requestedSignings: z.number().int().min(1).optional(),+ requestedWindowStart: z.string().datetime().optional(),+ requestedWindowEnd: z.string().datetime().optional()+ })+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const result = await server.services.signerPolicy.preApproveSigning({+ signerId: req.params.signerId,+ ...req.body,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.PKI_SIGNER_PRE_APPROVE_SIGNING,+ metadata: {+ signerId: req.params.signerId,+ requestId: result?.request?.id,+ granteeUserId: req.body.granteeUserId,+ granteeIdentityId: req.body.granteeIdentityId+ }+ }+ });++ return result;+ }+ });++ server.route({+ method: "POST",+ url: "/:signerId/requests/:requestId/revoke",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "revokeSignerRequest",+ tags: [ApiDocsTags.PkiSigners],+ description: "Revoke a pending or active signing request",+ params: z.object({ signerId: z.string().uuid(), requestId: z.string().uuid() })+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const result = await server.services.signerPolicy.revokeRequest({+ signerId: req.params.signerId,+ requestId: req.params.requestId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ projectId: req.internalCertManagerProjectId,+ event: {+ type: EventType.PKI_SIGNER_REVOKE_REQUEST,+ metadata: { signerId: req.params.signerId, requestId: req.params.requestId }+ }+ });++ return result;+ }+ });+server.route({method: "GET",url: "/:signerId/operations",diff --git a/backend/src/services/approval-policy/approval-policy-enums.ts b/backend/src/services/approval-policy/approval-policy-enums.tsindex 7915c4df7f..8dc375e1a9 100644--- a/backend/src/services/approval-policy/approval-policy-enums.ts+++ b/backend/src/services/approval-policy/approval-policy-enums.ts@@ -6,7 +6,8 @@ export enum ApprovalPolicyType {export enum ApprovalPolicyScope {Project = "project",- PkiApplication = "pki-application"+ PkiApplication = "pki-application",+ Signer = "signer"}export enum ApproverType {diff --git a/backend/src/services/approval-policy/approval-request-dal.ts b/backend/src/services/approval-policy/approval-request-dal.tsindex a214965a7c..82bafcbdca 100644--- a/backend/src/services/approval-policy/approval-request-dal.ts+++ b/backend/src/services/approval-policy/approval-request-dal.ts@@ -1,11 +1,12 @@import { Knex } from "knex";import { TDbClient } from "@app/db";-import { TableName, TApprovalRequestApprovals } from "@app/db/schemas";+import { TableName, TApprovalRequestApprovals, TApprovalRequests } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";import { ormify, selectAllTableCols } from "@app/lib/knex";import {+ ApprovalPolicyScope,ApprovalPolicyType,ApprovalRequestGrantStatus,ApprovalRequestStatus,@@ -162,6 +163,112 @@ export const approvalRequestDALFactory = (db: TDbClient) => {}};+ const listSignerRequestsPaginated = async ({+ signerId,+ projectId,+ type,+ statuses,+ offset,+ limit+ }: {+ signerId: string;+ projectId: string;+ type: ApprovalPolicyType;+ statuses?: string[];+ offset: number;+ limit: number;+ }) => {+ try {+ const usageSubquery = db+ .replicaNode()(TableName.PkiSigningOperations)+ .select("approvalGrantId")+ .count("* as usedSignings")+ .where({ status: "success" })+ .whereNotNull("approvalGrantId")+ .groupBy("approvalGrantId")+ .as("usage");++ const dedupedRequests = db+ .replicaNode()(TableName.ApprovalRequests)+ .leftJoin(TableName.ApprovalRequestGrants, function joinGrants() {+ this.on(`${TableName.ApprovalRequestGrants}.requestId`, "=", `${TableName.ApprovalRequests}.id`);+ })+ .leftJoin(usageSubquery, "usage.approvalGrantId", `${TableName.ApprovalRequestGrants}.id`)+ .where(`${TableName.ApprovalRequests}.projectId`, projectId)+ .where(`${TableName.ApprovalRequests}.type`, type)+ .where(`${TableName.ApprovalRequests}.scopeType`, ApprovalPolicyScope.Signer)+ .where(`${TableName.ApprovalRequests}.scopeId`, signerId)+ .modify((qb) => {+ if (statuses?.length) {+ void qb.whereIn(`${TableName.ApprovalRequests}.status`, statuses);+ }+ })+ .distinctOn(`${TableName.ApprovalRequests}.id`)+ .select(+ `${TableName.ApprovalRequests}.*`,+ db.ref("attributes").withSchema(TableName.ApprovalRequestGrants).as("grantAttributes"),+ db.ref("expiresAt").withSchema(TableName.ApprovalRequestGrants).as("grantExpiresAt"),+ db.ref("status").withSchema(TableName.ApprovalRequestGrants).as("grantStatus"),+ db.ref("grantedByUserId").withSchema(TableName.ApprovalRequestGrants).as("grantedByUserId"),+ db.raw('COALESCE("usage"."usedSignings", 0) AS "usedSignings"')+ )+ .orderByRaw(+ `"${TableName.ApprovalRequests}"."id", ("${TableName.ApprovalRequestGrants}"."status" = ?) DESC NULLS LAST, "${TableName.ApprovalRequestGrants}"."createdAt" DESC NULLS LAST`,+ [ApprovalRequestGrantStatus.Active]+ )+ .as("dedup");++ const rows = (await db+ .replicaNode()+ .select("*")+ .from(dedupedRequests)+ .orderBy("createdAt", "desc")+ .offset(offset)+ .limit(limit)) as (TApprovalRequests & {+ grantAttributes?: { maxSignings?: number | null } | null;+ grantExpiresAt?: Date | string | null;+ grantStatus?: string | null;+ grantedByUserId?: string | null;+ usedSignings?: string | number;+ })[];+ return rows.map((row) => ({+ ...row,+ expiresAt: row.grantExpiresAt ?? row.expiresAt ?? null,+ maxSignings: row.grantAttributes?.maxSignings ?? null,+ usedSignings: Number(row.usedSignings ?? 0),+ grantStatus: row.grantStatus ?? null,+ grantedByUserId: row.grantedByUserId ?? null+ }));+ } catch (error) {+ throw new DatabaseError({ error, name: "ListSignerRequestsPaginated" });+ }+ };++ const countSignerRequests = async ({+ signerId,+ projectId,+ type,+ statuses+ }: {+ signerId: string;+ projectId: string;+ type: ApprovalPolicyType;+ statuses?: string[];+ }) => {+ try {+ const query = db+ .replicaNode()(TableName.ApprovalRequests)+ .where({ projectId, type, scopeType: ApprovalPolicyScope.Signer, scopeId: signerId });+ if (statuses?.length) {+ void query.whereIn("status", statuses);+ }+ const result = (await query.count("* as count").first()) as { count: string | number } | undefined;+ return Number(result?.count ?? 0);+ } catch (error) {+ throw new DatabaseError({ error, name: "CountSignerRequests" });+ }+ };+const markExpiredRequests = async (): Promise<string[]> => {try {const expiredRequestIds = await db(TableName.ApprovalRequests)@@ -184,7 +291,15 @@ export const approvalRequestDALFactory = (db: TDbClient) => {}};- return { ...orm, findStepsByRequestId, findByProjectId, findByIdForUpdate, markExpiredRequests };+ return {+ ...orm,+ findStepsByRequestId,+ findByProjectId,+ findByIdForUpdate,+ markExpiredRequests,+ listSignerRequestsPaginated,+ countSignerRequests+ };};// Approval Request Stepsdiff --git a/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts b/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.tsindex 85d875c6c6..b09305e123 100644--- a/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts@@ -59,6 +59,65 @@ import { azureDnsDeleteTxtRecord, azureDnsInsertTxtRecord } from "./dns-providerimport { cloudflareDeleteTxtRecord, cloudflareInsertTxtRecord } from "./dns-providers/cloudflare";import { dnsMadeEasyDeleteTxtRecord, dnsMadeEasyInsertTxtRecord } from "./dns-providers/dns-made-easy";+const ACME_INTERCEPTOR_FLAG = Symbol.for("infisical.acme.responseInterceptor.v1");+const looksLikeClassName = new RE2("^[A-Z][a-zA-Z0-9]*(Error|Exception)$");++type TAcmeProblemBody = {+ error?: unknown;+ detail?: unknown;+ type?: unknown;+ status?: unknown;+ subproblems?: unknown;+};++(() => {+ // eslint-disable-next-line @typescript-eslint/ban-types+ const ax = (acme as unknown as { axios?: { interceptors?: { response?: { use?: Function } }; [s: symbol]: unknown } })+ .axios;+ if (!ax || !ax.interceptors?.response?.use) return;+ if ((ax as { [s: symbol]: unknown })[ACME_INTERCEPTOR_FLAG]) return;++ (+ ax.interceptors.response.use as (+ fulfilled: (r: {+ status: number;+ statusText?: string;+ data?: unknown;+ config?: { url?: string; method?: string };+ }) => unknown+ ) => void+ )((response) => {+ if (response.status >= 200 && response.status < 300) return response;++ const body = response.data as TAcmeProblemBody | undefined;+ if (body && typeof body === "object") {+ logger.error(+ {+ acmeRequestUrl: response.config?.url,+ acmeRequestMethod: response.config?.method,+ acmeStatus: response.status,+ acmeStatusText: response.statusText,+ acmeResponseBody: body+ },+ `ACME response error from upstream CA [status=${response.status}] [url=${response.config?.url ?? "?"}]`+ );++ if (+ typeof body.error === "string" &&+ looksLikeClassName.test(body.error.trim()) &&+ typeof body.detail === "string" &&+ body.detail.trim().length > 0+ ) {+ body.error = body.detail;+ }+ }++ return response;+ });++ (ax as { [s: symbol]: unknown })[ACME_INTERCEPTOR_FLAG] = true;+})();+const validateDnsResolver = (resolver: string): void => {const appCfg = getConfig();@@ -414,6 +473,19 @@ export const orderCertificate = async (const acmeClient = new acme.Client(acmeClientOptions);+ const accountPayload: { termsOfServiceAgreed: boolean; contact?: string[] } = {+ termsOfServiceAgreed: true+ };+ if (acmeCa.configuration.accountEmail) {+ accountPayload.contact = [`mailto:${acmeCa.configuration.accountEmail}`];+ }+ try {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access+ await (acmeClient as any).api.createAccount(accountPayload);+ } catch (err) {+ logger.error(err, `ACME pre-register account failed [caId=${caId}] — falling back to auto() registration`);+ }+const appConnection = await appConnectionDAL.findById(acmeCa.configuration.dnsAppConnectionId);const connection = await decryptAppConnection(appConnection, kmsService);diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.tsindex 03791583f3..7345c34e3a 100644--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts@@ -1,4 +1,4 @@-import acme from "acme-client";+import * as x509 from "@peculiar/x509";import { UnrecoverableError } from "bullmq";import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";@@ -92,7 +92,7 @@ const ensureCsrPemFormat = (csr: string): string => {export type TIssueCertificateFromProfileJobData = {certificateId: string;- profileId: string;+ profileId?: string;caId: string;caType?: CaType;commonName?: string;@@ -326,7 +326,8 @@ export const certificateIssuanceQueueFactory = ({}}- await queueService.queue(QueueName.CertificateIssuance, QueueJobs.CaIssueCertificateFromProfile, jobData, {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument+ await queueService.queue(QueueName.CertificateIssuance, QueueJobs.CaIssueCertificateFromProfile, jobData as any, {jobId: `certificate-issuance-${jobIdSeed}`,...queueOpts});@@ -410,14 +411,42 @@ export const certificateIssuanceQueueFactory = ({const skLeafObj = crypto.nativeCrypto.KeyObject.from(leafKeys.privateKey);skLeaf = skLeafObj.export({ format: "pem", type: "pkcs8" }) as string;- const [, generatedCsr] = await acme.crypto.createCsr(- {- altNames: altNames ? altNames.map((san) => san.value) : [],- commonName: commonName || ""- },- skLeaf- );- certificateCsr = generatedCsr.toString();+ const csrExtensions: x509.Extension[] = [];+ if (altNames && altNames.length > 0) {+ csrExtensions.push(+ new x509.SubjectAlternativeNameExtension(+ altNames.map((san) => ({+ type: (san.type === "ip" ? "ip" : "dns") as "ip" | "dns",+ value: san.value+ }))+ )+ );+ }+ if (keyUsages && keyUsages.length > 0) {+ // eslint-disable-next-line no-bitwise+ const bits = (keyUsages as CertKeyUsage[]).reduce(+ // eslint-disable-next-line no-bitwise+ (acc, ku) => acc | x509.KeyUsageFlags[ku],+ 0+ );+ if (bits) csrExtensions.push(new x509.KeyUsagesExtension(bits, true));+ }+ if (extendedKeyUsages && extendedKeyUsages.length > 0) {+ csrExtensions.push(+ new x509.ExtendedKeyUsageExtension(+ (extendedKeyUsages as CertExtendedKeyUsage[]).map((eku) => x509.ExtendedKeyUsage[eku]),+ true+ )+ );+ }++ const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({+ name: commonName ? `CN=${commonName}` : "",+ keys: leafKeys,+ signingAlgorithm: keyAlg,+ extensions: csrExtensions+ });+ certificateCsr = csrObj.toString("pem");}if (await isCancelled()) {@@ -502,7 +531,7 @@ export const certificateIssuanceQueueFactory = ({} else if (ca.externalCa?.type === CaType.AZURE_AD_CS) {await setPending("Submitting the request to Azure AD CS");let template: string | undefined;- if (certificateProfileDAL) {+ if (certificateProfileDAL && profileId) {try {const profile = await certificateProfileDAL.findById(profileId);if (@@ -544,7 +573,9 @@ export const certificateIssuanceQueueFactory = ({return;}- const azureResult = await azureAdCsFns.orderCertificateFromProfile(azureParams);+ const azureResult = await azureAdCsFns.orderCertificateFromProfile(+ azureParams as Parameters<typeof azureAdCsFns.orderCertificateFromProfile>[0]+ );if (await isCancelled()) {logger.info(`Cancelled after Azure AD CS order [certificateRequestId=${certificateRequestId}]`);@@ -612,7 +643,9 @@ export const certificateIssuanceQueueFactory = ({return;}- const acmResult = await awsAcmPublicCaFns.orderCertificateFromProfile(acmParams);+ const acmResult = await awsAcmPublicCaFns.orderCertificateFromProfile(+ acmParams as Parameters<typeof awsAcmPublicCaFns.orderCertificateFromProfile>[0]+ );if (await isCancelled()) {logger.info(`Cancelled after AWS ACM Public CA order [certificateRequestId=${certificateRequestId}]`);@@ -679,7 +712,9 @@ export const certificateIssuanceQueueFactory = ({return;}- const awsPcaResult = await awsPcaFns.orderCertificateFromProfile(awsPcaParams);+ const awsPcaResult = await awsPcaFns.orderCertificateFromProfile(+ awsPcaParams as Parameters<typeof awsPcaFns.orderCertificateFromProfile>[0]+ );if (await isCancelled()) {logger.info(`Cancelled after AWS Private CA order [certificateRequestId=${certificateRequestId}]`);@@ -870,7 +905,9 @@ export const certificateIssuanceQueueFactory = ({return;}- const venafiTppResult = await venafiTppFns.orderCertificateFromProfile(venafiTppParams);+ const venafiTppResult = await venafiTppFns.orderCertificateFromProfile(+ venafiTppParams as Parameters<typeof venafiTppFns.orderCertificateFromProfile>[0]+ );if (await isCancelled()) {logger.info(`Cancelled after Venafi TPP order [certificateRequestId=${certificateRequestId}]`);@@ -1100,6 +1137,12 @@ export const certificateIssuanceQueueFactory = ({return {queueCertificateIssuance,- processCertificateIssuanceJobs+ processCertificateIssuanceJobs,+ acmeFns,+ azureAdCsFns,+ awsPcaFns,+ awsAcmPublicCaFns,+ digicertFns,+ venafiTppFns};};diff --git a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.ts b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.tsindex 8d1643836e..4771575cc7 100644--- a/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/digicert/digicert-certificate-authority-fns.ts@@ -39,6 +39,7 @@ import { CaStatus, CaType } from "../certificate-authority-enums";import { extractDnParts, keyAlgorithmToAlgCfg } from "../certificate-authority-fns";import { TExternalCertificateAuthorityDALFactory } from "../external-certificate-authority-dal";import { createDigiCertApiClient } from "./digicert-api-client";+import { DIGICERT_FINAL_ISSUED_STATUSES, DigiCertOrderStatus } from "./digicert-certificate-authority-enums";import {TCreateDigiCertCertificateAuthorityDTO,TDigiCertCertificateAuthority,@@ -659,6 +660,57 @@ export const DigiCertCertificateAuthorityFns = ({return { certificateId: createdCertificateId, certificatePem: leaf };};+ const pollOrderForCertificate = async ({+ caId,+ orderId+ }: {+ caId: string;+ orderId: number;+ }): Promise<+ | { status: "issued"; certificateId: number }+ | { status: "pending"; orderStatus: string }+ | { status: "failed"; orderStatus: string; reason: string }+ > => {+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);+ if (!ca.externalCa || ca.externalCa.type !== CaType.DIGICERT) {+ throw new BadRequestError({ message: "CA is not a DigiCert certificate authority" });+ }+ const digicertCa = castDbEntryToDigiCertCertificateAuthority(ca);++ const { apiKey, baseUrl } = await getDigiCertClientCredentials(+ digicertCa.configuration.appConnectionId,+ appConnectionDAL,+ kmsService+ );+ const client = createDigiCertApiClient(apiKey, baseUrl);++ const orderInfo = await client.getOrder(orderId);+ let orderStatus = orderInfo.status?.toLowerCase() ?? "unknown";+ let certificateId = orderInfo.certificate?.id;++ if (orderStatus === DigiCertOrderStatus.Pending) {+ const checkResult = await client.checkValidation(orderId);+ orderStatus = checkResult.order_status?.toLowerCase() ?? orderStatus;+ certificateId = checkResult.certificate_id ?? certificateId;+ }++ const isFinalisable = DIGICERT_FINAL_ISSUED_STATUSES.some((status) => status === orderStatus);+ if (isFinalisable && certificateId) {+ return { status: "issued", certificateId };+ }++ if (+ orderStatus === DigiCertOrderStatus.Rejected ||+ orderStatus === DigiCertOrderStatus.Canceled ||+ orderStatus === DigiCertOrderStatus.Expired ||+ orderStatus === DigiCertOrderStatus.Revoked+ ) {+ return { status: "failed", orderStatus, reason: `DigiCert order ${orderStatus}` };+ }++ return { status: "pending", orderStatus };+ };+const revokeCertificate = async ({caId,serialNumber,@@ -719,6 +771,7 @@ export const DigiCertCertificateAuthorityFns = ({listCertificateAuthorities,orderCertificateFromProfile,fetchAndAttachIssuedCertificate,+ pollOrderForCertificate,revokeCertificate};};diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.tsindex 0bf67b7aed..cee0829a83 100644--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts@@ -120,6 +120,11 @@ export const dailyResourceCleanUpQueueServiceFactory = ({handler: async () => {logger.info(`cron[${CronJobName.FrequentResourceCleanup}]: task started`);await identityAccessTokenDAL.removeExpiredTokens();+ const expiredApprovalRequestIds = await approvalRequestDAL.markExpiredRequests();+ if (expiredApprovalRequestIds.length > 0) {+ await certificateRequestDAL.markExpiredApprovalRequests(expiredApprovalRequestIds);+ }+ await approvalRequestGrantsDAL.markExpiredGrants();}});};diff --git a/backend/src/services/signer-membership/index.ts b/backend/src/services/signer-membership/index.tsnew file mode 100644index 0000000000..7b82d76c02--- /dev/null+++ b/backend/src/services/signer-membership/index.ts@@ -0,0 +1,2 @@+export { signerMembershipServiceFactory, type TSignerMembershipServiceFactory } from "./signer-membership-service";+export * from "./signer-membership-types";diff --git a/backend/src/services/signer-membership/signer-membership-service.ts b/backend/src/services/signer-membership/signer-membership-service.tsnew file mode 100644index 0000000000..36b36a658b--- /dev/null+++ b/backend/src/services/signer-membership/signer-membership-service.ts@@ -0,0 +1,914 @@+import { ForbiddenError } from "@casl/ability";+import { Knex } from "knex";++import {+ AccessScope,+ ActionProjectType,+ ApplicationMembershipRole,+ ProjectMembershipRole,+ RESOURCE_SCOPE,+ ResourceType+} from "@app/db/schemas";+import { TGroupDALFactory } from "@app/ee/services/group/group-dal";+import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";+import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { ProjectPermissionMemberActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";+import { ResourcePermissionSub } from "@app/ee/services/permission/resource-permission";+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { ActorType } from "@app/services/auth/auth-type";++import { TApprovalPolicyDALFactory } from "../approval-policy/approval-policy-dal";+import { ApprovalPolicyScope } from "../approval-policy/approval-policy-enums";+import { TIdentityDALFactory } from "../identity/identity-dal";+import { TMembershipDALFactory } from "../membership/membership-dal";+import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";+import { TSignerDALFactory } from "../signer/signer-dal";+import { TUserDALFactory } from "../user/user-dal";+import {+ SignerMemberKind,+ TAddSignerMemberDTO,+ TAddSignerUserMembersDTO,+ TEffectiveSignerMember,+ TListEffectiveSignerMembersDTO,+ TListSignerMembersDTO,+ TRemoveSignerMemberDTO,+ TSignerMember,+ TSignerMemberKind,+ TUpdateSignerMemberRoleDTO+} from "./signer-membership-types";++type TSignerMembershipServiceFactoryDep = {+ signerDAL: Pick<TSignerDALFactory, "findById" | "find">;+ membershipDAL: Pick<+ TMembershipDALFactory,+ | "create"+ | "findById"+ | "find"+ | "delete"+ | "deleteById"+ | "transaction"+ | "findResourceMembershipsForActor"+ | "findResourceMembershipsForGroup"+ >;+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "find" | "delete" | "update">;+ permissionService: Pick<TPermissionServiceFactory, "getResourcePermission" | "getProjectPermission">;+ userDAL: Pick<TUserDALFactory, "find" | "findByEmailsOrUsernames">;+ identityDAL: Pick<TIdentityDALFactory, "find">;+ groupDAL: Pick<TGroupDALFactory, "find">;+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;+ identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;+ approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "deleteStepApproversBySubject">;+};++export type TSignerMembershipServiceFactory = ReturnType<typeof signerMembershipServiceFactory>;++export const BUILTIN_SIGNER_ROLES = Object.values(ApplicationMembershipRole).filter(+ (r) => r !== ApplicationMembershipRole.Custom+);++export const isBuiltInSignerRole = (role: string): role is ApplicationMembershipRole =>+ (BUILTIN_SIGNER_ROLES as string[]).includes(role);++export const unknownSignerRoleMessage = (role: string) =>+ `Unknown signer role '${role}'. Expected one of: ${BUILTIN_SIGNER_ROLES.join(", ")}.`;++const ROLE_RANK: Record<string, number> = {+ [ApplicationMembershipRole.Admin]: 3,+ [ApplicationMembershipRole.Operator]: 2,+ [ApplicationMembershipRole.Auditor]: 1+};++const pickHigherRole = (a: string, b: string) => ((ROLE_RANK[b] ?? 0) > (ROLE_RANK[a] ?? 0) ? b : a);++export const signerMembershipServiceFactory = ({+ signerDAL,+ membershipDAL,+ membershipRoleDAL,+ permissionService,+ userDAL,+ identityDAL,+ groupDAL,+ userGroupMembershipDAL,+ identityGroupMembershipDAL,+ approvalPolicyDAL+}: TSignerMembershipServiceFactoryDep) => {+ const $loadSignerOrThrow = async (signerId: string, projectId: string) => {+ const signer = await signerDAL.findById(signerId);+ if (!signer || signer.projectId !== projectId) {+ throw new NotFoundError({ message: `Signer with id '${signerId}' not found.` });+ }+ return signer;+ };++ const $buildMemberDetails = async (member: {+ actorUserId?: string | null;+ actorIdentityId?: string | null;+ actorGroupId?: string | null;+ }): Promise<TSignerMember["details"]> => {+ if (member.actorUserId) {+ const [u] = await userDAL.find({ $in: { id: [member.actorUserId] } });+ if (!u) return null;+ const fullName = [u.firstName, u.lastName].filter((p): p is string => Boolean(p?.trim())).join(" ") || null;+ return { name: fullName, email: u.email ?? null, username: u.username ?? null };+ }+ if (member.actorIdentityId) {+ const [i] = await identityDAL.find({ $in: { id: [member.actorIdentityId] } });+ if (!i) return null;+ return { name: i.name, authMethod: i.authMethod ?? null };+ }+ if (member.actorGroupId) {+ const [g] = await groupDAL.find({ $in: { id: [member.actorGroupId] } });+ if (!g) return null;+ return { name: g.name, slug: g.slug };+ }+ return null;+ };++ const $assertActorPresentInOrg = async (+ orgId: string,+ actor: { userId?: string; identityId?: string; groupId?: string }+ ) => {+ const setActors = [actor.userId, actor.identityId, actor.groupId].filter(Boolean);+ if (setActors.length !== 1) {+ throw new BadRequestError({+ message: "Exactly one of userId, identityId, or groupId must be provided."+ });+ }++ const where: Record<string, unknown> = {+ scope: AccessScope.Organization,+ scopeOrgId: orgId+ };+ if (actor.userId) where.actorUserId = actor.userId;+ else if (actor.identityId) where.actorIdentityId = actor.identityId;+ else if (actor.groupId) where.actorGroupId = actor.groupId;++ const orgMembership = await membershipDAL.find(where);+ if (!orgMembership.length) {+ throw new BadRequestError({+ message: "The actor is not a member of this organization. Invite them to the organization first."+ });+ }+ return orgMembership[0];+ };++ const $loadResourcePermission = (+ signerId: string,+ projectId: string,+ ctx: {+ actor: TAddSignerMemberDTO["actor"];+ actorId: string;+ actorAuthMethod: TAddSignerMemberDTO["actorAuthMethod"];+ actorOrgId?: string;+ }+ ) =>+ permissionService.getResourcePermission({+ actor: ctx.actor,+ actorId: ctx.actorId,+ projectId,+ resourceType: ResourceType.Signer,+ resourceId: signerId,+ actorAuthMethod: ctx.actorAuthMethod,+ actorOrgId: ctx.actorOrgId+ });++ const addMember = async ({+ signerId,+ userId,+ identityId,+ groupId,+ role,+ projectId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TAddSignerMemberDTO): Promise<TSignerMember> => {+ const signer = await $loadSignerOrThrow(signerId, projectId);++ const { permission } = await $loadResourcePermission(signerId, projectId, {+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Create, ResourcePermissionSub.Member);++ if (!isBuiltInSignerRole(role)) {+ throw new BadRequestError({ message: unknownSignerRoleMessage(role) });+ }++ const orgMembership = await $assertActorPresentInOrg(actorOrgId, { userId, identityId, groupId });++ let canCreateProjectMember = false;+ try {+ const { permission: projectPermission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.CertificateManager+ });+ canCreateProjectMember = projectPermission.can(+ ProjectPermissionMemberActions.Create,+ ProjectPermissionSub.Member+ );+ } catch (err) {+ if (err instanceof ForbiddenError || err instanceof ForbiddenRequestError) {+ canCreateProjectMember = false;+ } else {+ logger.warn(+ err,+ `signer-membership: project permission lookup failed, treating actor as non-admin [projectId=${projectId}] [actorId=${actorId}]`+ );+ canCreateProjectMember = false;+ }+ }++ const membership = await membershipDAL.transaction(async (tx) => {+ const existingSignerMembershipFilter: Record<string, unknown> = {+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signerId+ };+ if (userId) existingSignerMembershipFilter.actorUserId = userId;+ else if (identityId) existingSignerMembershipFilter.actorIdentityId = identityId;+ else if (groupId) existingSignerMembershipFilter.actorGroupId = groupId;+ const existingSignerMembership = await membershipDAL.find(existingSignerMembershipFilter, { tx });+ if (existingSignerMembership.length > 0) {+ // eslint-disable-next-line no-nested-ternary+ const subjectLabel = userId ? "user" : identityId ? "identity" : "group";+ throw new BadRequestError({+ message: `This ${subjectLabel} is already a member of this Signer.`+ });+ }++ const projectMembershipFilter: Record<string, unknown> = {+ scope: AccessScope.Project,+ scopeProjectId: projectId+ };+ if (userId) projectMembershipFilter.actorUserId = userId;+ else if (identityId) projectMembershipFilter.actorIdentityId = identityId;+ else if (groupId) projectMembershipFilter.actorGroupId = groupId;+ const existingProjectMembership = await membershipDAL.find(projectMembershipFilter, { tx });++ if (existingProjectMembership.length === 0) {+ if (!canCreateProjectMember) {+ throw new ForbiddenRequestError({ message: "You don't have access to perform this action." });+ }+ const projectMembership = await membershipDAL.create(+ {+ scope: AccessScope.Project,+ scopeOrgId: orgMembership.scopeOrgId,+ scopeProjectId: projectId,+ actorUserId: userId ?? null,+ actorIdentityId: identityId ?? null,+ actorGroupId: groupId ?? null,+ isActive: true+ },+ tx+ );+ await membershipRoleDAL.create({ membershipId: projectMembership.id, role: ProjectMembershipRole.Member }, tx);+ }++ const newMembership = await membershipDAL.create(+ {+ scope: RESOURCE_SCOPE,+ scopeOrgId: orgMembership.scopeOrgId,+ scopeProjectId: projectId,+ actorUserId: userId ?? null,+ actorIdentityId: identityId ?? null,+ actorGroupId: groupId ?? null,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signerId,+ isActive: true+ },+ tx+ );++ const newRole = await membershipRoleDAL.create(+ {+ membershipId: newMembership.id,+ role+ },+ tx+ );++ return {+ membershipId: newMembership.id,+ signerId,+ actorUserId: newMembership.actorUserId ?? null,+ actorIdentityId: newMembership.actorIdentityId ?? null,+ actorGroupId: newMembership.actorGroupId ?? null,+ role: newRole.role,+ customRoleId: newRole.customRoleId ?? null,+ createdAt: newMembership.createdAt,+ updatedAt: newMembership.updatedAt+ };+ });++ const details = await $buildMemberDetails(membership);+ return { ...membership, signerName: signer.name, details };+ };++ const listMembers = async ({+ signerId,+ kind,+ projectId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TListSignerMembersDTO): Promise<TSignerMember[]> => {+ await $loadSignerOrThrow(signerId, projectId);++ await $loadResourcePermission(signerId, projectId, { actor, actorId, actorAuthMethod, actorOrgId });++ const memberships = await membershipDAL.find({+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signerId+ });++ const filteredMemberships = kind+ ? memberships.filter((m) => {+ if (kind === SignerMemberKind.User) return Boolean(m.actorUserId);+ if (kind === SignerMemberKind.Identity) return Boolean(m.actorIdentityId);+ return Boolean(m.actorGroupId);+ })+ : memberships;++ if (filteredMemberships.length === 0) return [];++ const roles = await membershipRoleDAL.find({+ $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 = 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([]),+ identityIds.length > 0 ? identityDAL.find({ $in: { id: identityIds } }) : Promise.resolve([]),+ groupIds.length > 0 ? groupDAL.find({ $in: { id: groupIds } }) : Promise.resolve([])+ ]);++ const userById = new Map(users.map((u) => [u.id, u]));+ const identityById = new Map(identities.map((i) => [i.id, i]));+ const groupById = new Map(groups.map((g) => [g.id, g]));++ return filteredMemberships.map((m) => {+ const r = rolesByMembership.get(m.id);++ let details: TSignerMember["details"] = null;+ if (m.actorUserId) {+ const u = userById.get(m.actorUserId);+ if (u) {+ const fullName = [u.firstName, u.lastName].filter((p): p is string => Boolean(p?.trim())).join(" ") || null;+ details = {+ name: fullName,+ email: u.email ?? null,+ username: u.username ?? null+ };+ }+ } else if (m.actorIdentityId) {+ const i = identityById.get(m.actorIdentityId);+ if (i) {+ details = { name: i.name, authMethod: i.authMethod ?? null };+ }+ } else if (m.actorGroupId) {+ const g = groupById.get(m.actorGroupId);+ if (g) {+ details = { name: g.name, slug: g.slug };+ }+ }++ return {+ membershipId: m.id,+ signerId,+ actorUserId: m.actorUserId ?? null,+ actorIdentityId: m.actorIdentityId ?? null,+ actorGroupId: m.actorGroupId ?? null,+ role: r?.role ?? "",+ customRoleId: r?.customRoleId ?? null,+ createdAt: m.createdAt,+ updatedAt: m.updatedAt,+ details+ };+ });+ };++ const listEffectiveMembers = async ({+ signerId,+ kind,+ projectId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TListEffectiveSignerMembersDTO): Promise<TEffectiveSignerMember[]> => {+ await $loadSignerOrThrow(signerId, projectId);+ await $loadResourcePermission(signerId, projectId, { actor, actorId, actorAuthMethod, actorOrgId });++ const allMemberships = await membershipDAL.find({+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signerId+ });+ if (allMemberships.length === 0) return [];++ const roles = await membershipRoleDAL.find({ $in: { membershipId: allMemberships.map((m) => m.id) } });+ const roleByMembership = new Map(roles.map((r) => [r.membershipId, r.role]));++ type EffectiveEntry = { role: string; isDirect: boolean; viaGroupIds: Set<string> };+ const idToEntry = new Map<string, EffectiveEntry>();++ for (const m of allMemberships) {+ const directActorId = kind === "user" ? m.actorUserId : m.actorIdentityId;+ const role = directActorId ? (roleByMembership.get(m.id) ?? "") : "";+ if (directActorId && role) {+ idToEntry.set(directActorId, { role, isDirect: true, viaGroupIds: new Set() });+ }+ }++ const groupMemberships = allMemberships.filter((m) => Boolean(m.actorGroupId));+ const groupIds = groupMemberships.map((m) => m.actorGroupId as string);+ if (groupIds.length > 0) {+ const expansions =+ kind === "user"+ ? await userGroupMembershipDAL.find({ $in: { groupId: groupIds } })+ : await identityGroupMembershipDAL.find({ $in: { groupId: groupIds } });++ const roleByGroupId = new Map<string, string>();+ for (const gm of groupMemberships) {+ const r = roleByMembership.get(gm.id);+ if (r) roleByGroupId.set(gm.actorGroupId as string, r);+ }++ for (const exp of expansions) {+ const memberId = "userId" in exp ? exp.userId : exp.identityId;+ const { groupId } = exp;+ const groupRole = roleByGroupId.get(groupId);+ if (groupRole) {+ const existing = idToEntry.get(memberId);+ if (existing) {+ existing.role = pickHigherRole(existing.role, groupRole);+ existing.viaGroupIds.add(groupId);+ } else {+ idToEntry.set(memberId, { role: groupRole, isDirect: false, viaGroupIds: new Set([groupId]) });+ }+ }+ }+ }++ const ids = Array.from(idToEntry.keys());+ if (ids.length === 0) return [];++ if (kind === "user") {+ const users = await userDAL.find({ $in: { id: ids } });+ return users+ .map((u): TEffectiveSignerMember | null => {+ const entry = idToEntry.get(u.id);+ if (!entry) return null;+ const fullName = [u.firstName, u.lastName].filter((p): p is string => Boolean(p?.trim())).join(" ") || null;+ return {+ actorUserId: u.id,+ actorIdentityId: null,+ role: entry.role,+ viaGroupIds: Array.from(entry.viaGroupIds),+ isDirect: entry.isDirect,+ details: { name: fullName, email: u.email ?? null, username: u.username ?? null }+ };+ })+ .filter((r): r is TEffectiveSignerMember => r !== null);+ }++ const identities = await identityDAL.find({ $in: { id: ids } });+ return identities+ .map((i): TEffectiveSignerMember | null => {+ const entry = idToEntry.get(i.id);+ if (!entry) return null;+ return {+ actorUserId: null,+ actorIdentityId: i.id,+ role: entry.role,+ viaGroupIds: Array.from(entry.viaGroupIds),+ isDirect: entry.isDirect,+ details: { name: i.name, authMethod: i.authMethod ?? null }+ };+ })+ .filter((r): r is TEffectiveSignerMember => r !== null);+ };++ const $findMembershipByMember = async (+ signerId: string,+ projectId: string,+ kind: TSignerMemberKind,+ memberId: string+ ) => {+ const where: Record<string, unknown> = {+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signerId+ };+ if (kind === SignerMemberKind.User) where.actorUserId = memberId;+ else if (kind === SignerMemberKind.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 signer membership found for ${kind} '${memberId}' on signer '${signerId}'.`+ });+ }+ return membership;+ };++ const updateMemberRole = async ({+ signerId,+ kind,+ memberId,+ role,+ projectId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TUpdateSignerMemberRoleDTO): Promise<TSignerMember> => {+ const signer = await $loadSignerOrThrow(signerId, projectId);++ const { permission } = await $loadResourcePermission(signerId, projectId, {+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Edit, ResourcePermissionSub.Member);++ if (!isBuiltInSignerRole(role)) {+ throw new BadRequestError({ message: unknownSignerRoleMessage(role) });+ }++ const membership = await $findMembershipByMember(signerId, projectId, kind, memberId);++ const updated = await membershipDAL.transaction(async (tx) => {+ const updatedRoles = await membershipRoleDAL.update(+ { membershipId: membership.id },+ { role, customRoleId: null },+ tx+ );+ const r = updatedRoles[0];++ if (role === ApplicationMembershipRole.Auditor && kind !== SignerMemberKind.Identity) {+ await approvalPolicyDAL.deleteStepApproversBySubject(+ {+ projectId,+ scopeType: ApprovalPolicyScope.Signer,+ scopeId: signerId,+ userId: kind === SignerMemberKind.User ? (membership.actorUserId ?? undefined) : undefined,+ groupId: kind === SignerMemberKind.Group ? (membership.actorGroupId ?? undefined) : undefined+ },+ tx+ );+ }++ return {+ membershipId: membership.id,+ signerId,+ actorUserId: membership.actorUserId ?? null,+ actorIdentityId: membership.actorIdentityId ?? null,+ actorGroupId: membership.actorGroupId ?? null,+ role: r.role,+ customRoleId: r.customRoleId ?? null,+ createdAt: membership.createdAt,+ updatedAt: membership.updatedAt+ };+ });++ const details = await $buildMemberDetails(updated);+ return { ...updated, signerName: signer.name, details };+ };++ const removeMember = async ({+ signerId,+ kind,+ memberId,+ projectId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TRemoveSignerMemberDTO): Promise<{+ membershipId: string;+ signerId: string;+ signerName: string;+ actorUserId?: string | null;+ actorIdentityId?: string | null;+ actorGroupId?: string | null;+ details?: TSignerMember["details"];+ }> => {+ const signer = await $loadSignerOrThrow(signerId, projectId);++ const { permission } = await $loadResourcePermission(signerId, projectId, {+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Delete, ResourcePermissionSub.Member);++ const membership = await $findMembershipByMember(signerId, projectId, kind, memberId);+ const details = await $buildMemberDetails(membership);++ await membershipDAL.transaction(async (tx) => {+ if (kind !== SignerMemberKind.Identity) {+ await approvalPolicyDAL.deleteStepApproversBySubject(+ {+ projectId,+ scopeType: ApprovalPolicyScope.Signer,+ scopeId: signerId,+ userId: kind === SignerMemberKind.User ? (membership.actorUserId ?? undefined) : undefined,+ groupId: kind === SignerMemberKind.Group ? (membership.actorGroupId ?? undefined) : undefined+ },+ tx+ );+ }+ await membershipRoleDAL.delete({ membershipId: membership.id }, tx);+ await membershipDAL.deleteById(membership.id, tx);+ });++ return {+ membershipId: membership.id,+ signerId,+ signerName: signer.name,+ actorUserId: membership.actorUserId ?? null,+ actorIdentityId: membership.actorIdentityId ?? null,+ actorGroupId: membership.actorGroupId ?? null,+ details+ };+ };++ const addUserMembers = async ({+ signerId,+ projectId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId,+ userIds,+ emails,+ role+ }: TAddSignerUserMembersDTO): Promise<{+ memberships: TSignerMember[];+ skipped: string[];+ unresolved: string[];+ }> => {+ if (!isBuiltInSignerRole(role)) {+ throw new BadRequestError({ message: unknownSignerRoleMessage(role) });+ }++ await $loadSignerOrThrow(signerId, projectId);++ const { permission } = await $loadResourcePermission(signerId, projectId, {+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Create, ResourcePermissionSub.Member);++ const usersByEmail = emails.length ? await userDAL.find({ $in: { username: emails } }) : [];+ const userByEmail = new Map<string, (typeof usersByEmail)[number]>();+ for (const u of usersByEmail) userByEmail.set(u.username, u);+ const unresolved = emails.filter((e) => !userByEmail.has(e));++ const existing = await membershipDAL.find({+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signerId+ });+ const alreadyAttached = new Set<string>(existing.map((m) => m.actorUserId).filter((v): v is string => Boolean(v)));++ const targets: { userId: string; label: string }[] = [];+ const seen = new Set<string>();+ userIds.forEach((id) => {+ if (!seen.has(id)) {+ seen.add(id);+ targets.push({ userId: id, label: id });+ }+ });+ emails.forEach((email) => {+ const user = userByEmail.get(email);+ if (user && !seen.has(user.id)) {+ seen.add(user.id);+ targets.push({ userId: user.id, label: email });+ }+ });++ const memberships: TSignerMember[] = [];+ const skipped: string[] = [];+ for (const t of targets) {+ if (alreadyAttached.has(t.userId)) {+ skipped.push(t.label);+ } else {+ // eslint-disable-next-line no-await-in-loop+ const m = await addMember({+ signerId,+ userId: t.userId,+ role,+ projectId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ });+ memberships.push(m);+ alreadyAttached.add(t.userId);+ }+ }++ return { memberships, skipped, unresolved };+ };++ const listSignersForActor = async ({+ projectId,+ actorKind,+ actorId+ }: {+ projectId: string;+ actorKind: SignerMemberKind;+ actorId: string;+ }): Promise<Array<{ id: string; name: string }>> => {+ const memberships =+ actorKind === SignerMemberKind.Group+ ? await membershipDAL.findResourceMembershipsForGroup({+ projectId,+ resourceType: ResourceType.Signer,+ groupId: actorId+ })+ : await membershipDAL.findResourceMembershipsForActor({+ projectId,+ resourceType: ResourceType.Signer,+ actorType: actorKind === SignerMemberKind.User ? ActorType.USER : ActorType.IDENTITY,+ actorId+ });++ if (!memberships.length) return [];++ const signerIds = Array.from(+ new Set(memberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id)))+ );+ if (!signerIds.length) return [];++ const signers = await signerDAL.find({ $in: { id: signerIds } });+ return signers.map((s) => ({ id: s.id, name: s.name }));+ };++ const removeActorFromSignerMemberships = async (+ {+ projectId,+ actorKind,+ actorId+ }: {+ projectId: string;+ actorKind: SignerMemberKind;+ actorId: string;+ },+ externalTx?: Knex+ ): Promise<{+ signers: Array<{ id: string; name: string }>;+ approvalPolicies: Array<{ id: string; name: string }>;+ }> => {+ const memberships =+ actorKind === SignerMemberKind.Group+ ? await membershipDAL.findResourceMembershipsForGroup({+ projectId,+ resourceType: ResourceType.Signer,+ groupId: actorId+ })+ : await membershipDAL.findResourceMembershipsForActor({+ projectId,+ resourceType: ResourceType.Signer,+ actorType: actorKind === SignerMemberKind.User ? ActorType.USER : ActorType.IDENTITY,+ actorId+ });++ const directMemberships =+ actorKind === SignerMemberKind.Group+ ? memberships+ : memberships.filter((m) =>+ actorKind === SignerMemberKind.User ? m.actorUserId === actorId : m.actorIdentityId === actorId+ );++ const signerIds = Array.from(+ new Set(directMemberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id)))+ );+ const signers = signerIds.length ? await signerDAL.find({ $in: { id: signerIds } }) : [];+ const signersTouched = signers.map((s) => ({ id: s.id, name: s.name }));++ let approvalPoliciesTouched: Array<{ id: string; name: string }> = [];++ const performCleanup = async (tx: Knex) => {+ if (actorKind !== SignerMemberKind.Identity && signerIds.length > 0) {+ for (const signerId of signerIds) {+ // eslint-disable-next-line no-await-in-loop+ const affected = await approvalPolicyDAL.deleteStepApproversBySubject(+ {+ projectId,+ scopeType: ApprovalPolicyScope.Signer,+ scopeId: signerId,+ userId: actorKind === SignerMemberKind.User ? actorId : undefined,+ groupId: actorKind === SignerMemberKind.Group ? actorId : undefined+ },+ tx+ );+ approvalPoliciesTouched = approvalPoliciesTouched.concat(affected);+ }+ const seen = new Set<string>();+ approvalPoliciesTouched = approvalPoliciesTouched.filter((p) => {+ if (seen.has(p.id)) return false;+ seen.add(p.id);+ return true;+ });+ }++ if (directMemberships.length > 0) {+ const membershipIds = directMemberships.map((m) => m.id);+ await membershipRoleDAL.delete({ $in: { membershipId: membershipIds } }, tx);+ await membershipDAL.delete({ $in: { id: membershipIds } }, tx);+ }+ };++ if (externalTx) {+ await performCleanup(externalTx);+ } else {+ await membershipDAL.transaction(performCleanup);+ }++ return { signers: signersTouched, approvalPolicies: approvalPoliciesTouched };+ };++ const resolveMembership = async ({+ signerId,+ membershipId,+ projectId+ }: {+ signerId: string;+ membershipId: string;+ projectId: string;+ }): Promise<{ kind: TSignerMemberKind; memberId: string }> => {+ const matches = await membershipDAL.find({+ id: membershipId,+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signerId+ });+ const membership = matches[0];+ if (!membership) {+ throw new NotFoundError({+ message: `No signer membership '${membershipId}' on signer '${signerId}'.`+ });+ }+ if (membership.actorUserId) {+ return { kind: SignerMemberKind.User, memberId: membership.actorUserId };+ }+ if (membership.actorIdentityId) {+ return { kind: SignerMemberKind.Identity, memberId: membership.actorIdentityId };+ }+ if (membership.actorGroupId) {+ return { kind: SignerMemberKind.Group, memberId: membership.actorGroupId };+ }+ throw new BadRequestError({+ message: `Membership '${membershipId}' has no actor recorded; data is inconsistent.`+ });+ };++ return {+ addMember,+ addUserMembers,+ listMembers,+ listEffectiveMembers,+ updateMemberRole,+ removeMember,+ listSignersForActor,+ removeActorFromSignerMemberships,+ resolveMembership+ };+};diff --git a/backend/src/services/signer-membership/signer-membership-types.ts b/backend/src/services/signer-membership/signer-membership-types.tsnew file mode 100644index 0000000000..008cbd3083--- /dev/null+++ b/backend/src/services/signer-membership/signer-membership-types.ts@@ -0,0 +1,85 @@+import { TProjectPermission } from "@app/lib/types";++type TActorPermission = Omit<TProjectPermission, "projectId"> & { projectId: string };++export type TSignerMember = {+ membershipId: string;+ signerId: string;+ signerName?: string;+ actorUserId?: string | null;+ actorIdentityId?: string | null;+ actorGroupId?: string | null;+ role: string;+ customRoleId?: string | null;+ createdAt: Date;+ updatedAt: Date;+ details?: {+ name: string | null;+ email?: string | null;+ username?: string | null;+ authMethod?: string | null;+ slug?: string | null;+ } | null;+};++export type TAddSignerMemberDTO = {+ signerId: string;+ userId?: string;+ identityId?: string;+ groupId?: string;+ role: string;+} & TActorPermission;++export enum SignerMemberKind {+ User = "user",+ Identity = "identity",+ Group = "group"+}++export type TSignerMemberKind = `${SignerMemberKind}`;++export type TListSignerMembersDTO = {+ signerId: string;+ kind?: TSignerMemberKind;+} & TActorPermission;++export type TEffectiveSignerMemberKind = "user" | "identity";++export type TListEffectiveSignerMembersDTO = {+ signerId: string;+ kind: TEffectiveSignerMemberKind;+} & TActorPermission;++export type TEffectiveSignerMember = {+ actorUserId: string | null;+ actorIdentityId: string | null;+ role: string;+ viaGroupIds: string[];+ isDirect: boolean;+ details: {+ name: string | null;+ email?: string | null;+ username?: string | null;+ authMethod?: string | null;+ } | null;+};++export type TUpdateSignerMemberRoleDTO = {+ signerId: string;+ kind: TSignerMemberKind;+ memberId: string;+ role: string;+} & TActorPermission;++export type TRemoveSignerMemberDTO = {+ signerId: string;+ kind: TSignerMemberKind;+ memberId: string;+} & TActorPermission;++export type TAddSignerUserMembersDTO = {+ signerId: string;+ userIds: string[];+ emails: string[];+ role: string;+} & TActorPermission;diff --git a/backend/src/services/signer/signer-auto-renewal-queue.ts b/backend/src/services/signer/signer-auto-renewal-queue.tsnew file mode 100644index 0000000000..1249d29302--- /dev/null+++ b/backend/src/services/signer/signer-auto-renewal-queue.ts@@ -0,0 +1,115 @@+/* eslint-disable no-await-in-loop, no-continue */+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";+import { logger } from "@app/lib/logger";+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";++import { TSignerDALFactory } from "./signer-dal";+import { SignerStatus } from "./signer-enums";+import { TSignerServiceFactory } from "./signer-service";++type TSignerAutoRenewalQueueFactoryDep = {+ queueService: TQueueServiceFactory;+ cronJob: TCronJobFactory;+ signerDAL: Pick<TSignerDALFactory, "find" | "findByIdWithCertificate">;+ signerService: Pick<TSignerServiceFactory, "autoRenewCertificate">;+};++export type TSignerAutoRenewalQueueFactory = ReturnType<typeof signerAutoRenewalQueueFactory>;++const MS_PER_DAY = 24 * 60 * 60 * 1000;++export const signerAutoRenewalQueueFactory = ({+ queueService,+ cronJob,+ signerDAL,+ signerService+}: TSignerAutoRenewalQueueFactoryDep) => {+ queueService.start(QueueName.SignerAutoRenewal, async (job) => {+ if (job.name !== QueueJobs.SignerDailyAutoRenewal) return;++ const now = Date.now();+ const candidates = await signerDAL.find({ status: SignerStatus.Active });++ let scanned = 0;+ let needsRenewal = 0;+ let renewed = 0;+ let unrenewable = 0;+ let failed = 0;++ for (const signer of candidates) {+ scanned += 1;++ if (!signer.renewBeforeDays || signer.renewBeforeDays < 1) continue;++ if (!signer.caId) {+ unrenewable += 1;+ logger.warn(+ { signerId: signer.id, signerName: signer.name },+ `signer auto-renewal: skipping signer '${signer.name}' [signerId=${signer.id}] — no CA configured for renewal (likely migrated from an imported certificate)`+ );+ continue;+ }++ const withCert = await signerDAL.findByIdWithCertificate(signer.id);+ if (!withCert?.certificateNotAfter) {+ needsRenewal += 1;+ try {+ await signerService.autoRenewCertificate(signer.id);+ renewed += 1;+ } catch (err) {+ failed += 1;+ logger.error(err, `signer auto-renewal: renewal failed for signer '${signer.name}' [signerId=${signer.id}]`);+ }+ continue;+ }++ const msUntilExpiry = new Date(withCert.certificateNotAfter).getTime() - now;+ const daysUntilExpiry = msUntilExpiry / MS_PER_DAY;+ const isDue = daysUntilExpiry <= signer.renewBeforeDays;+ if (!isDue) continue;++ needsRenewal += 1;+ logger.info(+ {+ signerId: signer.id,+ signerName: signer.name,+ caId: signer.caId,+ daysUntilExpiry: Math.round(daysUntilExpiry * 100) / 100+ },+ `signer auto-renewal: renewing '${signer.name}' [signerId=${signer.id}] [caId=${signer.caId}]`+ );++ try {+ await signerService.autoRenewCertificate(signer.id);+ renewed += 1;+ } catch (err) {+ failed += 1;+ logger.error(err, `signer auto-renewal: renewal failed for signer '${signer.name}' [signerId=${signer.id}]`);+ }+ }++ logger.info(+ { scanned, needsRenewal, renewed, unrenewable, failed, elapsedMs: Date.now() - now },+ `signer auto-renewal cron completed [scanned=${scanned}] [needsRenewal=${needsRenewal}] [renewed=${renewed}] [unrenewable=${unrenewable}] [failed=${failed}]`+ );+ });++ queueService.listen(QueueName.SignerAutoRenewal, "failed", (_, err) => {+ logger.error(err, `${QueueName.SignerAutoRenewal}: job failed`);+ });++ const start = () => {+ cronJob.register({+ name: CronJobName.SignerDailyAutoRenewal,+ pattern: "10 0 * * *",+ runHashTtlS: 3 * 24 * 60 * 60,+ handler: async () => {+ await queueService.queue(QueueName.SignerAutoRenewal, QueueJobs.SignerDailyAutoRenewal, undefined as never, {+ jobId: CronJobName.SignerDailyAutoRenewal+ });+ }+ });+ };++ return { start };+};diff --git a/backend/src/services/signer/signer-dal.ts b/backend/src/services/signer/signer-dal.tsindex 558cd5a7a8..c03568a7c4 100644--- a/backend/src/services/signer/signer-dal.ts+++ b/backend/src/services/signer/signer-dal.ts@@ -21,6 +21,7 @@ export type TSignerWithCertificateSummary = TPkiSigners & {certificateCommonName: string | null;certificateSerialNumber: string | null;certificateNotAfter: Date | null;+ certificateStatus: string | null;approvalPolicyName: string | null;};@@ -63,11 +64,13 @@ export const signerDALFactory = (db: TDbClient) => {{offset = 0,limit = 25,- search+ search,+ signerIds}: {offset?: number;limit?: number;search?: string;+ signerIds?: string[];},tx?: Knex) => {@@ -84,10 +87,15 @@ export const signerDALFactory = (db: TDbClient) => {db.ref("commonName").withSchema(TableName.Certificate).as("certificateCommonName"),db.ref("serialNumber").withSchema(TableName.Certificate).as("certificateSerialNumber"),db.ref("notAfter").withSchema(TableName.Certificate).as("certificateNotAfter"),+ db.ref("status").withSchema(TableName.Certificate).as("certificateStatus"),db.ref("name").withSchema(TableName.ApprovalPolicies).as("approvalPolicyName")).where(`${TableName.PkiSigners}.projectId`, projectId);+ if (signerIds) {+ query = query.whereIn(`${TableName.PkiSigners}.id`, signerIds);+ }+if (search) {const sanitizedSearch = `%${sanitizeSqlLikeString(search)}%`;query = query.where((qb) => {@@ -106,13 +114,17 @@ export const signerDALFactory = (db: TDbClient) => {}};- const countByProjectId = async (projectId: string, search?: string, tx?: Knex) => {+ const countByProjectId = async (projectId: string, search?: string, signerIds?: string[], tx?: Knex) => {try {let query: Knex.QueryBuilder = (tx || db.replicaNode())(TableName.PkiSigners).where(`${TableName.PkiSigners}.projectId`,projectId);+ if (signerIds) {+ query = query.whereIn(`${TableName.PkiSigners}.id`, signerIds);+ }+if (search) {const sanitizedSearch = `%${sanitizeSqlLikeString(search)}%`;query = querydiff --git a/backend/src/services/signer/signer-enums.ts b/backend/src/services/signer/signer-enums.tsindex ca7da695ff..629e70e2fc 100644--- a/backend/src/services/signer/signer-enums.ts+++ b/backend/src/services/signer/signer-enums.ts@@ -1,6 +1,9 @@export enum SignerStatus {+ Pending = "pending",Active = "active",- Disabled = "disabled"+ Failed = "failed",+ Disabled = "disabled",+ Expired = "expired"}export enum SigningOperationStatus {@@ -8,3 +11,9 @@ export enum SigningOperationStatus {Failed = "failed",Denied = "denied"}++export enum SignerIssuanceJobStatus {+ Pending = "pending",+ Completed = "completed",+ Failed = "failed"+}diff --git a/backend/src/services/signer/signer-issuance-errors.ts b/backend/src/services/signer/signer-issuance-errors.tsnew file mode 100644index 0000000000..74210c9032--- /dev/null+++ b/backend/src/services/signer/signer-issuance-errors.ts@@ -0,0 +1,154 @@+import { AxiosError } from "axios";++import { AcmeError } from "@app/ee/services/pki-acme/pki-acme-errors";+import {+ BadRequestError,+ CryptographyError,+ DatabaseError,+ ForbiddenRequestError,+ InternalServerError,+ NotFoundError,+ RateLimitError+} from "@app/lib/errors";++const MAX_REASON_LEN = 1000;++const KNOWN_USELESS_DEFAULTS = new Set([+ "Failed to execute db ops",+ "Something went wrong",+ "Unknown error",+ "Error",+ "Request failed with status code 400",+ "Request failed with status code 500"+]);++const isEmptyish = (s: string | undefined | null): boolean => {+ if (!s) return true;+ const trimmed = s.trim();+ if (!trimmed) return true;+ if (KNOWN_USELESS_DEFAULTS.has(trimmed)) return true;+ return false;+};++const truncate = (s: string): string => {+ const normalized = s.replace(/\s+/g, " ").trim();+ if (normalized.length <= MAX_REASON_LEN) return normalized;+ return `${normalized.slice(0, MAX_REASON_LEN - 1)}…`;+};++type TAxiosErrorBody = {+ type?: string;+ detail?: string;+ errors?: { code?: string | number; message?: string; detail?: string }[];+ error?: { message?: string; detail?: string } | string;+ message?: string;+};++const formatAxiosError = (err: AxiosError): string | null => {+ const status = err.response?.status;+ const statusText = err.response?.statusText;+ const body = err.response?.data as TAxiosErrorBody | string | undefined;++ let detail: string | undefined;+ if (typeof body === "string") {+ detail = body;+ } else if (body) {+ detail =+ body.detail ??+ body.errors?.[0]?.message ??+ body.errors?.[0]?.detail ??+ (typeof body.error === "string" ? body.error : (body.error?.detail ?? body.error?.message)) ??+ body.message;+ if (!detail && body.type) detail = body.type;+ }++ if (!detail && !isEmptyish(err.message)) detail = err.message;++ const prefix = status ? `HTTP ${status}${statusText ? ` ${statusText}` : ""}` : null;+ if (detail && prefix) return `${prefix} — ${detail}`;+ if (detail) return detail;+ if (prefix) return prefix;+ return null;+};++const formatAcmeError = (err: AcmeError): string => {+ const subproblems = err.subproblems?.map((sp) => sp.detail || sp.type).filter((s): s is string => Boolean(s));+ const base = !isEmptyish(err.message) ? err.message : err.type || err.name;+ if (subproblems && subproblems.length > 0) {+ return `${base}: ${subproblems.join("; ")}`;+ }+ return base;+};++const collectMessageChain = (err: unknown): string | null => {+ const seen = new Set<unknown>();+ const parts: string[] = [];+ let current: unknown = err;+ while (current && !seen.has(current)) {+ seen.add(current);+ if (current instanceof AxiosError) {+ const formatted = formatAxiosError(current);+ if (formatted) parts.push(formatted);+ } else if (current instanceof AcmeError) {+ parts.push(formatAcmeError(current));+ } else if (current instanceof Error) {+ if (!isEmptyish(current.message)) {+ parts.push(current.message);+ } else if (!isEmptyish(current.name) && current.name !== "Error") {+ parts.push(current.name);+ }+ } else {+ const stringified = String(current);+ if (!isEmptyish(stringified)) parts.push(stringified);+ }+ current = (current as { cause?: unknown } | null | undefined)?.cause;+ }++ if (parts.length === 0) return null;+ const deduped: string[] = [];+ for (const p of parts) {+ if (!deduped.includes(p)) deduped.push(p);+ }+ return deduped.join(" — ");+};++export const formatSignerIssuanceErrorReason = (err: unknown, fallbackContext?: string): string => {+ const fallback = fallbackContext+ ? `${fallbackContext}. Check audit logs for the full error.`+ : "Issuance failed. Check audit logs for the full error.";++ if (err == null) return truncate(fallback);++ if (+ err instanceof BadRequestError ||+ err instanceof NotFoundError ||+ err instanceof ForbiddenRequestError ||+ err instanceof RateLimitError ||+ err instanceof CryptographyError+ ) {+ return truncate(err.message);+ }++ if (err instanceof DatabaseError) {+ const cause = collectMessageChain((err as DatabaseError & { error?: unknown }).error);+ if (cause) {+ return truncate(`Internal database error: ${cause}`);+ }+ return truncate(+ "An internal database error occurred while issuing the certificate. Retry the operation; if it persists, contact support."+ );+ }+ if (err instanceof InternalServerError) {+ const chain = collectMessageChain(err);+ if (chain) return truncate(`Internal error: ${chain}`);+ return truncate("An internal error occurred while issuing the certificate. Check audit logs for details.");+ }++ const chain = collectMessageChain(err);+ if (chain) return truncate(chain);++ if (err instanceof Error && !isEmptyish(err.name) && err.name !== "Error") {+ return truncate(`${fallback} (${err.name})`);+ }+ return truncate(fallback);+};diff --git a/backend/src/services/signer/signer-issuance-fns.ts b/backend/src/services/signer/signer-issuance-fns.tsnew file mode 100644index 0000000000..c949e305b8--- /dev/null+++ b/backend/src/services/signer/signer-issuance-fns.ts@@ -0,0 +1,178 @@+/* eslint-disable @typescript-eslint/no-unsafe-argument */+import * as x509 from "@peculiar/x509";+import { Knex } from "knex";++import { crypto } from "@app/lib/crypto/cryptography";+import { isPqcAlgorithm } from "@app/lib/crypto/pqc";+import { BadRequestError } from "@app/lib/errors";+import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";+import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";+import {+ CertExtendedKeyUsage,+ CertExtendedKeyUsageOIDToName,+ CertKeyAlgorithm+} from "@app/services/certificate/certificate-types";+import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";+import { CaStatus } from "@app/services/certificate-authority/certificate-authority-enums";+import { keyAlgorithmToAlgCfg } from "@app/services/certificate-authority/certificate-authority-fns";+import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { TProjectDALFactory } from "@app/services/project/project-dal";+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";++type TIssueSignerCertificateDeps = {+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;+ internalCertificateAuthorityService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa">;+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;+ kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "encryptWithKmsKey" | "generateKmsKey">;+};++type TVerifyCodeSigningEkuDeps = {+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;+ kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;+};++export const verifyCodeSigningEku = async (+ { certificateBodyDAL, projectDAL, kmsService }: TVerifyCodeSigningEkuDeps,+ { certificateId, projectId }: { certificateId: string; projectId: string }+): Promise<void> => {+ const certBody = await certificateBodyDAL.findOne({ certId: certificateId });+ if (!certBody?.encryptedCertificate) {+ throw new BadRequestError({+ message: "Cannot verify code-signing usage: certificate body is missing."+ });+ }++ const kmsId = await getProjectKmsCertificateKeyId({ projectId, projectDAL, kmsService });+ const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId });+ const decrypted = await kmsDecryptor({ cipherTextBlob: certBody.encryptedCertificate });+ const cert = new x509.X509Certificate(decrypted);++ const ekuExtension = cert.getExtension("2.5.29.37") as x509.ExtendedKeyUsageExtension | undefined;+ const hasCodeSigningEku =+ ekuExtension?.usages?.some(+ (oid) => CertExtendedKeyUsageOIDToName[oid as string] === CertExtendedKeyUsage.CODE_SIGNING+ ) ?? false;++ if (!hasCodeSigningEku) {+ throw new BadRequestError({+ message: "The issued certificate does not have the codeSigning extended key usage set."+ });+ }+};++type TIssueSignerCertificateInput = {+ caId: string;+ projectId: string;+ commonName: string;+ certificateTtlDays: number;+ keyAlgorithm?: CertKeyAlgorithm;+ tx?: Knex;+};++export const issueSignerCertificate = async (+ {+ certificateAuthorityDAL,+ internalCertificateAuthorityService,+ certificateBodyDAL,+ certificateSecretDAL,+ projectDAL,+ kmsService+ }: TIssueSignerCertificateDeps,+ { caId, projectId, commonName, certificateTtlDays, keyAlgorithm, tx }: TIssueSignerCertificateInput+): Promise<{ certificateId: string }> => {+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId, tx);+ if (!ca || ca.projectId !== projectId) {+ throw new BadRequestError({+ message: `Certificate authority '${caId}' is not in this project.`+ });+ }+ if (ca.status !== CaStatus.ACTIVE) {+ throw new BadRequestError({ message: "The selected certificate authority is not active." });+ }+ if (!ca.internalCa?.id) {+ throw new BadRequestError({+ message:+ "Issuing a signer certificate directly from an external Certificate Authority is not yet supported. " ++ "Issue a code-signing certificate through Certificate Manager first and attach it to the signer by ID."+ });+ }++ const caKeyAlgorithm = ca.internalCa.keyAlgorithm as CertKeyAlgorithm;+ if (isPqcAlgorithm(caKeyAlgorithm)) {+ throw new BadRequestError({+ message: "PQC certificate authorities cannot back code signers in this version."+ });+ }++ const leafKeyAlgorithm = keyAlgorithm ?? CertKeyAlgorithm.RSA_2048;+ if (isPqcAlgorithm(leafKeyAlgorithm)) {+ throw new BadRequestError({+ message: "PQC leaf key algorithms are not supported for code signers in this version."+ });+ }+ const alg = keyAlgorithmToAlgCfg(leafKeyAlgorithm);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const leafKeys = await crypto.nativeCrypto.subtle.generateKey(alg as any, true, ["sign", "verify"]);++ const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({+ name: `CN=${commonName}`,+ keys: leafKeys,+ signingAlgorithm: alg,+ // eslint-disable-next-line no-bitwise+ extensions: [+ new x509.KeyUsagesExtension(+ // eslint-disable-next-line no-bitwise+ x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyEncipherment+ )+ ]+ });+ const csrPem = csrObj.toString("pem");++ const signResult = await internalCertificateAuthorityService.signCertFromCa({+ isInternal: true,+ isFromProfile: true,+ caId: ca.id,+ csr: csrPem,+ commonName,+ ttl: `${certificateTtlDays}d`,+ extendedKeyUsages: [CertExtendedKeyUsage.CODE_SIGNING],+ tx+ });++ if (!signResult.certificateId) {+ throw new BadRequestError({ message: "Certificate authority did not return a certificate id." });+ }++ await verifyCodeSigningEku(+ { certificateBodyDAL, projectDAL, kmsService },+ { certificateId: signResult.certificateId, projectId: ca.projectId }+ );++ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({+ projectId: ca.projectId,+ projectDAL,+ kmsService+ });++ const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKmsId });++ const skLeafObj = crypto.nativeCrypto.KeyObject.from(leafKeys.privateKey);+ const skLeafPem = skLeafObj.export({ format: "pem", type: "pkcs8" }) as string;+ const { cipherTextBlob: encryptedPrivateKey } = await kmsEncryptor({+ plainText: Buffer.from(skLeafPem)+ });++ await certificateSecretDAL.create(+ {+ certId: signResult.certificateId,+ encryptedPrivateKey+ },+ tx+ );++ return { certificateId: signResult.certificateId };+};diff --git a/backend/src/services/signer/signer-issuance-job-dal.ts b/backend/src/services/signer/signer-issuance-job-dal.tsnew file mode 100644index 0000000000..7034c698d3--- /dev/null+++ b/backend/src/services/signer/signer-issuance-job-dal.ts@@ -0,0 +1,66 @@+/* eslint-disable @typescript-eslint/no-unsafe-assignment */+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName, TPkiSignerIssuanceJobs } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify } from "@app/lib/knex";++import { SignerIssuanceJobStatus } from "./signer-enums";++export type TSignerIssuanceJobDALFactory = ReturnType<typeof signerIssuanceJobDALFactory>;++export const signerIssuanceJobDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.PkiSignerIssuanceJobs);++ const findDuePending = async (now: Date, limit: number, tx?: Knex): Promise<TPkiSignerIssuanceJobs[]> => {+ try {+ return (await (tx || db.replicaNode())(TableName.PkiSignerIssuanceJobs)+ .where({ status: SignerIssuanceJobStatus.Pending })+ .andWhere("nextPollAt", "<=", now)+ .orderBy("nextPollAt", "asc")+ .limit(limit)) as TPkiSignerIssuanceJobs[];+ } catch (error) {+ throw new DatabaseError({ error, name: "FindDuePendingSignerIssuanceJobs" });+ }+ };++ const cancelOpenForSigner = async (signerId: string, reason: string, tx?: Knex) => {+ try {+ await (tx || db)(TableName.PkiSignerIssuanceJobs)+ .where({ signerId, status: SignerIssuanceJobStatus.Pending })+ .update({+ status: SignerIssuanceJobStatus.Failed,+ failureReason: reason.slice(0, 1000),+ updatedAt: new Date()+ } as Record<string, unknown>);+ } catch (error) {+ throw new DatabaseError({ error, name: "CancelOpenSignerIssuanceJobs" });+ }+ };++ const claimForAttempt = async (+ jobId: string,+ expectedAttempts: number,+ nextPollAt: Date,+ lastAttemptAt: Date,+ tx?: Knex+ ): Promise<TPkiSignerIssuanceJobs | null> => {+ try {+ const [row] = await (tx || db)(TableName.PkiSignerIssuanceJobs)+ .where({ id: jobId, status: SignerIssuanceJobStatus.Pending, attempts: expectedAttempts })+ .update({+ attempts: expectedAttempts + 1,+ lastAttemptAt,+ nextPollAt,+ updatedAt: new Date()+ } as Record<string, unknown>)+ .returning("*");+ return row ?? null;+ } catch (error) {+ throw new DatabaseError({ error, name: "ClaimSignerIssuanceJobAttempt" });+ }+ };++ return { ...orm, findDuePending, cancelOpenForSigner, claimForAttempt };+};diff --git a/backend/src/services/signer/signer-issuance-service.ts b/backend/src/services/signer/signer-issuance-service.tsnew file mode 100644index 0000000000..e3d0a1e338--- /dev/null+++ b/backend/src/services/signer/signer-issuance-service.ts@@ -0,0 +1,572 @@+/* eslint-disable no-await-in-loop, @typescript-eslint/no-use-before-define, @typescript-eslint/no-unsafe-argument */+import * as x509 from "@peculiar/x509";++import { TPkiSignerIssuanceJobs } from "@app/db/schemas";+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";+import { crypto } from "@app/lib/crypto/cryptography";+import { BadRequestError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";++import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";+import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";+import { CertExtendedKeyUsage, CertKeyAlgorithm, CertKeyUsage } from "../certificate/certificate-types";+import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";+import { CaStatus, CaType } from "../certificate-authority/certificate-authority-enums";+import { keyAlgorithmToAlgCfg } from "../certificate-authority/certificate-authority-fns";+import { TCertificateIssuanceQueueFactory } from "../certificate-authority/certificate-issuance-queue";+import { TKmsServiceFactory } from "../kms/kms-service";+import { TProjectDALFactory } from "../project/project-dal";+import { getProjectKmsCertificateKeyId } from "../project/project-fns";+import { TSignerDALFactory } from "./signer-dal";+import { SignerIssuanceJobStatus, SignerStatus } from "./signer-enums";+import { formatSignerIssuanceErrorReason } from "./signer-issuance-errors";+import { verifyCodeSigningEku } from "./signer-issuance-fns";+import { TSignerIssuanceJobDALFactory } from "./signer-issuance-job-dal";++const POLL_INTERVAL_PATTERN = "*/15 * * * *"; // every 15 minutes+const POLL_BATCH = 25;+const RETRY_BACKOFF_MS = 15 * 60_000;+const PENDING_VALIDATION_POLL_INTERVAL_MS = 15 * 60_000;+const MAX_ISSUANCE_WINDOW_MS = 24 * 60 * 60 * 1000;++export type TSignerIssuanceServiceFactory = ReturnType<typeof signerIssuanceServiceFactory>;++type TSignerIssuanceServiceDeps = {+ signerIssuanceJobDAL: TSignerIssuanceJobDALFactory;+ signerDAL: Pick<TSignerDALFactory, "updateById">;+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create" | "updateById">;+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;+ kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "decryptWithKmsKey" | "generateKmsKey">;+ certificateIssuanceQueue: Pick<+ TCertificateIssuanceQueueFactory,+ "acmeFns" | "azureAdCsFns" | "awsPcaFns" | "digicertFns" | "venafiTppFns"+ >;+ cronJob: TCronJobFactory;+};++type TRequestIssuanceInput = {+ signerId: string;+ projectId: string;+ caId: string;+ commonName: string;+ certificateTtlDays: number;+ keyAlgorithm?: CertKeyAlgorithm;+};++type TExternalOrderRef =+ | { type: CaType.DIGICERT; orderId: number }+ | { type: CaType.ACME; orderUrl?: string }+ | Record<string, unknown>;++export const signerIssuanceServiceFactory = ({+ signerIssuanceJobDAL,+ signerDAL,+ certificateAuthorityDAL,+ certificateBodyDAL,+ certificateSecretDAL,+ projectDAL,+ kmsService,+ certificateIssuanceQueue,+ cronJob+}: TSignerIssuanceServiceDeps) => {+ const { acmeFns, azureAdCsFns, awsPcaFns, digicertFns, venafiTppFns } = certificateIssuanceQueue;++ const buildCsrForSigner = async (+ commonName: string,+ keyAlgorithm: CertKeyAlgorithm+ ): Promise<{ csrPem: string; privateKeyPem: string }> => {+ const alg = keyAlgorithmToAlgCfg(keyAlgorithm);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const leafKeys = await crypto.nativeCrypto.subtle.generateKey(alg as any, true, ["sign", "verify"]);+ const skLeafObj = crypto.nativeCrypto.KeyObject.from(leafKeys.privateKey);+ const privateKeyPem = skLeafObj.export({ format: "pem", type: "pkcs8" }) as string;++ const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({+ name: `CN=${commonName}`,+ keys: leafKeys,+ signingAlgorithm: alg,+ extensions: [+ new x509.KeyUsagesExtension(+ // eslint-disable-next-line no-bitwise+ x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyEncipherment+ ),+ new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage.codeSigning], true)+ ]+ });++ return { csrPem: csrObj.toString("pem"), privateKeyPem };+ };++ const encryptForProject = async (projectId: string, plain: Buffer): Promise<Buffer> => {+ const kmsId = await getProjectKmsCertificateKeyId({ projectId, projectDAL, kmsService });+ const encryptor = await kmsService.encryptWithKmsKey({ kmsId });+ const { cipherTextBlob } = await encryptor({ plainText: plain });+ return cipherTextBlob;+ };++ const decryptForProject = async (projectId: string, cipher: Buffer): Promise<Buffer> => {+ const kmsId = await getProjectKmsCertificateKeyId({ projectId, projectDAL, kmsService });+ const decryptor = await kmsService.decryptWithKmsKey({ kmsId });+ return decryptor({ cipherTextBlob: cipher });+ };++ const requestIssuance = async (input: TRequestIssuanceInput): Promise<TPkiSignerIssuanceJobs> => {+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(input.caId);+ if (!ca || ca.projectId !== input.projectId) {+ throw new BadRequestError({+ message: `Certificate authority '${input.caId}' is not in this project.`+ });+ }+ if (ca.status !== CaStatus.ACTIVE) {+ throw new BadRequestError({ message: "The selected certificate authority is not active." });+ }+ const caType = ca.externalCa?.type;+ if (!caType || caType === CaType.INTERNAL) {+ throw new BadRequestError({+ message: "Internal CAs must be issued synchronously, not through the signer issuance service."+ });+ }++ await signerIssuanceJobDAL.cancelOpenForSigner(input.signerId, "Superseded by a newer issuance request.");++ const keyAlgorithm: CertKeyAlgorithm = input.keyAlgorithm ?? CertKeyAlgorithm.RSA_2048;+ const { csrPem, privateKeyPem } = await buildCsrForSigner(input.commonName, keyAlgorithm);++ const encryptedCsr = await encryptForProject(input.projectId, Buffer.from(csrPem));+ const encryptedPrivateKey = await encryptForProject(input.projectId, Buffer.from(privateKeyPem));++ const job = await signerIssuanceJobDAL.create({+ signerId: input.signerId,+ caId: input.caId,+ caType,+ status: SignerIssuanceJobStatus.Pending,+ commonName: input.commonName,+ certificateTtlDays: input.certificateTtlDays,+ keyAlgorithm,+ encryptedCsr,+ encryptedPrivateKey,+ nextPollAt: new Date()+ });++ void (async () => {+ try {+ await processJob(job.id);+ } catch (err) {+ logger.warn(+ err,+ `signer issuance: first-attempt background failed, cron will retry [jobId=${job.id}] [signerId=${input.signerId}]`+ );+ }+ })();++ return job;+ };++ const processJob = async (jobId: string): Promise<void> => {+ const snapshot = await signerIssuanceJobDAL.findById(jobId);+ if (!snapshot) {+ logger.warn(`signer issuance: job ${jobId} not found, skipping`);+ return;+ }+ if (snapshot.status !== SignerIssuanceJobStatus.Pending) return;++ const now = new Date();++ const ageMs = now.getTime() - new Date(snapshot.createdAt).getTime();+ if (ageMs > MAX_ISSUANCE_WINDOW_MS) {+ await markJobFailedIfStillPending(+ snapshot,+ "Signer issuance was pending for more than 24 hours. The upstream Certificate Authority never finished issuing the certificate; abandoning."+ );+ return;+ }++ const job = await signerIssuanceJobDAL.claimForAttempt(+ snapshot.id,+ snapshot.attempts,+ new Date(now.getTime() + RETRY_BACKOFF_MS),+ now+ );+ if (!job) {+ logger.info(+ `signer issuance: claim missed for [jobId=${snapshot.id}] [signerId=${snapshot.signerId}] (concurrent claim or cancellation)`+ );+ return;+ }++ if (job.attempts > job.maxAttempts) {+ await markJobFailed(+ job,+ `Signer issuance exhausted after ${job.maxAttempts} attempts. Last attempt at ${now.toISOString()}.`+ );+ return;+ }++ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(job.caId);+ if (!ca || ca.status !== CaStatus.ACTIVE) {+ await markJobFailed(job, `Certificate authority is no longer available or active.`);+ return;+ }++ try {+ switch (job.caType as CaType) {+ case CaType.DIGICERT:+ await stepDigiCert(job);+ break;+ case CaType.ACME:+ await stepSyncWithCsr(job, "acme");+ break;+ case CaType.AZURE_AD_CS:+ await stepSyncWithCsr(job, "azure");+ break;+ case CaType.AWS_PCA:+ await stepSyncWithCsr(job, "aws-pca");+ break;+ case CaType.VENAFI_TPP:+ await stepSyncWithCsr(job, "venafi");+ break;+ case CaType.AWS_ACM_PUBLIC_CA:+ await markJobFailed(+ job,+ "AWS ACM Public CA does not issue code-signing certificates. Choose a different CA."+ );+ return;+ default:+ await markJobFailed(job, `CA type '${job.caType}' is not supported for signer issuance.`);+ }+ } catch (err) {+ const reason = formatSignerIssuanceErrorReason(+ err,+ "External Certificate Authority refused to issue the signer certificate"+ );+ const rows = await signerIssuanceJobDAL.update(+ { id: job.id, status: SignerIssuanceJobStatus.Pending },+ {+ nextPollAt: new Date(Date.now() + RETRY_BACKOFF_MS),+ failureReason: reason+ }+ );+ if (rows.length > 0) {+ await signerDAL.updateById(job.signerId, {+ status: SignerStatus.Pending,+ failureReason: reason+ });+ }+ logger.error(+ err,+ `signer issuance: attempt failed, will retry [jobId=${job.id}] [signerId=${job.signerId}] [attempts=${job.attempts}/${job.maxAttempts}]`+ );+ }+ };++ const markJobFailed = async (job: TPkiSignerIssuanceJobs, reason: string) => {+ await signerIssuanceJobDAL.updateById(job.id, {+ status: SignerIssuanceJobStatus.Failed,+ failureReason: reason.slice(0, 1000)+ });+ await signerDAL.updateById(job.signerId, {+ status: SignerStatus.Failed,+ failureReason: reason.slice(0, 1000)+ });+ logger.info(+ `signer issuance: job marked Failed [jobId=${job.id}] [signerId=${job.signerId}] [reason=${reason.slice(0, 200)}]`+ );+ };++ const markJobFailedIfStillPending = async (job: TPkiSignerIssuanceJobs, reason: string) => {+ const trimmed = reason.slice(0, 1000);+ const rows = await signerIssuanceJobDAL.update(+ { id: job.id, status: SignerIssuanceJobStatus.Pending },+ { status: SignerIssuanceJobStatus.Failed, failureReason: trimmed }+ );+ if (rows.length === 0) return;+ await signerDAL.updateById(job.signerId, {+ status: SignerStatus.Failed,+ failureReason: trimmed+ });+ logger.info(+ `signer issuance: job marked Failed [jobId=${job.id}] [signerId=${job.signerId}] [reason=${trimmed.slice(0, 200)}]`+ );+ };++ const attachIssuedCertToSigner = async (+ job: TPkiSignerIssuanceJobs,+ certificateId: string,+ projectId: string+ ): Promise<void> => {+ try {+ await verifyCodeSigningEku({ certificateBodyDAL, projectDAL, kmsService }, { certificateId, projectId });+ } catch (ekuErr) {+ const reason = formatSignerIssuanceErrorReason(ekuErr, "Issued certificate failed code-signing EKU verification");+ await markJobFailed(job, reason);+ return;+ }++ await signerDAL.updateById(job.signerId, {+ certificateId,+ status: SignerStatus.Active,+ failureReason: null+ });+ await signerIssuanceJobDAL.updateById(job.id, {+ status: SignerIssuanceJobStatus.Completed,+ certificateId,+ failureReason: null+ });+ logger.info(+ `signer issuance: signer attached [jobId=${job.id}] [signerId=${job.signerId}] [certificateId=${certificateId}]`+ );+ };++ const stepDigiCert = async (job: TPkiSignerIssuanceJobs) => {+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(job.caId);+ if (!ca) {+ await markJobFailed(job, "Certificate authority is no longer available.");+ return;+ }+ const { projectId } = ca;+ const existingRef = job.externalOrderRef as TExternalOrderRef | null | undefined;++ if (!existingRef || (existingRef as { type?: CaType }).type !== CaType.DIGICERT) {+ const csr = (await decryptForProject(projectId, Buffer.from(job.encryptedCsr as Buffer))).toString();++ const orderResult = await digicertFns.orderCertificateFromProfile({+ caId: job.caId,+ commonName: job.commonName,+ altNames: [],+ signatureAlgorithm: undefined,+ keyAlgorithm: job.keyAlgorithm as CertKeyAlgorithm,+ ttl: `${job.certificateTtlDays}d`,+ csr+ });++ const orderRef: TExternalOrderRef = {+ type: CaType.DIGICERT,+ orderId: orderResult.orderId+ };++ if (orderResult.immediateCertificateId) {+ const { certificateId } = await digicertFns.fetchAndAttachIssuedCertificate({+ caId: job.caId,+ certificateRequest: {+ id: `signer:${job.signerId}`,+ profileId: undefined,+ commonName: job.commonName,+ altNames: null,+ keyUsages: [CertKeyUsage.DIGITAL_SIGNATURE, CertKeyUsage.KEY_ENCIPHERMENT],+ extendedKeyUsages: [CertExtendedKeyUsage.CODE_SIGNING],+ keyAlgorithm: job.keyAlgorithm,+ signatureAlgorithm: null+ },+ digicertCertificateId: orderResult.immediateCertificateId,+ digicertOrderId: orderResult.orderId+ });++ await persistCertificatePrivateKey(certificateId, projectId, job);+ await attachIssuedCertToSigner(job, certificateId, projectId);+ return;+ }++ await signerIssuanceJobDAL.updateById(job.id, {+ externalOrderRef: orderRef,+ nextPollAt: new Date(Date.now() + PENDING_VALIDATION_POLL_INTERVAL_MS)+ });+ logger.info(+ `signer issuance: DigiCert order ${orderResult.orderId} placed, awaiting validation [jobId=${job.id}]`+ );+ return;+ }++ const ref = existingRef as { type: CaType.DIGICERT; orderId: number };++ const poll = await digicertFns.pollOrderForCertificate({ caId: job.caId, orderId: ref.orderId });+ if (poll.status === "pending") {+ await signerIssuanceJobDAL.updateById(job.id, {+ nextPollAt: new Date(Date.now() + PENDING_VALIDATION_POLL_INTERVAL_MS)+ });+ logger.info(+ `signer issuance: DigiCert order ${ref.orderId} still pending (status=${poll.orderStatus}) [jobId=${job.id}]`+ );+ return;+ }+ if (poll.status === "failed") {+ await markJobFailed(job, poll.reason);+ return;+ }++ const { certificateId } = await digicertFns.fetchAndAttachIssuedCertificate({+ caId: job.caId,+ certificateRequest: {+ id: `signer:${job.signerId}`,+ profileId: undefined,+ commonName: job.commonName,+ altNames: null,+ keyUsages: [CertKeyUsage.DIGITAL_SIGNATURE, CertKeyUsage.KEY_ENCIPHERMENT],+ extendedKeyUsages: [CertExtendedKeyUsage.CODE_SIGNING],+ keyAlgorithm: job.keyAlgorithm,+ signatureAlgorithm: null+ },+ digicertCertificateId: poll.certificateId,+ digicertOrderId: ref.orderId+ });+ await persistCertificatePrivateKey(certificateId, projectId, job);+ await attachIssuedCertToSigner(job, certificateId, projectId);+ };++ const stepSyncWithCsr = async (job: TPkiSignerIssuanceJobs, kind: "acme" | "azure" | "aws-pca" | "venafi") => {+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(job.caId);+ if (!ca) {+ await markJobFailed(job, "Certificate authority is no longer available.");+ return;+ }+ const { projectId } = ca;+ const csr = (await decryptForProject(projectId, Buffer.from(job.encryptedCsr as Buffer))).toString();++ let certificateId: string;++ if (kind === "acme") {+ const acmeResult = await acmeFns.orderCertificateFromProfile({+ caId: job.caId,+ profileId: undefined as unknown as string,+ commonName: job.commonName,+ altNames: [],+ csr: Buffer.from(csr),+ csrPrivateKey: (await decryptForProject(projectId, Buffer.from(job.encryptedPrivateKey as Buffer))).toString(),+ keyUsages: [CertKeyUsage.DIGITAL_SIGNATURE, CertKeyUsage.KEY_ENCIPHERMENT],+ extendedKeyUsages: [CertExtendedKeyUsage.CODE_SIGNING],+ ttl: `${job.certificateTtlDays}d`,+ signatureAlgorithm: undefined,+ keyAlgorithm: job.keyAlgorithm,+ isRenewal: false,+ originalCertificateId: undefined,+ onProgress: async () => {},+ isCancelled: async () => false+ });+ if (!acmeResult?.id) {+ throw new BadRequestError({ message: "ACME order returned without a certificate id." });+ }+ certificateId = acmeResult.id;+ } else if (kind === "azure") {+ const azureResult = await azureAdCsFns.orderCertificateFromProfile({+ caId: job.caId,+ profileId: undefined as unknown as string,+ commonName: job.commonName,+ altNames: [],+ keyUsages: [CertKeyUsage.DIGITAL_SIGNATURE, CertKeyUsage.KEY_ENCIPHERMENT],+ extendedKeyUsages: [CertExtendedKeyUsage.CODE_SIGNING],+ validity: { ttl: `${job.certificateTtlDays}d` },+ signatureAlgorithm: undefined,+ keyAlgorithm: job.keyAlgorithm as CertKeyAlgorithm,+ isRenewal: false,+ originalCertificateId: undefined,+ csr,+ isCancelled: async () => false+ } as Parameters<typeof azureAdCsFns.orderCertificateFromProfile>[0]);+ if (!azureResult?.certificateId) {+ throw new BadRequestError({ message: "Azure AD CS order returned without a certificate id." });+ }+ certificateId = azureResult.certificateId;+ } else if (kind === "aws-pca") {+ const awsResult = await awsPcaFns.orderCertificateFromProfile({+ caId: job.caId,+ profileId: undefined as unknown as string,+ commonName: job.commonName,+ altNames: [],+ keyUsages: [CertKeyUsage.DIGITAL_SIGNATURE, CertKeyUsage.KEY_ENCIPHERMENT],+ extendedKeyUsages: [CertExtendedKeyUsage.CODE_SIGNING],+ validity: { ttl: `${job.certificateTtlDays}d` },+ signatureAlgorithm: undefined,+ keyAlgorithm: job.keyAlgorithm as CertKeyAlgorithm,+ isRenewal: false,+ originalCertificateId: undefined,+ csr,+ isCancelled: async () => false+ });+ if (!awsResult?.certificateId) {+ throw new BadRequestError({ message: "AWS PCA order returned without a certificate id." });+ }+ certificateId = awsResult.certificateId;+ } else {+ const venafiResult = await venafiTppFns.orderCertificateFromProfile({+ caId: job.caId,+ profileId: undefined as unknown as string,+ commonName: job.commonName,+ altNames: [],+ keyUsages: [CertKeyUsage.DIGITAL_SIGNATURE, CertKeyUsage.KEY_ENCIPHERMENT],+ extendedKeyUsages: [CertExtendedKeyUsage.CODE_SIGNING],+ validity: { ttl: `${job.certificateTtlDays}d` },+ signatureAlgorithm: undefined,+ keyAlgorithm: job.keyAlgorithm as CertKeyAlgorithm,+ isRenewal: false,+ originalCertificateId: undefined,+ csr,+ isCancelled: async () => false+ });+ if (!venafiResult?.certificateId) {+ throw new BadRequestError({ message: "Venafi TPP order returned without a certificate id." });+ }+ certificateId = venafiResult.certificateId;+ }++ await persistCertificatePrivateKey(certificateId, projectId, job);+ await attachIssuedCertToSigner(job, certificateId, projectId);+ };++ const persistCertificatePrivateKey = async (+ certificateId: string,+ projectId: string,+ job: TPkiSignerIssuanceJobs+ ) => {+ if (!job.encryptedPrivateKey) return;+ const existing = await certificateSecretDAL.findOne({ certId: certificateId });+ if (existing) {+ try {+ await certificateSecretDAL.updateById(existing.id, {+ encryptedPrivateKey: job.encryptedPrivateKey+ });+ } catch (err) {+ logger.warn(+ err,+ `signer issuance: could not replace cert_secrets private key, leaving the per-CA fn's copy in place [certificateId=${certificateId}]`+ );+ }+ return;+ }+ try {+ await certificateSecretDAL.create({+ certId: certificateId,+ encryptedPrivateKey: job.encryptedPrivateKey+ });+ } catch (err) {+ logger.warn(err, `signer issuance: could not create cert_secrets row [certificateId=${certificateId}]`);+ }+ };++ const start = () => {+ cronJob.register({+ name: CronJobName.SignerIssuancePolling,+ pattern: POLL_INTERVAL_PATTERN,+ runHashTtlS: 15 * 60,+ handler: async () => {+ const due = await signerIssuanceJobDAL.findDuePending(new Date(), POLL_BATCH);+ if (due.length === 0) return;+ logger.info(`signer-issuance-polling: picked up ${due.length} pending jobs`);+ for (const job of due) {+ try {+ await processJob(job.id);+ } catch (err) {+ logger.error(err, `signer-issuance-polling: processing job failed [jobId=${job.id}]`);+ }+ }+ }+ });+ };++ return {+ requestIssuance,+ processJob,+ start,+ _buildCsrForSigner: buildCsrForSigner+ };+};diff --git a/backend/src/services/signer/signer-policy-service.ts b/backend/src/services/signer/signer-policy-service.tsnew file mode 100644index 0000000000..e15fafe187--- /dev/null+++ b/backend/src/services/signer/signer-policy-service.ts@@ -0,0 +1,735 @@+import { ForbiddenError } from "@casl/ability";++import { ApplicationMembershipRole, RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";+import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";+import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ResourcePermissionSignerActions,+ ResourcePermissionSub+} from "@app/ee/services/permission/resource-permission";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { ms } from "@app/lib/ms";++import {+ TApprovalPolicyDALFactory,+ TApprovalPolicyStepApproversDALFactory,+ TApprovalPolicyStepsDALFactory+} from "../approval-policy/approval-policy-dal";+import {+ ApprovalPolicyScope,+ ApprovalPolicyType,+ ApprovalRequestGrantStatus,+ ApprovalRequestStatus+} from "../approval-policy/approval-policy-enums";+import {+ TApprovalRequestDALFactory,+ TApprovalRequestGrantsDALFactory,+ TApprovalRequestStepEligibleApproversDALFactory,+ TApprovalRequestStepsDALFactory+} from "../approval-policy/approval-request-dal";+import { createApprovalRequestWithSteps } from "../approval-policy/approval-request-fns";+import { ActorType } from "../auth/auth-type";+import { TIdentityDALFactory } from "../identity/identity-dal";+import { TMembershipDALFactory } from "../membership/membership-dal";+import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";+import { TUserDALFactory } from "../user/user-dal";+import { TSignerDALFactory } from "./signer-dal";+import {+ TGetSignerPolicyDTO,+ TListSignerRequestsDTO,+ TPreApproveSigningDTO,+ TRequestToSignDTO,+ TRevokeSignerRequestDTO,+ TSignerRequestStatusFilter,+ TUpdateSignerPolicyDTO+} from "./signer-types";++type TSignerPolicyServiceFactoryDep = {+ signerDAL: Pick<TSignerDALFactory, "findById">;+ approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findById" | "updateById" | "findStepsByPolicyId">;+ approvalPolicyStepsDAL: Pick<TApprovalPolicyStepsDALFactory, "create" | "delete" | "find">;+ approvalPolicyStepApproversDAL: Pick<TApprovalPolicyStepApproversDALFactory, "create" | "delete">;+ approvalRequestDAL: Pick<+ TApprovalRequestDALFactory,+ | "create"+ | "find"+ | "findById"+ | "updateById"+ | "transaction"+ | "listSignerRequestsPaginated"+ | "countSignerRequests"+ >;+ approvalRequestStepsDAL: Pick<TApprovalRequestStepsDALFactory, "create">;+ approvalRequestStepEligibleApproversDAL: Pick<TApprovalRequestStepEligibleApproversDALFactory, "create">;+ approvalRequestGrantsDAL: Pick<TApprovalRequestGrantsDALFactory, "create" | "find" | "updateById">;+ membershipDAL: Pick<TMembershipDALFactory, "find" | "transaction">;+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;+ identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;+ userDAL: Pick<TUserDALFactory, "findById">;+ identityDAL: Pick<TIdentityDALFactory, "findById">;+ permissionService: Pick<TPermissionServiceFactory, "getResourcePermission">;+};++export type TSignerPolicyServiceFactory = ReturnType<typeof signerPolicyServiceFactory>;++type TConstraintsBlob = {+ constraints?: {+ maxSignings?: number | null;+ maxWindowDuration?: string | null;+ };+};++const $loadSignerOrThrow = async (signerDAL: TSignerPolicyServiceFactoryDep["signerDAL"], signerId: string) => {+ const signer = await signerDAL.findById(signerId);+ if (!signer) {+ throw new NotFoundError({ message: `Signer with ID '${signerId}' not found` });+ }+ if (!signer.approvalPolicyId) {+ throw new BadRequestError({+ message: `Signer '${signer.name}' does not have an approval policy. Re-create the signer.`+ });+ }+ return signer;+};++export const signerPolicyServiceFactory = ({+ signerDAL,+ approvalPolicyDAL,+ approvalPolicyStepsDAL,+ approvalPolicyStepApproversDAL,+ approvalRequestDAL,+ approvalRequestStepsDAL,+ approvalRequestStepEligibleApproversDAL,+ approvalRequestGrantsDAL,+ membershipDAL,+ membershipRoleDAL,+ userGroupMembershipDAL,+ identityGroupMembershipDAL,+ userDAL,+ identityDAL,+ permissionService+}: TSignerPolicyServiceFactoryDep) => {+ const $assertResourcePermission = async (+ signerId: string,+ projectId: string,+ actor: TGetSignerPolicyDTO["actor"],+ actorId: string,+ actorAuthMethod: TGetSignerPolicyDTO["actorAuthMethod"],+ actorOrgId: string | undefined,+ action: ResourcePermissionSignerActions+ ) => {+ const { permission } = await permissionService.getResourcePermission({+ actor,+ actorId,+ projectId,+ resourceType: ResourceType.Signer,+ resourceId: signerId,+ actorAuthMethod,+ actorOrgId+ });+ ForbiddenError.from(permission).throwUnlessCan(action, ResourcePermissionSub.Signer);+ };++ const $resolveActorDisplay = async ({+ userId,+ identityId+ }: {+ userId?: string | null;+ identityId?: string | null;+ }): Promise<{ name: string; email: string }> => {+ if (userId) {+ const u = await userDAL.findById(userId);+ if (u) {+ const fullName = [u.firstName, u.lastName]+ .filter((p): p is string => Boolean(p?.trim()))+ .join(" ")+ .trim();+ return { name: fullName || u.username || u.email || userId, email: u.email ?? "" };+ }+ return { name: userId, email: "" };+ }+ if (identityId) {+ const i = await identityDAL.findById(identityId);+ return { name: i?.name || identityId, email: "" };+ }+ return { name: "", email: "" };+ };++ const $assertRequestWithinPolicyLimits = (+ policyConstraints: unknown,+ dto: { requestedSignings?: number; requestedWindowStart?: string; requestedWindowEnd?: string }+ ) => {+ const blob = (policyConstraints as TConstraintsBlob) ?? {};+ const maxSignings = blob.constraints?.maxSignings ?? null;+ const maxWindowDuration = blob.constraints?.maxWindowDuration ?? null;++ if (dto.requestedSignings !== undefined && dto.requestedSignings < 1) {+ throw new BadRequestError({ message: "requestedSignings must be at least 1." });+ }+ if (maxSignings !== null && dto.requestedSignings !== undefined && dto.requestedSignings > maxSignings) {+ throw new BadRequestError({+ message: `Requested signatures (${dto.requestedSignings}) exceed the policy limit of ${maxSignings}.`+ });+ }++ if (dto.requestedWindowEnd) {+ const end = new Date(dto.requestedWindowEnd).getTime();+ if (Number.isNaN(end)) {+ throw new BadRequestError({ message: "Invalid requestedWindowEnd date." });+ }+ const rawStart = dto.requestedWindowStart ? new Date(dto.requestedWindowStart).getTime() : Date.now();+ if (Number.isNaN(rawStart)) {+ throw new BadRequestError({ message: "Invalid requestedWindowStart date." });+ }+ const startTime = Math.max(rawStart, Date.now());+ if (end <= startTime) {+ throw new BadRequestError({+ message: "requestedWindowEnd must be in the future and after requestedWindowStart."+ });+ }+ if (maxWindowDuration) {+ let allowedMs: number;+ try {+ allowedMs = ms(maxWindowDuration);+ } catch {+ return;+ }+ if (end - startTime > allowedMs) {+ throw new BadRequestError({+ message: `Requested signing window exceeds the policy maximum of ${maxWindowDuration}.`+ });+ }+ }+ }+ };++ const $resolveGranteeEffectiveRoles = async ({+ projectId,+ signerId,+ granteeUserId,+ granteeIdentityId+ }: {+ projectId: string;+ signerId: string;+ granteeUserId?: string;+ granteeIdentityId?: string;+ }): Promise<string[]> => {+ const directWhere: Record<string, unknown> = {+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signerId+ };+ if (granteeUserId) directWhere.actorUserId = granteeUserId;+ else directWhere.actorIdentityId = granteeIdentityId;++ const directMemberships = await membershipDAL.find(directWhere);++ const memberGroupIds = granteeUserId+ ? (await userGroupMembershipDAL.find({ userId: granteeUserId })).map((g) => g.groupId)+ : (await identityGroupMembershipDAL.find({ identityId: granteeIdentityId as string })).map((g) => g.groupId);++ let groupMemberships: Awaited<ReturnType<typeof membershipDAL.find>> = [];+ if (memberGroupIds.length > 0) {+ groupMemberships = await membershipDAL.find({+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signerId,+ $in: { actorGroupId: memberGroupIds }+ });+ }++ const membershipIds = [...directMemberships, ...groupMemberships].map((m) => m.id);+ if (membershipIds.length === 0) return [];++ const roles = await membershipRoleDAL.find({ $in: { membershipId: membershipIds } });+ return roles.map((r) => r.role).filter((r): r is string => Boolean(r));+ };++ const getPolicy = async (dto: TGetSignerPolicyDTO) => {+ const signer = await $loadSignerOrThrow(signerDAL, dto.signerId);+ await $assertResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId,+ ResourcePermissionSignerActions.Read+ );++ const policy = await approvalPolicyDAL.findById(signer.approvalPolicyId);+ if (!policy) {+ throw new NotFoundError({ message: `Policy for signer '${signer.name}' has been removed.` });+ }+ const steps = await approvalPolicyDAL.findStepsByPolicyId(policy.id);+ const blob = (policy.constraints as TConstraintsBlob) ?? {};+ return {+ id: policy.id,+ signerId: signer.id,+ hasSteps: steps.length > 0,+ steps,+ constraints: {+ maxSignings: blob.constraints?.maxSignings ?? null,+ maxWindowDuration: blob.constraints?.maxWindowDuration ?? null+ }+ };+ };++ const $assertApproversAreMembers = async (signerId: string, projectId: string, userIds: string[]) => {+ if (userIds.length === 0) return;++ const memberships = await membershipDAL.find({+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signerId,+ $in: { actorUserId: userIds }+ });++ const found = new Set(memberships.map((m) => m.actorUserId).filter((v): v is string => Boolean(v)));+ const missing = userIds.filter((u) => !found.has(u));+ if (missing.length > 0) {+ throw new BadRequestError({+ message: `Approvers must already be signer members. Missing: ${missing.join(", ")}.`+ });+ }++ const membershipIds = memberships.map((m) => m.id);+ if (membershipIds.length === 0) return;+ const roles = await membershipRoleDAL.find({ $in: { membershipId: membershipIds } });+ const auditorIds = new Set<string>();+ for (const r of roles) {+ if (r.role === ApplicationMembershipRole.Auditor) {+ const m = memberships.find((mem) => mem.id === r.membershipId);+ if (m?.actorUserId) auditorIds.add(m.actorUserId);+ }+ }+ if (auditorIds.size > 0) {+ throw new BadRequestError({+ message: `Auditors cannot be approvers. Found auditor users: ${Array.from(auditorIds).join(", ")}.`+ });+ }+ };++ const $assertGroupApproversAreMembers = async (signerId: string, projectId: string, groupIds: string[]) => {+ if (groupIds.length === 0) return;++ const memberships = await membershipDAL.find({+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signerId,+ $in: { actorGroupId: groupIds }+ });++ const found = new Set(memberships.map((m) => m.actorGroupId).filter((v): v is string => Boolean(v)));+ const missing = groupIds.filter((g) => !found.has(g));+ if (missing.length > 0) {+ throw new BadRequestError({+ message: `Approver groups must already be signer members. Missing: ${missing.join(", ")}.`+ });+ }++ const membershipIds = memberships.map((m) => m.id);+ const roles = await membershipRoleDAL.find({ $in: { membershipId: membershipIds } });+ const auditorGroupIds = new Set<string>();+ for (const r of roles) {+ if (r.role === ApplicationMembershipRole.Auditor) {+ const m = memberships.find((mem) => mem.id === r.membershipId);+ if (m?.actorGroupId) auditorGroupIds.add(m.actorGroupId);+ }+ }+ if (auditorGroupIds.size > 0) {+ throw new BadRequestError({+ message: `Auditor groups cannot be approvers. Found auditor groups: ${Array.from(auditorGroupIds).join(", ")}.`+ });+ }+ };++ const updatePolicy = async (dto: TUpdateSignerPolicyDTO) => {+ const signer = await $loadSignerOrThrow(signerDAL, dto.signerId);+ await $assertResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId,+ ResourcePermissionSignerActions.ManagePolicy+ );++ const effectiveConstraints =+ dto.steps.length > 0 && !dto.constraints?.maxSignings && !dto.constraints?.maxWindowDuration+ ? { ...(dto.constraints ?? {}), maxSignings: 1, maxWindowDuration: null }+ : (dto.constraints ?? {});++ if (dto.steps.length > 0) {+ if (effectiveConstraints.maxWindowDuration) {+ try {+ ms(effectiveConstraints.maxWindowDuration);+ } catch {+ throw new BadRequestError({+ message: `Invalid maxWindowDuration '${effectiveConstraints.maxWindowDuration}'.`+ });+ }+ }+ const allApproverUserIds = Array.from(new Set(dto.steps.flatMap((s) => s.approverUserIds)));+ const allApproverGroupIds = Array.from(new Set(dto.steps.flatMap((s) => s.approverGroupIds ?? [])));+ await $assertApproversAreMembers(signer.id, signer.projectId, allApproverUserIds);+ await $assertGroupApproversAreMembers(signer.id, signer.projectId, allApproverGroupIds);++ for (const step of dto.steps) {+ const stepApproverGroupCount = step.approverGroupIds?.length ?? 0;+ const stepApproverUserCount = step.approverUserIds.length;+ if (stepApproverUserCount + stepApproverGroupCount === 0) {+ throw new BadRequestError({+ message: `Step ${step.stepNumber}: at least one approver is required.`+ });+ }+ if (step.requiredApprovals < 1) {+ throw new BadRequestError({+ message: `Step ${step.stepNumber}: requiredApprovals must be at least 1.`+ });+ }+ if (stepApproverGroupCount === 0 && step.requiredApprovals > stepApproverUserCount) {+ throw new BadRequestError({+ message: `Step ${step.stepNumber}: requiredApprovals (${step.requiredApprovals}) can't exceed the number of approvers (${stepApproverUserCount}). Add a group to allow more than the current user approvers.`+ });+ }+ }+ }++ await membershipDAL.transaction(async (tx) => {+ const policyId = signer.approvalPolicyId;++ const existingSteps = await approvalPolicyStepsDAL.find({ policyId }, { tx });+ if (existingSteps.length > 0) {+ await approvalPolicyStepApproversDAL.delete({ $in: { policyStepId: existingSteps.map((s) => s.id) } }, tx);+ await approvalPolicyStepsDAL.delete({ $in: { id: existingSteps.map((s) => s.id) } }, tx);+ }++ for (const step of dto.steps) {+ // eslint-disable-next-line no-await-in-loop+ const created = await approvalPolicyStepsDAL.create(+ {+ policyId,+ stepNumber: step.stepNumber,+ name: step.name?.trim() || null,+ requiredApprovals: step.requiredApprovals+ },+ tx+ );+ for (const userId of step.approverUserIds) {+ // eslint-disable-next-line no-await-in-loop+ await approvalPolicyStepApproversDAL.create({ policyStepId: created.id, userId }, tx);+ }+ for (const groupId of step.approverGroupIds ?? []) {+ // eslint-disable-next-line no-await-in-loop+ await approvalPolicyStepApproversDAL.create({ policyStepId: created.id, groupId }, tx);+ }+ }++ const blob: TConstraintsBlob = {+ constraints: {+ maxSignings: effectiveConstraints.maxSignings ?? null,+ maxWindowDuration: effectiveConstraints.maxWindowDuration ?? null+ }+ };+ await approvalPolicyDAL.updateById(policyId, { constraints: blob }, tx);+ });++ return getPolicy({+ signerId: dto.signerId,+ actor: dto.actor,+ actorId: dto.actorId,+ actorAuthMethod: dto.actorAuthMethod,+ actorOrgId: dto.actorOrgId+ });+ };++ const listRequests = async (dto: TListSignerRequestsDTO) => {+ const signer = await $loadSignerOrThrow(signerDAL, dto.signerId);+ await $assertResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId,+ ResourcePermissionSignerActions.Read+ );++ const UI_TO_DB_STATUS: Record<Exclude<TSignerRequestStatusFilter, "revoked">, ApprovalRequestStatus> = {+ pending: ApprovalRequestStatus.Pending,+ approved: ApprovalRequestStatus.Approved,+ expired: ApprovalRequestStatus.Expired+ };+ const dbStatuses: ApprovalRequestStatus[] | undefined = dto.statuses?.flatMap((s) =>+ s === "revoked" ? [ApprovalRequestStatus.Cancelled, ApprovalRequestStatus.Rejected] : [UI_TO_DB_STATUS[s]]+ );++ const offset = dto.offset ?? 0;+ const limit = dto.limit ?? 25;++ const [requests, totalCount] = await Promise.all([+ approvalRequestDAL.listSignerRequestsPaginated({+ signerId: signer.id,+ projectId: signer.projectId,+ type: ApprovalPolicyType.CertCodeSigning,+ statuses: dbStatuses,+ offset,+ limit+ }),+ approvalRequestDAL.countSignerRequests({+ signerId: signer.id,+ projectId: signer.projectId,+ type: ApprovalPolicyType.CertCodeSigning,+ statuses: dbStatuses+ })+ ]);++ if (requests.length === 0) {+ return { requests: [], totalCount };+ }++ return {+ requests,+ totalCount+ };+ };++ const requestToSign = async (dto: TRequestToSignDTO) => {+ const signer = await $loadSignerOrThrow(signerDAL, dto.signerId);+ await $assertResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId,+ ResourcePermissionSignerActions.RequestSign+ );++ const steps = await approvalPolicyDAL.findStepsByPolicyId(signer.approvalPolicyId);+ if (steps.length === 0) {+ throw new BadRequestError({+ message: "This signer does not require approval. You can sign directly."+ });+ }++ if (!dto.requestedSignings && !dto.requestedWindowEnd) {+ throw new BadRequestError({ message: "Provide at least one of requestedSignings or requestedWindowEnd." });+ }++ const policy = await approvalPolicyDAL.findById(signer.approvalPolicyId);+ if (!policy) {+ throw new NotFoundError({ message: `Policy for signer '${signer.name}' has been removed.` });+ }++ $assertRequestWithinPolicyLimits(policy.constraints, {+ requestedSignings: dto.requestedSignings,+ requestedWindowStart: dto.requestedWindowStart,+ requestedWindowEnd: dto.requestedWindowEnd+ });++ const requester = await $resolveActorDisplay({+ userId: dto.actor === ActorType.USER ? dto.actorId : null,+ identityId: dto.actor === ActorType.IDENTITY ? dto.actorId : null+ });++ const orgId = dto.actorOrgId;+ const requestWithSteps = await createApprovalRequestWithSteps(+ {+ projectId: signer.projectId,+ organizationId: orgId,+ policyId: policy.id,+ policyType: ApprovalPolicyType.CertCodeSigning,+ policySteps: steps,+ // createApprovalRequestWithSteps wraps this in { version: 1, requestData } before persisting — pass the flat shape.+ requestData: {+ signerId: signer.id,+ signerName: signer.name,+ approvalPolicyId: policy.id,+ justification: dto.justification,+ requestedSignings: dto.requestedSignings,+ requestedWindowStart: dto.requestedWindowStart,+ requestedWindowEnd: dto.requestedWindowEnd+ },+ justification: dto.justification,+ requesterUserId: dto.actor === ActorType.USER ? dto.actorId : null,+ machineIdentityId: dto.actor === ActorType.IDENTITY ? dto.actorId : null,+ requesterName: requester.name,+ requesterEmail: requester.email,+ scopeType: ApprovalPolicyScope.Signer,+ scopeId: signer.id+ },+ {+ approvalRequestDAL,+ approvalRequestStepsDAL,+ approvalRequestStepEligibleApproversDAL+ }+ );++ return requestWithSteps;+ };++ const preApproveSigning = async (dto: TPreApproveSigningDTO) => {+ const signer = await $loadSignerOrThrow(signerDAL, dto.signerId);+ await $assertResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId,+ ResourcePermissionSignerActions.PreApprove+ );++ if (!dto.granteeUserId && !dto.granteeIdentityId) {+ throw new BadRequestError({ message: "granteeUserId or granteeIdentityId is required." });+ }+ if (!dto.requestedSignings && !dto.requestedWindowEnd) {+ throw new BadRequestError({ message: "Provide at least one of requestedSignings or requestedWindowEnd." });+ }++ const policy = await approvalPolicyDAL.findById(signer.approvalPolicyId);+ if (!policy) {+ throw new NotFoundError({ message: `Policy for signer '${signer.name}' has been removed.` });+ }+ $assertRequestWithinPolicyLimits(policy.constraints, {+ requestedSignings: dto.requestedSignings,+ requestedWindowStart: dto.requestedWindowStart,+ requestedWindowEnd: dto.requestedWindowEnd+ });++ const granteeRoles = await $resolveGranteeEffectiveRoles({+ projectId: signer.projectId,+ signerId: signer.id,+ granteeUserId: dto.granteeUserId,+ granteeIdentityId: dto.granteeIdentityId+ });+ if (granteeRoles.length === 0) {+ throw new BadRequestError({ message: "Grantee is not a member of this signer." });+ }+ const hasGrantableRole = granteeRoles.some((r) => r !== ApplicationMembershipRole.Auditor);+ if (!hasGrantableRole) {+ throw new BadRequestError({ message: "Grantee must be an Administrator or Operator on this signer." });+ }++ const grantee = await $resolveActorDisplay({+ userId: dto.granteeUserId,+ identityId: dto.granteeIdentityId+ });++ const orgId = dto.actorOrgId;+ const result = await membershipDAL.transaction(async (tx) => {+ const request = await approvalRequestDAL.create(+ {+ projectId: signer.projectId,+ organizationId: orgId,+ policyId: signer.approvalPolicyId,+ type: ApprovalPolicyType.CertCodeSigning,+ status: ApprovalRequestStatus.Approved,+ justification: dto.justification,+ currentStep: 1,+ requesterId: dto.granteeUserId ?? null,+ machineIdentityId: dto.granteeIdentityId ?? null,+ requesterName: grantee.name,+ requesterEmail: grantee.email,+ scopeType: ApprovalPolicyScope.Signer,+ scopeId: signer.id,+ requestData: {+ version: 1,+ requestData: {+ signerId: signer.id,+ signerName: signer.name,+ approvalPolicyId: signer.approvalPolicyId,+ justification: dto.justification,+ requestedSignings: dto.requestedSignings,+ requestedWindowStart: dto.requestedWindowStart,+ requestedWindowEnd: dto.requestedWindowEnd+ }+ }+ },+ tx+ );++ const grant = await approvalRequestGrantsDAL.create(+ {+ projectId: signer.projectId,+ requestId: request.id,+ granteeUserId: dto.granteeUserId ?? null,+ granteeMachineIdentityId: dto.granteeIdentityId ?? null,+ status: ApprovalRequestGrantStatus.Active,+ type: ApprovalPolicyType.CertCodeSigning,+ attributes: {+ signerId: signer.id,+ signerName: signer.name,+ maxSignings: dto.requestedSignings,+ windowStart: dto.requestedWindowStart+ },+ expiresAt: dto.requestedWindowEnd ? new Date(dto.requestedWindowEnd) : null,+ grantedByUserId: dto.actor === ActorType.USER ? dto.actorId : null+ },+ tx+ );++ return { request, grant };+ });++ return result;+ };++ const revokeRequest = async (dto: TRevokeSignerRequestDTO) => {+ const signer = await $loadSignerOrThrow(signerDAL, dto.signerId);+ await $assertResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId,+ ResourcePermissionSignerActions.RevokeRequest+ );++ const request = await approvalRequestDAL.findById(dto.requestId);+ if (!request || request.scopeId !== signer.id) {+ throw new NotFoundError({ message: `Request '${dto.requestId}' not found on this signer.` });+ }++ await membershipDAL.transaction(async (tx) => {+ const grants = await approvalRequestGrantsDAL.find(+ { requestId: dto.requestId, status: ApprovalRequestGrantStatus.Active },+ { tx }+ );+ for (const grant of grants) {+ // eslint-disable-next-line no-await-in-loop+ await approvalRequestGrantsDAL.updateById(+ grant.id,+ {+ status: ApprovalRequestGrantStatus.Revoked,+ revokedAt: new Date(),+ revokedByUserId: dto.actor === ActorType.USER ? dto.actorId : null+ },+ tx+ );+ }+ await approvalRequestDAL.updateById(dto.requestId, { status: ApprovalRequestStatus.Cancelled }, tx);+ });++ return { requestId: dto.requestId };+ };++ return {+ getPolicy,+ updatePolicy,+ listRequests,+ requestToSign,+ preApproveSigning,+ revokeRequest+ };+};diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.tsindex d669eb0121..8919ad1296 100644--- a/backend/src/services/signer/signer-service.ts+++ b/backend/src/services/signer/signer-service.ts@@ -1,69 +1,143 @@import { ForbiddenError } from "@casl/ability";+import * as x509 from "@peculiar/x509";import { KeyObject } from "crypto";-import { ActionProjectType } from "@app/db/schemas";+import {+ ActionProjectType,+ ApplicationMembershipRole,+ ProjectMembershipRole,+ RESOURCE_SCOPE,+ ResourceType+} from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {ProjectPermissionCodeSigningActions,+ ProjectPermissionMemberActions,ProjectPermissionSub} from "@app/ee/services/permission/project-permission";+import {+ ResourcePermissionSignerActions,+ ResourcePermissionSub+} from "@app/ee/services/permission/resource-permission";import { crypto } from "@app/lib/crypto/cryptography";import { signingService } from "@app/lib/crypto/sign/signing";import { AsymmetricKeyAlgorithm, SigningAlgorithm } from "@app/lib/crypto/sign/types";import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";-import { TApprovalPolicyDALFactory } from "../approval-policy/approval-policy-dal";-import { ApprovalPolicyType, ApprovalRequestGrantStatus } from "../approval-policy/approval-policy-enums";-import { TApprovalRequestGrantsDALFactory } from "../approval-policy/approval-request-dal";+import {+ TApprovalPolicyDALFactory,+ TApprovalPolicyStepApproversDALFactory,+ TApprovalPolicyStepsDALFactory+} from "../approval-policy/approval-policy-dal";+import {+ ApprovalPolicyScope,+ ApprovalPolicyType,+ ApprovalRequestGrantStatus+} from "../approval-policy/approval-policy-enums";+import { TApprovalRequestDALFactory, TApprovalRequestGrantsDALFactory } from "../approval-policy/approval-request-dal";import { TCodeSigningGrantAttributes } from "../approval-policy/code-signing/code-signing-policy-types";+import { ActorType } from "../auth/auth-type";+import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";import { TCertificateDALFactory } from "../certificate/certificate-dal";import { getCertificateCredentials } from "../certificate/certificate-fns";import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";-import { CertExtendedKeyUsage, CertStatus } from "../certificate/certificate-types";+import { CertExtendedKeyUsage, CertKeyAlgorithm, CertStatus } from "../certificate/certificate-types";+import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";+import { CaStatus, CaType } from "../certificate-authority/certificate-authority-enums";+import { TInternalCertificateAuthorityServiceFactory } from "../certificate-authority/internal/internal-certificate-authority-service";import { TKmsServiceFactory } from "../kms/kms-service";+import { TMembershipDALFactory } from "../membership/membership-dal";+import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";import { TProjectDALFactory } from "../project/project-dal";+import { getProjectKmsCertificateKeyId } from "../project/project-fns";+import { isBuiltInSignerRole, unknownSignerRoleMessage } from "../signer-membership/signer-membership-service";import { TSignerDALFactory } from "./signer-dal";import { SignerStatus, SigningOperationStatus } from "./signer-enums";+import { formatSignerIssuanceErrorReason } from "./signer-issuance-errors";+import { issueSignerCertificate } from "./signer-issuance-fns";+import { TSignerIssuanceServiceFactory } from "./signer-issuance-service";import {TCreateSignerDTO,TDeleteSignerDTO,+ TDisableSignerDTO,+ TEnableSignerDTO,+ TExportCertificateDTO,TGetPublicKeyDTO,TGetSignerDTO,TListSignersDTO,TListSigningOperationsDTO,+ TReissueCertificateDTO,TSignDataDTO,TUpdateSignerDTO} from "./signer-types";import { TSigningOperationDALFactory } from "./signing-operation-dal";const MAX_DATA_BYTES = 128;+const DEFAULT_CERTIFICATE_TTL_DAYS = 365;++const computeEffectiveStatus = (signer: {+ status: string;+ certificateNotAfter?: Date | string | null;+ certificateStatus?: string | null;+}): SignerStatus => {+ const dbStatus = signer.status as SignerStatus;+ if (dbStatus !== SignerStatus.Active) return dbStatus;+ if (signer.certificateStatus === CertStatus.REVOKED) return SignerStatus.Expired;+ if (signer.certificateNotAfter && new Date(signer.certificateNotAfter) < new Date()) {+ return SignerStatus.Expired;+ }+ return SignerStatus.Active;+};type TSignerServiceFactoryDep = {signerDAL: TSignerDALFactory;signingOperationDAL: TSigningOperationDALFactory;certificateDAL: Pick<TCertificateDALFactory, "findById">;- certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne">;+ certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;+ certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;+ signerIssuanceService: Pick<TSignerIssuanceServiceFactory, "requestIssuance">;+ internalCertificateAuthorityService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa">;projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;- kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "encryptWithKmsKey" | "generateKmsKey">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;approvalPolicyDAL: TApprovalPolicyDALFactory;+ approvalPolicyStepsDAL: Pick<TApprovalPolicyStepsDALFactory, "create">;+ approvalPolicyStepApproversDAL: Pick<TApprovalPolicyStepApproversDALFactory, "create">;+ approvalRequestDAL: Pick<TApprovalRequestDALFactory, "delete">;approvalRequestGrantsDAL: TApprovalRequestGrantsDALFactory;+ membershipDAL: Pick<+ TMembershipDALFactory,+ "create" | "find" | "delete" | "transaction" | "findResourceMembershipsForActor"+ >;+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "delete">;};export type TSignerServiceFactory = ReturnType<typeof signerServiceFactory>;-const getKeyAlgorithm = (key: KeyObject): AsymmetricKeyAlgorithm => {+const getKeyAlgorithmFamily = (key: KeyObject): AsymmetricKeyAlgorithm => {const keyType = key.asymmetricKeyType;if (keyType === "rsa") {return AsymmetricKeyAlgorithm.RSA_4096;}if (keyType === "ec") {const { namedCurve } = key.asymmetricKeyDetails as { namedCurve?: string };- if (namedCurve !== "prime256v1" && namedCurve !== "P-256") {- throw new BadRequestError({ message: `Unsupported EC curve: ${namedCurve}. Only P-256 is supported.` });+ switch (namedCurve) {+ case "prime256v1":+ case "P-256":+ return AsymmetricKeyAlgorithm.ECC_NIST_P256;+ case "secp384r1":+ case "P-384":+ return AsymmetricKeyAlgorithm.ECC_NIST_P384;+ case "secp521r1":+ case "P-521":+ return AsymmetricKeyAlgorithm.ECC_NIST_P521;+ default:+ throw new BadRequestError({+ message: `Unsupported EC curve: ${namedCurve}. Supported curves: P-256, P-384, P-521.`+ });}- return AsymmetricKeyAlgorithm.ECC_NIST_P256;}throw new BadRequestError({ message: `Unsupported key type: ${keyType}` });};@@ -89,13 +163,40 @@ export const signerServiceFactory = ({signerDAL,signingOperationDAL,certificateDAL,+ certificateBodyDAL,certificateSecretDAL,+ certificateAuthorityDAL,+ signerIssuanceService,+ internalCertificateAuthorityService,projectDAL,kmsService,permissionService,approvalPolicyDAL,- approvalRequestGrantsDAL+ approvalPolicyStepsDAL,+ approvalPolicyStepApproversDAL,+ approvalRequestDAL,+ approvalRequestGrantsDAL,+ membershipDAL,+ membershipRoleDAL}: TSignerServiceFactoryDep) => {+ const $loadSignerResourcePermission = async (+ signerId: string,+ projectId: string,+ actor: TGetSignerDTO["actor"],+ actorId: string,+ actorAuthMethod: TGetSignerDTO["actorAuthMethod"],+ actorOrgId?: string+ ) =>+ permissionService.getResourcePermission({+ actor,+ actorId,+ projectId,+ resourceType: ResourceType.Signer,+ resourceId: signerId,+ actorAuthMethod,+ actorOrgId+ });+const create = async (dto: TCreateSignerDTO) => {const { permission } = await permissionService.getProjectPermission({actor: dto.actor,@@ -111,57 +212,299 @@ export const signerServiceFactory = ({ProjectPermissionSub.CodeSigners);- const certificate = await certificateDAL.findById(dto.certificateId);- if (!certificate) {- throw new NotFoundError({ message: `Certificate with ID '${dto.certificateId}' not found` });- }- if (certificate.projectId !== dto.projectId) {- throw new BadRequestError({ message: "Certificate must belong to the same project" });- }-- if (certificate.status === CertStatus.REVOKED) {- throw new BadRequestError({ message: "Certificate has been revoked" });- }- if (certificate.notAfter && new Date(certificate.notAfter) < new Date()) {- throw new BadRequestError({ message: "Certificate has expired" });+ const usingExistingCert = Boolean(dto.certificateId);+ const usingCa = Boolean(dto.caId);+ if (usingExistingCert === usingCa) {+ throw new BadRequestError({+ message:+ "Provide either certificateId (bring an existing certificate) or caId + commonName (issue a fresh one)."+ });}- const extendedKeyUsages = certificate.extendedKeyUsages as string[] | null;- if (!extendedKeyUsages?.includes(CertExtendedKeyUsage.CODE_SIGNING)) {- throw new BadRequestError({ message: "Certificate must have the codeSigning extended key usage" });+ if (usingCa && dto.renewBeforeDays != null) {+ const ttl = dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS;+ if (dto.renewBeforeDays >= ttl) {+ throw new BadRequestError({+ message: `Renew before (${dto.renewBeforeDays}d) must be less than the certificate validity (${ttl}d).`+ });+ }}- const certSecret = await certificateSecretDAL.findOne({ certId: dto.certificateId });- if (!certSecret) {- throw new BadRequestError({ message: "Certificate must have an associated private key" });+ if (usingExistingCert) {+ const certificate = await certificateDAL.findById(dto.certificateId as string);+ if (!certificate) {+ throw new NotFoundError({ message: `Certificate with ID '${dto.certificateId}' not found` });+ }+ if (certificate.projectId !== dto.projectId) {+ throw new BadRequestError({ message: "Certificate must belong to the same project" });+ }+ if (certificate.status === CertStatus.REVOKED) {+ throw new BadRequestError({ message: "Certificate has been revoked" });+ }+ if (certificate.notAfter && new Date(certificate.notAfter) < new Date()) {+ throw new BadRequestError({ message: "Certificate has expired" });+ }+ const extendedKeyUsages = certificate.extendedKeyUsages as string[] | null;+ if (!extendedKeyUsages?.includes(CertExtendedKeyUsage.CODE_SIGNING)) {+ throw new BadRequestError({ message: "Certificate must have the codeSigning extended key usage" });+ }+ const certSecret = await certificateSecretDAL.findOne({ certId: dto.certificateId as string });+ if (!certSecret) {+ throw new BadRequestError({ message: "Certificate must have an associated private key" });+ }}- if (dto.approvalPolicyId) {- const approvalPolicy = await approvalPolicyDAL.findById(dto.approvalPolicyId);- if (!approvalPolicy) {- throw new NotFoundError({ message: `Approval policy with ID '${dto.approvalPolicyId}' not found` });+ let resolvedCaId: string | null = null;+ let resolvedCaType: CaType | null = null;+ if (usingCa) {+ if (!dto.commonName) {+ throw new BadRequestError({ message: "commonName is required when issuing a certificate from a CA." });}- if (approvalPolicy.projectId !== dto.projectId) {- throw new BadRequestError({ message: "Approval policy must belong to the same project" });+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(dto.caId as string);+ if (!ca || ca.projectId !== dto.projectId) {+ throw new NotFoundError({ message: `Certificate authority '${dto.caId}' not found in this project.` });}- if (approvalPolicy.type !== ApprovalPolicyType.CertCodeSigning) {- throw new BadRequestError({- message: "Approval policy must be of type cert-code-signing"- });+ if (ca.status !== CaStatus.ACTIVE) {+ throw new BadRequestError({ message: "The selected certificate authority is not active." });}+ resolvedCaId = ca.id;+ resolvedCaType = (ca.externalCa?.type as CaType | undefined) ?? CaType.INTERNAL;+ }++ const isExternalCa = resolvedCaType !== null && resolvedCaType !== CaType.INTERNAL;++ const keyAlgorithm: CertKeyAlgorithm = (dto.keyAlgorithm as CertKeyAlgorithm) ?? CertKeyAlgorithm.RSA_2048;++ let issuedCertificateId: string | null = null;+ if (usingCa && resolvedCaId && !isExternalCa) {+ const { certificateId } = await issueSignerCertificate(+ {+ certificateAuthorityDAL,+ internalCertificateAuthorityService,+ certificateBodyDAL,+ certificateSecretDAL,+ projectDAL,+ kmsService+ },+ {+ caId: resolvedCaId,+ projectId: dto.projectId,+ commonName: dto.commonName as string,+ certificateTtlDays: dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS,+ keyAlgorithm+ }+ );+ issuedCertificateId = certificateId;}+ const finalCertificateId = usingExistingCert ? (dto.certificateId as string) : issuedCertificateId;+ const initialStatus: SignerStatus = isExternalCa ? SignerStatus.Pending : SignerStatus.Active;+try {- const signer = await signerDAL.create({- projectId: dto.projectId,- name: dto.name,- description: dto.description,- certificateId: dto.certificateId,- approvalPolicyId: dto.approvalPolicyId ?? null,- status: SignerStatus.Active+ const result = await signerDAL.transaction(async (tx) => {+ const project = await projectDAL.findOne({ id: dto.projectId }, tx);+ if (!project) {+ throw new NotFoundError({ message: `Project '${dto.projectId}' not found.` });+ }+ const policy = await approvalPolicyDAL.create(+ {+ projectId: dto.projectId,+ organizationId: project.orgId,+ type: ApprovalPolicyType.CertCodeSigning,+ name: `signer:pending`,+ scopeType: ApprovalPolicyScope.Signer,+ scopeId: null,+ conditions: {},+ constraints: {}+ },+ tx+ );++ const signer = await signerDAL.create(+ {+ projectId: dto.projectId,+ name: dto.name,+ description: dto.description,+ certificateId: finalCertificateId,+ caId: resolvedCaId,+ commonName: usingCa ? dto.commonName : null,+ certificateTtlDays: usingCa ? (dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS) : null,+ renewBeforeDays: usingCa ? (dto.renewBeforeDays ?? null) : null,+ keyAlgorithm,+ status: initialStatus,+ approvalPolicyId: policy.id,+ failureReason: null+ },+ tx+ );++ await approvalPolicyDAL.updateById(+ policy.id,+ {+ scopeId: signer.id,+ name: `signer:${signer.id}`+ },+ tx+ );++ if (dto.actor === ActorType.USER && dto.actorOrgId) {+ const newMembership = await membershipDAL.create(+ {+ scope: RESOURCE_SCOPE,+ scopeOrgId: dto.actorOrgId,+ scopeProjectId: dto.projectId,+ actorUserId: dto.actorId,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signer.id,+ isActive: true+ },+ tx+ );+ await membershipRoleDAL.create({ membershipId: newMembership.id, role: ApplicationMembershipRole.Admin }, tx);+ }++ const pendingMembers = (dto.members ?? []).filter(+ (m) => !(m.kind === "user" && dto.actor === ActorType.USER && m.id === dto.actorId)+ );+ if (pendingMembers.length > 0 && !dto.actorOrgId) {+ throw new BadRequestError({+ message: "Cannot add members during signer creation without an organization context."+ });+ }+ for (const member of pendingMembers) {+ if (!isBuiltInSignerRole(member.role)) {+ throw new BadRequestError({ message: unknownSignerRoleMessage(member.role) });+ }+ const membershipFields = {+ scope: RESOURCE_SCOPE,+ scopeOrgId: dto.actorOrgId,+ scopeProjectId: dto.projectId,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: signer.id,+ isActive: true,+ actorUserId: member.kind === "user" ? member.id : null,+ actorIdentityId: member.kind === "identity" ? member.id : null,+ actorGroupId: member.kind === "group" ? member.id : null+ };+ // eslint-disable-next-line no-await-in-loop+ const newMembership = await membershipDAL.create(membershipFields, tx);+ // eslint-disable-next-line no-await-in-loop+ await membershipRoleDAL.create({ membershipId: newMembership.id, role: member.role }, tx);+ }++ const { approvalPolicy } = dto;+ if (approvalPolicy && approvalPolicy.steps.length > 0) {+ const effectiveConstraints =+ !approvalPolicy.constraints?.maxSignings && !approvalPolicy.constraints?.maxWindowDuration+ ? { ...(approvalPolicy.constraints ?? {}), maxSignings: 1, maxWindowDuration: null }+ : (approvalPolicy.constraints ?? {});++ const allowedApproverIds = new Set<string>();+ if (dto.actor === ActorType.USER) allowedApproverIds.add(dto.actorId);+ const allowedGroupApproverIds = new Set<string>();+ for (const m of pendingMembers) {+ if (m.role !== ApplicationMembershipRole.Auditor) {+ if (m.kind === "user") allowedApproverIds.add(m.id);+ else if (m.kind === "group") allowedGroupApproverIds.add(m.id);+ }+ }++ for (const step of approvalPolicy.steps) {+ const stepApproverGroupIds = step.approverGroupIds ?? [];+ const stepApproverUserCount = step.approverUserIds.length;+ const stepApproverGroupCount = stepApproverGroupIds.length;+ if (stepApproverUserCount + stepApproverGroupCount === 0) {+ throw new BadRequestError({+ message: `Step ${step.stepNumber}: at least one approver is required.`+ });+ }+ if (step.requiredApprovals < 1) {+ throw new BadRequestError({+ message: `Step ${step.stepNumber}: requiredApprovals must be at least 1.`+ });+ }+ if (stepApproverGroupCount === 0 && step.requiredApprovals > stepApproverUserCount) {+ throw new BadRequestError({+ message: `Step ${step.stepNumber}: requiredApprovals (${step.requiredApprovals}) can't exceed the number of approvers (${stepApproverUserCount}). Add a group to allow more than the current user approvers.`+ });+ }+ for (const userId of step.approverUserIds) {+ if (!allowedApproverIds.has(userId)) {+ throw new BadRequestError({+ message: `Step ${step.stepNumber}: approver '${userId}' is not a member of the signer or is an auditor.`+ });+ }+ }+ for (const groupId of stepApproverGroupIds) {+ if (!allowedGroupApproverIds.has(groupId)) {+ throw new BadRequestError({+ message: `Step ${step.stepNumber}: approver group '${groupId}' is not a member of the signer or is an auditor.`+ });+ }+ }+ // eslint-disable-next-line no-await-in-loop+ const createdStep = await approvalPolicyStepsDAL.create(+ {+ policyId: policy.id,+ stepNumber: step.stepNumber,+ name: step.name?.trim() || null,+ requiredApprovals: step.requiredApprovals+ },+ tx+ );+ for (const userId of step.approverUserIds) {+ // eslint-disable-next-line no-await-in-loop+ await approvalPolicyStepApproversDAL.create({ policyStepId: createdStep.id, userId }, tx);+ }+ for (const groupId of stepApproverGroupIds) {+ // eslint-disable-next-line no-await-in-loop+ await approvalPolicyStepApproversDAL.create({ policyStepId: createdStep.id, groupId }, tx);+ }+ }++ await approvalPolicyDAL.updateById(+ policy.id,+ {+ constraints: {+ constraints: {+ maxSignings: effectiveConstraints.maxSignings ?? null,+ maxWindowDuration: effectiveConstraints.maxWindowDuration ?? null+ }+ }+ },+ tx+ );+ }++ return { ...signer, approvalPolicyId: policy.id };});- return signer;+ if (usingCa && resolvedCaId && isExternalCa && resolvedCaType) {+ try {+ await signerIssuanceService.requestIssuance({+ signerId: result.id,+ projectId: dto.projectId,+ caId: resolvedCaId,+ commonName: dto.commonName as string,+ certificateTtlDays: dto.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS,+ keyAlgorithm+ });+ } catch (queueErr) {+ logger.error(+ queueErr,+ `signer create: failed to enqueue async issuance — marking signer Failed [signerId=${result.id}]`+ );+ await signerDAL.updateById(result.id, {+ status: SignerStatus.Failed,+ failureReason: formatSignerIssuanceErrorReason(+ queueErr,+ "Could not schedule issuance from the external Certificate Authority"+ )+ });+ }+ }++ return result;} catch (error) {// 23505 = unique constraint violationif (error instanceof DatabaseError && (error.error as { code?: string })?.code === "23505") {@@ -172,7 +515,7 @@ export const signerServiceFactory = ({};const list = async (dto: TListSignersDTO) => {- const { permission } = await permissionService.getProjectPermission({+ const { permission, hasRole } = await permissionService.getProjectPermission({actor: dto.actor,actorId: dto.actorId,projectId: dto.projectId,@@ -186,15 +529,35 @@ export const signerServiceFactory = ({ProjectPermissionSub.CodeSigners);+ let signerIds: string[] | undefined;+ if (!hasRole(ProjectMembershipRole.Admin)) {+ const memberships = await membershipDAL.findResourceMembershipsForActor({+ projectId: dto.projectId,+ resourceType: ResourceType.Signer,+ actorType: dto.actor === ActorType.IDENTITY ? ActorType.IDENTITY : ActorType.USER,+ actorId: dto.actorId+ });+ signerIds = Array.from(+ new Set(memberships.map((m) => m.scopeResourceId).filter((id): id is string => Boolean(id)))+ );+ if (signerIds.length === 0) {+ return { signers: [], totalCount: 0 };+ }+ }+const signers = await signerDAL.findByProjectId(dto.projectId, {offset: dto.offset,limit: dto.limit,- search: dto.search+ search: dto.search,+ signerIds});- const totalCount = await signerDAL.countByProjectId(dto.projectId, dto.search);+ const totalCount = await signerDAL.countByProjectId(dto.projectId, dto.search, signerIds);- return { signers, totalCount };+ return {+ signers: signers.map((s) => ({ ...s, status: computeEffectiveStatus(s) })),+ totalCount+ };};const getById = async (dto: TGetSignerDTO) => {@@ -203,21 +566,54 @@ export const signerServiceFactory = ({throw new NotFoundError({ message: `Signer with ID '${dto.signerId}' not found` });}- const { permission } = await permissionService.getProjectPermission({- actor: dto.actor,- actorId: dto.actorId,- projectId: signer.projectId,- actorAuthMethod: dto.actorAuthMethod,- actorOrgId: dto.actorOrgId,- actionProjectType: ActionProjectType.CertificateManager- });+ const { permission } = await $loadSignerResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId+ );- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionCodeSigningActions.Read,- ProjectPermissionSub.CodeSigners+ ForbiddenError.from(permission).throwUnlessCan(ResourcePermissionSignerActions.Read, ResourcePermissionSub.Signer);++ return { ...signer, status: computeEffectiveStatus(signer) };+ };++ const getMyPermissions = async (dto: TGetSignerDTO) => {+ const signer = await signerDAL.findById(dto.signerId);+ if (!signer) {+ throw new NotFoundError({ message: `Signer with ID '${dto.signerId}' not found` });+ }++ const { permission } = await $loadSignerResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId);- return signer;+ const allows = (action: ResourcePermissionSignerActions) => permission.can(action, ResourcePermissionSub.Signer);++ const canManageMembers =+ allows(ResourcePermissionSignerActions.ManageMembers) ||+ permission.can(ProjectPermissionMemberActions.Create, ResourcePermissionSub.Member);++ return {+ canRead: allows(ResourcePermissionSignerActions.Read),+ canEdit: allows(ResourcePermissionSignerActions.Edit),+ canDelete: allows(ResourcePermissionSignerActions.Delete),+ canEnableDisable: allows(ResourcePermissionSignerActions.EnableDisable),+ canManageMembers,+ canManagePolicy: allows(ResourcePermissionSignerActions.ManagePolicy),+ canSign: allows(ResourcePermissionSignerActions.Sign),+ canRequestSign: allows(ResourcePermissionSignerActions.RequestSign),+ canPreApprove: allows(ResourcePermissionSignerActions.PreApprove),+ canReissueCertificate: allows(ResourcePermissionSignerActions.ReissueCertificate),+ canExportCertificate: allows(ResourcePermissionSignerActions.ExportCertificate)+ };};const update = async (dto: TUpdateSignerDTO) => {@@ -228,64 +624,41 @@ export const signerServiceFactory = ({const { projectId } = existingSigner;- const { permission } = await permissionService.getProjectPermission({- actor: dto.actor,- actorId: dto.actorId,+ const { permission } = await $loadSignerResourcePermission(+ existingSigner.id,projectId,- actorAuthMethod: dto.actorAuthMethod,- actorOrgId: dto.actorOrgId,- actionProjectType: ActionProjectType.CertificateManager- });-- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionCodeSigningActions.Edit,- ProjectPermissionSub.CodeSigners+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId);- if (dto.certificateId !== undefined) {- const certificate = await certificateDAL.findById(dto.certificateId);- if (!certificate) {- throw new NotFoundError({ message: `Certificate with ID '${dto.certificateId}' not found` });- }- if (certificate.projectId !== projectId) {- throw new BadRequestError({ message: "Certificate must belong to the same project" });- }- if (certificate.status === CertStatus.REVOKED) {- throw new BadRequestError({ message: "Certificate has been revoked" });- }- if (certificate.notAfter && new Date(certificate.notAfter) < new Date()) {- throw new BadRequestError({ message: "Certificate has expired" });- }- const extendedKeyUsages = certificate.extendedKeyUsages as string[] | null;- if (!extendedKeyUsages?.includes(CertExtendedKeyUsage.CODE_SIGNING)) {- throw new BadRequestError({ message: "Certificate must have the codeSigning extended key usage" });+ ForbiddenError.from(permission).throwUnlessCan(ResourcePermissionSignerActions.Edit, ResourcePermissionSub.Signer);++ const patch: Record<string, unknown> = {};+ if (dto.name !== undefined) patch.name = dto.name;+ if (dto.description !== undefined) patch.description = dto.description;+ if (dto.renewBeforeDays !== undefined) {+ if (dto.renewBeforeDays === null) {+ patch.renewBeforeDays = null;+ } else {+ if (dto.renewBeforeDays < 1 || dto.renewBeforeDays > 30) {+ throw new BadRequestError({ message: "Renew before must be between 1 and 30 days." });+ }+ if (existingSigner.certificateTtlDays != null && dto.renewBeforeDays >= existingSigner.certificateTtlDays) {+ throw new BadRequestError({+ message: `Renew before (${dto.renewBeforeDays}d) must be less than the certificate validity (${existingSigner.certificateTtlDays}d).`+ });+ }+ patch.renewBeforeDays = dto.renewBeforeDays;}}- if (dto.approvalPolicyId !== undefined && dto.approvalPolicyId !== null) {- const approvalPolicy = await approvalPolicyDAL.findById(dto.approvalPolicyId);- if (!approvalPolicy) {- throw new NotFoundError({ message: `Approval policy with ID '${dto.approvalPolicyId}' not found` });- }- if (approvalPolicy.projectId !== projectId) {- throw new BadRequestError({ message: "Approval policy must belong to the same project" });- }- if (approvalPolicy.type !== ApprovalPolicyType.CertCodeSigning) {- throw new BadRequestError({- message: "Approval policy must be of type cert-code-signing"- });- }+ if (Object.keys(patch).length === 0) {+ return existingSigner;}- const signer = await signerDAL.updateById(dto.signerId, {- name: dto.name,- description: dto.description,- status: dto.status,- certificateId: dto.certificateId,- approvalPolicyId: dto.approvalPolicyId- });-- return signer;+ return signerDAL.updateById(dto.signerId, patch);};const deleteSigner = async (dto: TDeleteSignerDTO) => {@@ -294,24 +667,274 @@ export const signerServiceFactory = ({throw new NotFoundError({ message: `Signer with ID '${dto.signerId}' not found` });}- const { permission } = await permissionService.getProjectPermission({- actor: dto.actor,- actorId: dto.actorId,- projectId: existingSigner.projectId,- actorAuthMethod: dto.actorAuthMethod,- actorOrgId: dto.actorOrgId,- actionProjectType: ActionProjectType.CertificateManager- });+ const { permission } = await $loadSignerResourcePermission(+ existingSigner.id,+ existingSigner.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId+ );ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionCodeSigningActions.Delete,- ProjectPermissionSub.CodeSigners+ ResourcePermissionSignerActions.Delete,+ ResourcePermissionSub.Signer);- await signerDAL.deleteById(dto.signerId);+ await signerDAL.transaction(async (tx) => {+ const memberships = await membershipDAL.find(+ {+ scope: RESOURCE_SCOPE,+ scopeResourceType: ResourceType.Signer,+ scopeResourceId: existingSigner.id+ },+ { tx }+ );+ if (memberships.length > 0) {+ const ids = memberships.map((m) => m.id);+ await membershipRoleDAL.delete({ $in: { membershipId: ids } }, tx);+ await membershipDAL.delete({ $in: { id: ids } }, tx);+ }++ await approvalRequestDAL.delete({ scopeType: ApprovalPolicyScope.Signer, scopeId: existingSigner.id }, tx);++ await signerDAL.deleteById(dto.signerId, tx);++ await approvalPolicyDAL.delete({ scopeType: ApprovalPolicyScope.Signer, scopeId: existingSigner.id }, tx);+ });+return existingSigner;};+ const enable = async (dto: TEnableSignerDTO) => {+ const signer = await signerDAL.findById(dto.signerId);+ if (!signer) throw new NotFoundError({ message: `Signer with ID '${dto.signerId}' not found` });++ const { permission } = await $loadSignerResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId+ );+ ForbiddenError.from(permission).throwUnlessCan(+ ResourcePermissionSignerActions.EnableDisable,+ ResourcePermissionSub.Signer+ );++ if (signer.status !== SignerStatus.Disabled) {+ throw new BadRequestError({+ message: `Signer '${signer.name}' is not disabled (current status: ${signer.status}).`+ });+ }+ if (!signer.certificateId) {+ throw new BadRequestError({+ message: `Signer '${signer.name}' has no certificate. Reissue from a CA before enabling.`+ });+ }+ return signerDAL.updateById(dto.signerId, { status: SignerStatus.Active });+ };++ const disable = async (dto: TDisableSignerDTO) => {+ const signer = await signerDAL.findById(dto.signerId);+ if (!signer) throw new NotFoundError({ message: `Signer with ID '${dto.signerId}' not found` });++ const { permission } = await $loadSignerResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId+ );+ ForbiddenError.from(permission).throwUnlessCan(+ ResourcePermissionSignerActions.EnableDisable,+ ResourcePermissionSub.Signer+ );++ if (signer.status === SignerStatus.Disabled) return signer;+ return signerDAL.updateById(dto.signerId, { status: SignerStatus.Disabled });+ };++ const reissueCertificate = async (dto: TReissueCertificateDTO) => {+ const signer = await signerDAL.findById(dto.signerId);+ if (!signer) throw new NotFoundError({ message: `Signer with ID '${dto.signerId}' not found` });++ const { permission } = await $loadSignerResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId+ );+ ForbiddenError.from(permission).throwUnlessCan(+ ResourcePermissionSignerActions.ReissueCertificate,+ ResourcePermissionSub.Signer+ );++ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(dto.caId);+ if (!ca || ca.projectId !== signer.projectId) {+ throw new NotFoundError({ message: `Certificate authority '${dto.caId}' not found in this project.` });+ }+ if (ca.status !== CaStatus.ACTIVE) {+ throw new BadRequestError({ message: "The selected certificate authority is not active." });+ }++ const reissueCaType: CaType = (ca.externalCa?.type as CaType | undefined) ?? CaType.INTERNAL;+ const reissueIsExternal = reissueCaType !== CaType.INTERNAL;++ const allowsResubject = signer.status === SignerStatus.Pending || signer.status === SignerStatus.Failed;+ let nextCommonName = signer.commonName;+ let nextTtl = signer.certificateTtlDays;+ if (allowsResubject) {+ if (dto.commonName !== undefined) nextCommonName = dto.commonName;+ if (dto.certificateTtlDays !== undefined) nextTtl = dto.certificateTtlDays;+ } else if (dto.commonName !== undefined || dto.certificateTtlDays !== undefined) {+ throw new BadRequestError({+ message: "Common Name and validity are fixed for an active signer. Create a new signer to change them."+ });+ }++ if (!nextCommonName) {+ throw new BadRequestError({+ message: "Signer has no common name configured; cannot issue a certificate."+ });+ }++ const effectiveTtl = nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS;+ if (signer.renewBeforeDays != null && signer.renewBeforeDays >= effectiveTtl) {+ throw new BadRequestError({+ message: `Certificate validity (${effectiveTtl}d) must be greater than the configured renew before (${signer.renewBeforeDays}d). Update the renew-before window before reissuing with a shorter validity.`+ });+ }++ await signerDAL.updateById(dto.signerId, {+ caId: dto.caId,+ commonName: nextCommonName,+ certificateTtlDays: effectiveTtl+ });++ const reissueKeyAlgorithm: CertKeyAlgorithm =+ (signer.keyAlgorithm as CertKeyAlgorithm) ?? CertKeyAlgorithm.RSA_2048;++ if (reissueIsExternal) {+ await signerDAL.updateById(dto.signerId, {+ status: SignerStatus.Pending,+ failureReason: null+ });+ try {+ await signerIssuanceService.requestIssuance({+ signerId: signer.id,+ projectId: signer.projectId,+ caId: dto.caId,+ commonName: nextCommonName,+ certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,+ keyAlgorithm: reissueKeyAlgorithm+ });+ return await signerDAL.findById(dto.signerId);+ } catch (queueErr) {+ await signerDAL.updateById(dto.signerId, {+ status: SignerStatus.Failed,+ failureReason: formatSignerIssuanceErrorReason(+ queueErr,+ "Could not schedule re-issuance from the external Certificate Authority"+ )+ });+ throw queueErr;+ }+ }++ try {+ const { certificateId } = await issueSignerCertificate(+ {+ certificateAuthorityDAL,+ internalCertificateAuthorityService,+ certificateBodyDAL,+ certificateSecretDAL,+ projectDAL,+ kmsService+ },+ {+ caId: dto.caId,+ projectId: signer.projectId,+ commonName: nextCommonName,+ certificateTtlDays: nextTtl ?? DEFAULT_CERTIFICATE_TTL_DAYS,+ keyAlgorithm: reissueKeyAlgorithm+ }+ );++ return await signerDAL.updateById(dto.signerId, {+ certificateId,+ status: SignerStatus.Active,+ failureReason: null+ });+ } catch (issueErr) {+ logger.error(+ issueErr,+ `signer reissue: certificate issuance failed for signer '${signer.name}' [signerId=${signer.id}]`+ );+ await signerDAL.updateById(dto.signerId, {+ status: SignerStatus.Failed,+ failureReason: formatSignerIssuanceErrorReason(issueErr, "Internal CA certificate issuance failed")+ });+ throw issueErr;+ }+ };++ const exportCertificate = async (dto: TExportCertificateDTO) => {+ const signer = await signerDAL.findByIdWithCertificate(dto.signerId);+ if (!signer) throw new NotFoundError({ message: `Signer with ID '${dto.signerId}' not found` });++ const { permission } = await $loadSignerResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId+ );+ ForbiddenError.from(permission).throwUnlessCan(+ ResourcePermissionSignerActions.ExportCertificate,+ ResourcePermissionSub.Signer+ );++ if (!signer.certificateId) {+ throw new BadRequestError({ message: `Signer '${signer.name}' has no certificate attached yet.` });+ }++ const certBody = await certificateBodyDAL.findOne({ certId: signer.certificateId });+ if (!certBody?.encryptedCertificate) {+ throw new BadRequestError({+ message: `Certificate body not found for signer '${signer.name}'.`+ });+ }++ const keyId = await getProjectKmsCertificateKeyId({+ projectId: signer.projectId,+ projectDAL,+ kmsService+ });+ const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId: keyId });+ const decryptedCert = await kmsDecryptor({ cipherTextBlob: certBody.encryptedCertificate });+ const cert = new x509.X509Certificate(decryptedCert);+ const certificatePem = cert.toString("pem");+ const serialNumber = (cert.serialNumber || "").replace(/^0x/i, "").toLowerCase();++ return {+ certificatePem,+ serialNumber,+ signerName: signer.name,+ projectId: signer.projectId+ };+ };++ const $countPolicySteps = async (policyId: string): Promise<number> => {+ const steps = await approvalPolicyDAL.findStepsByPolicyId(policyId);+ return steps.length;+ };+const sign = async (dto: TSignDataDTO) => {const signer = await signerDAL.findByIdWithCertificate(dto.signerId);if (!signer) {@@ -320,26 +943,30 @@ export const signerServiceFactory = ({const { projectId } = signer;- const { permission } = await permissionService.getProjectPermission({- actor: dto.actor,- actorId: dto.actorId,+ const { permission } = await $loadSignerResourcePermission(+ signer.id,projectId,- actorAuthMethod: dto.actorAuthMethod,- actorOrgId: dto.actorOrgId,- actionProjectType: ActionProjectType.CertificateManager- });-- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionCodeSigningActions.Sign,- ProjectPermissionSub.CodeSigners+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId);+ ForbiddenError.from(permission).throwUnlessCan(ResourcePermissionSignerActions.Sign, ResourcePermissionSub.Signer);if (signer.status !== SignerStatus.Active) {throw new BadRequestError({ message: `Signer '${signer.name}' is not active (status: ${signer.status})` });}+ if (!signer.certificateId) {+ throw new BadRequestError({ message: `Signer '${signer.name}' has no certificate attached.` });+ }if (signer.certificateNotAfter && new Date() > new Date(signer.certificateNotAfter)) {throw new BadRequestError({ message: `Certificate for signer '${signer.name}' has expired` });}+ if (signer.certificateStatus === CertStatus.REVOKED) {+ throw new BadRequestError({+ message: `Certificate for signer '${signer.name}' has been revoked. Reissue from a CA before signing.`+ });+ }const dataBuffer = Buffer.from(dto.data, "base64");if (dataBuffer.length > MAX_DATA_BYTES) {@@ -364,10 +991,10 @@ export const signerServiceFactory = ({type: "pkcs8"});- const keyAlgorithm = getKeyAlgorithm(privateKeyObject);+ const keyAlgorithm = getKeyAlgorithmFamily(privateKeyObject);validateSigningAlgorithmForKey(dto.signingAlgorithm, keyAlgorithm);- const requiresApproval = Boolean(signer.approvalPolicyId);+ const requiresApproval = signer.approvalPolicyId ? (await $countPolicySteps(signer.approvalPolicyId)) > 0 : false;const result = await projectDAL.transaction(async (tx) => {let grantId: string | null = null;@@ -530,19 +1157,19 @@ export const signerServiceFactory = ({const { projectId } = signer;- const { permission } = await permissionService.getProjectPermission({- actor: dto.actor,- actorId: dto.actorId,+ const { permission } = await $loadSignerResourcePermission(+ signer.id,projectId,- actorAuthMethod: dto.actorAuthMethod,- actorOrgId: dto.actorOrgId,- actionProjectType: ActionProjectType.CertificateManager- });-- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionCodeSigningActions.Read,- ProjectPermissionSub.CodeSigners+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId);+ ForbiddenError.from(permission).throwUnlessCan(ResourcePermissionSignerActions.Read, ResourcePermissionSub.Signer);++ if (!signer.certificateId) {+ throw new BadRequestError({ message: `Signer '${signer.name}' has no certificate attached yet.` });+ }const { certPublicKey } = await getCertificateCredentials({certId: signer.certificateId,@@ -567,7 +1194,7 @@ export const signerServiceFactory = ({const publicKeyDer = publicKeyObject.export({ format: "der", type: "spki" });- const keyAlgorithm = getKeyAlgorithm(publicKeyObject);+ const keyAlgorithm = getKeyAlgorithmFamily(publicKeyObject);return {publicKey: publicKeyDer.toString("base64"),@@ -583,19 +1210,15 @@ export const signerServiceFactory = ({throw new NotFoundError({ message: `Signer with ID '${dto.signerId}' not found` });}- const { permission } = await permissionService.getProjectPermission({- actor: dto.actor,- actorId: dto.actorId,- projectId: signer.projectId,- actorAuthMethod: dto.actorAuthMethod,- actorOrgId: dto.actorOrgId,- actionProjectType: ActionProjectType.CertificateManager- });-- ForbiddenError.from(permission).throwUnlessCan(- ProjectPermissionCodeSigningActions.Read,- ProjectPermissionSub.CodeSigners+ const { permission } = await $loadSignerResourcePermission(+ signer.id,+ signer.projectId,+ dto.actor,+ dto.actorId,+ dto.actorAuthMethod,+ dto.actorOrgId);+ ForbiddenError.from(permission).throwUnlessCan(ResourcePermissionSignerActions.Read, ResourcePermissionSub.Signer);const operations = await signingOperationDAL.findBySignerId(dto.signerId, {offset: dto.offset,@@ -608,14 +1231,144 @@ export const signerServiceFactory = ({return { operations, totalCount, projectId: signer.projectId };};+ const attachIssuedCertificate = async (+ signerId: string,+ certificateId: string,+ tx?: Parameters<TSignerDALFactory["updateById"]>[2]+ ) => {+ return signerDAL.updateById(signerId, { certificateId, status: SignerStatus.Active, failureReason: null }, tx);+ };++ const markIssuanceFailed = async (+ signerId: string,+ reason?: string,+ tx?: Parameters<TSignerDALFactory["updateById"]>[2]+ ) => {+ return signerDAL.updateById(+ signerId,+ { status: SignerStatus.Failed, failureReason: reason ? reason.slice(0, 1000) : null },+ tx+ );+ };++ const autoRenewCertificate = async (signerId: string) => {+ const signer = await signerDAL.findById(signerId);+ if (!signer) {+ logger.warn(`signer auto-renewal: signer '${signerId}' not found, skipping`);+ return;+ }+ if (!signer.caId) {+ logger.warn(+ `signer auto-renewal: signer '${signer.name}' [signerId=${signer.id}] has no CA configured, skipping`+ );+ return;+ }+ if (!signer.commonName) {+ logger.warn(`signer auto-renewal: signer '${signer.name}' [signerId=${signer.id}] has no common name, skipping`);+ return;+ }++ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(signer.caId);+ if (!ca || ca.projectId !== signer.projectId) {+ const reason = `Certificate authority '${signer.caId}' is no longer available in the project.`;+ logger.warn(`signer auto-renewal: ${reason} [signerId=${signer.id}]`);+ await signerDAL.updateById(signer.id, {+ status: SignerStatus.Failed,+ failureReason: reason.slice(0, 1000)+ });+ return;+ }+ if (ca.status !== CaStatus.ACTIVE) {+ const reason = `Certificate authority '${ca.name}' is not active.`;+ await signerDAL.updateById(signer.id, {+ status: SignerStatus.Failed,+ failureReason: reason.slice(0, 1000)+ });+ return;+ }++ const isExternal = Boolean(ca.externalCa?.type) && ca.externalCa?.type !== CaType.INTERNAL;+ const ttlDays = signer.certificateTtlDays ?? DEFAULT_CERTIFICATE_TTL_DAYS;+ const renewKeyAlgorithm: CertKeyAlgorithm = (signer.keyAlgorithm as CertKeyAlgorithm) ?? CertKeyAlgorithm.RSA_2048;++ if (isExternal) {+ await signerDAL.updateById(signer.id, {+ status: SignerStatus.Pending,+ failureReason: null+ });+ try {+ await signerIssuanceService.requestIssuance({+ signerId: signer.id,+ projectId: signer.projectId,+ caId: signer.caId,+ commonName: signer.commonName,+ certificateTtlDays: ttlDays,+ keyAlgorithm: renewKeyAlgorithm+ });+ } catch (err) {+ await signerDAL.updateById(signer.id, {+ status: SignerStatus.Failed,+ failureReason: formatSignerIssuanceErrorReason(+ err,+ "Could not schedule auto-renewal from the external Certificate Authority"+ )+ });+ logger.error(err, `signer auto-renewal: failed to enqueue external CA issuance [signerId=${signer.id}]`);+ }+ return;+ }++ try {+ const { certificateId } = await issueSignerCertificate(+ {+ certificateAuthorityDAL,+ internalCertificateAuthorityService,+ certificateBodyDAL,+ certificateSecretDAL,+ projectDAL,+ kmsService+ },+ {+ caId: signer.caId,+ projectId: signer.projectId,+ commonName: signer.commonName,+ certificateTtlDays: ttlDays,+ keyAlgorithm: renewKeyAlgorithm+ }+ );+ await signerDAL.updateById(signer.id, {+ certificateId,+ status: SignerStatus.Active,+ failureReason: null+ });+ logger.info(+ `signer auto-renewal: renewed signer '${signer.name}' [signerId=${signer.id}] [newCertificateId=${certificateId}]`+ );+ } catch (err) {+ await signerDAL.updateById(signer.id, {+ status: SignerStatus.Failed,+ failureReason: formatSignerIssuanceErrorReason(err, "Internal CA auto-renewal failed")+ });+ logger.error(err, `signer auto-renewal: internal CA issuance failed [signerId=${signer.id}]`);+ }+ };+return {create,list,getById,+ getMyPermissions,update,delete: deleteSigner,+ enable,+ disable,+ reissueCertificate,+ exportCertificate,sign,getPublicKey,- listOperations+ listOperations,+ attachIssuedCertificate,+ markIssuanceFailed,+ autoRenewCertificate};};diff --git a/backend/src/services/signer/signer-types.ts b/backend/src/services/signer/signer-types.tsindex fdcf707133..0d5aab1257 100644--- a/backend/src/services/signer/signer-types.ts+++ b/backend/src/services/signer/signer-types.ts@@ -1,24 +1,41 @@import { SigningAlgorithm } from "@app/lib/crypto/sign/types";import { TProjectPermission } from "@app/lib/types";+import { CertKeyAlgorithm } from "../certificate/certificate-types";import { SignerStatus, SigningOperationStatus } from "./signer-enums";type TActorPermission = Omit<TProjectPermission, "projectId">;+export type TCreateSignerMemberInput = {+ kind: "user" | "identity" | "group";+ id: string;+ role: string;+};++export type TCreateSignerApprovalPolicyInput = {+ steps: TSignerPolicyStepInput[];+ constraints?: TSignerPolicyConstraints;+};+export type TCreateSignerDTO = {name: string;description?: string;- certificateId: string;+ caId?: string;+ commonName?: string;+ certificateTtlDays?: number;+ renewBeforeDays?: number | null;+ keyAlgorithm?: CertKeyAlgorithm;+ certificateId?: string;approvalPolicyId?: string;+ members?: TCreateSignerMemberInput[];+ approvalPolicy?: TCreateSignerApprovalPolicyInput;} & TProjectPermission;export type TUpdateSignerDTO = {signerId: string;name?: string;description?: string | null;- status?: SignerStatus;- certificateId?: string;- approvalPolicyId?: string | null;+ renewBeforeDays?: number | null;} & TActorPermission;export type TDeleteSignerDTO = {@@ -58,3 +75,79 @@ export type TListSigningOperationsDTO = {limit?: number;status?: SigningOperationStatus;} & TActorPermission;++export type TEnableSignerDTO = {+ signerId: string;+} & TActorPermission;++export type TDisableSignerDTO = {+ signerId: string;+} & TActorPermission;++export type TReissueCertificateDTO = {+ signerId: string;+ caId: string;+ commonName?: string;+ certificateTtlDays?: number;+} & TActorPermission;++export type TExportCertificateDTO = {+ signerId: string;+} & TActorPermission;++export type TSignerPolicyStepInput = {+ stepNumber: number;+ name?: string | null;+ requiredApprovals: number;+ approverUserIds: string[];+ approverGroupIds?: string[];+};++export type TSignerPolicyConstraints = {+ maxSignings?: number | null;+ maxWindowDuration?: string | null;+};++export type TGetSignerPolicyDTO = {+ signerId: string;+} & TActorPermission;++export type TUpdateSignerPolicyDTO = {+ signerId: string;+ steps: TSignerPolicyStepInput[];+ constraints?: TSignerPolicyConstraints;+} & TActorPermission;++export type TSignerRequestStatusFilter = "pending" | "approved" | "expired" | "revoked";++export type TListSignerRequestsDTO = {+ signerId: string;+ statuses?: TSignerRequestStatusFilter[];+ offset?: number;+ limit?: number;+} & TActorPermission;++export type TRequestToSignDTO = {+ signerId: string;+ justification: string;+ requestedSignings?: number;+ requestedWindowStart?: string;+ requestedWindowEnd?: string;+} & TActorPermission;++export type TPreApproveSigningDTO = {+ signerId: string;+ granteeUserId?: string;+ granteeIdentityId?: string;+ justification: string;+ requestedSignings?: number;+ requestedWindowStart?: string;+ requestedWindowEnd?: string;+} & TActorPermission;++export type TRevokeSignerRequestDTO = {+ signerId: string;+ requestId: string;+} & TActorPermission;++export type { SignerStatus };diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 2dac2f4b58..5e4fb275b7 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -18,7 +18,7 @@ services:ports:- "5432:5432"volumes:- - postgres-data:/var/lib/postgresql/data+ - postgres-data-2:/var/lib/postgresql/dataenvironment:POSTGRES_PASSWORD: infisicalPOSTGRES_USER: infisical@@ -254,7 +254,7 @@ services:profiles: [sso]volumes:- postgres-data:+ postgres-data-2:driver: localredis_data:driver: localdiff --git a/frontend/src/components/v3/generic/ReactSelect/styles.ts b/frontend/src/components/v3/generic/ReactSelect/styles.tsindex c27b5348ce..118b4090ed 100644--- a/frontend/src/components/v3/generic/ReactSelect/styles.ts+++ b/frontend/src/components/v3/generic/ReactSelect/styles.ts@@ -32,7 +32,9 @@ export const selectClassNames: ClassNamesConfig<unknown, boolean, GroupBase<unknclearIndicator: () =>"opacity-50 hover:opacity-100 hover:bg-foreground/10 cursor-pointer rounded-md p-1 text-danger [&>svg]:size-4",noOptionsMessage: () => "text-muted p-2 text-sm",- loadingMessage: () => "text-muted p-2 text-sm"+ loadingMessage: () => "text-muted p-2 text-sm",+ group: () => "pb-1",+ groupHeading: () => "px-2 pt-2 pb-1 text-xs font-medium text-muted"};export const selectStyles: StylesConfig<unknown, boolean, GroupBase<unknown>> = {diff --git a/frontend/src/const/routes.ts b/frontend/src/const/routes.tsindex 9ba139014b..c57aa8c15c 100644--- a/frontend/src/const/routes.ts+++ b/frontend/src/const/routes.ts@@ -354,6 +354,10 @@ export const ROUTE_PATHS = Object.freeze({SignerDetailByIDPage: setRoute("/organizations/$orgId/projects/cert-manager/$projectId/code-signing/$signerId","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/code-signing/$signerId"+ ),+ CodeSigningPage: setRoute(+ "/organizations/$orgId/projects/cert-manager/$projectId/code-signing",+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/code-signing")},Ssh: {diff --git a/frontend/src/hooks/api/approvalRequests/mutations.tsx b/frontend/src/hooks/api/approvalRequests/mutations.tsxindex f975ca0a31..e4c73c91f5 100644--- a/frontend/src/hooks/api/approvalRequests/mutations.tsx+++ b/frontend/src/hooks/api/approvalRequests/mutations.tsx@@ -1,6 +1,7 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";+import { signerKeys } from "@app/hooks/api/signers/queries";import { approvalRequestQuery } from "./queries";import {@@ -11,6 +12,11 @@ import {TRejectApprovalRequestDTO} from "./types";+const invalidateApprovalRequests = (queryClient: ReturnType<typeof useQueryClient>) => {+ queryClient.invalidateQueries({ queryKey: approvalRequestQuery.allKey() });+ queryClient.invalidateQueries({ queryKey: signerKeys.requestsAll() });+};+export const useCreateApprovalRequest = () => {const queryClient = useQueryClient();return useMutation({@@ -21,9 +27,7 @@ export const useCreateApprovalRequest = () => {);return data.request;},- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: approvalRequestQuery.allKey() });- }+ onSuccess: () => invalidateApprovalRequests(queryClient)});};@@ -42,9 +46,7 @@ export const useApproveApprovalRequest = () => {);return data.request;},- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: approvalRequestQuery.allKey() });- }+ onSuccess: () => invalidateApprovalRequests(queryClient)});};@@ -58,9 +60,7 @@ export const useRejectApprovalRequest = () => {);return data.request;},- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: approvalRequestQuery.allKey() });- }+ onSuccess: () => invalidateApprovalRequests(queryClient)});};@@ -73,8 +73,6 @@ export const useCancelApprovalRequest = () => {);return data.request;},- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: approvalRequestQuery.allKey() });- }+ onSuccess: () => invalidateApprovalRequests(queryClient)});};diff --git a/frontend/src/hooks/api/signers/constants.ts b/frontend/src/hooks/api/signers/constants.tsnew file mode 100644index 0000000000..119ed35d09--- /dev/null+++ b/frontend/src/hooks/api/signers/constants.ts@@ -0,0 +1 @@+export const SIGNER_TABLE_PAGE_SIZE = 25;diff --git a/frontend/src/hooks/api/signers/index.tsx b/frontend/src/hooks/api/signers/index.tsxindex 542b3d3ee5..b6e87e156c 100644--- a/frontend/src/hooks/api/signers/index.tsx+++ b/frontend/src/hooks/api/signers/index.tsx@@ -1,8 +1,36 @@-export { useCreateSigner, useDeleteSigner, useUpdateSigner } from "./mutations";+export * from "./constants";+export {+ useAddSignerGroupMember,+ useAddSignerIdentityMember,+ useAddSignerUserMembers,+ useCreateSigner,+ useDeleteSigner,+ useDisableSigner,+ useEnableSigner,+ usePreApproveSigning,+ useReissueSignerCertificate,+ useRemoveSignerGroupMember,+ useRemoveSignerIdentityMember,+ useRemoveSignerUserMember,+ useRequestToSign,+ useRevokeSignerRequest,+ useUpdateSigner,+ useUpdateSignerGroupRole,+ useUpdateSignerIdentityRole,+ useUpdateSignerPolicy,+ useUpdateSignerUserRole+} from "./mutations";+export type { TSignerMyPermissions } from "./queries";export {signerKeys,+ useExportSignerCertificate,useGetSigner,+ useGetSignerMyPermissions,+ useGetSignerPolicy,useGetSignerPublicKey,+ useListEffectiveSignerMembers,+ useListSignerMembers,+ useListSignerRequests,useListSigners,useListSigningOperations} from "./queries";diff --git a/frontend/src/hooks/api/signers/mutations.tsx b/frontend/src/hooks/api/signers/mutations.tsxindex d7f42a1f46..a409d3afe4 100644--- a/frontend/src/hooks/api/signers/mutations.tsx+++ b/frontend/src/hooks/api/signers/mutations.tsx@@ -2,9 +2,33 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { createNotification } from "@app/components/notifications";import { apiRequest } from "@app/config/request";+import { approvalRequestQuery } from "@app/hooks/api/approvalRequests/queries";import { signerKeys } from "./queries";-import { TCreateSignerDTO, TDeleteSignerDTO, TSigner, TUpdateSignerDTO } from "./types";+import {+ TAddSignerGroupMemberDTO,+ TAddSignerIdentityMemberDTO,+ TAddSignerUserMembersDTO,+ TCreateSignerDTO,+ TDeleteSignerDTO,+ TDisableSignerDTO,+ TEnableSignerDTO,+ TPreApproveSigningDTO,+ TReissueSignerCertificateDTO,+ TRemoveSignerGroupDTO,+ TRemoveSignerIdentityDTO,+ TRemoveSignerUserDTO,+ TRequestToSignDTO,+ TRevokeSignerRequestDTO,+ TSigner,+ TSignerMember,+ TSignerPolicy,+ TUpdateSignerDTO,+ TUpdateSignerGroupRoleDTO,+ TUpdateSignerIdentityRoleDTO,+ TUpdateSignerPolicyDTO,+ TUpdateSignerUserRoleDTO+} from "./types";export const useCreateSigner = () => {const queryClient = useQueryClient();@@ -54,3 +78,309 @@ export const useDeleteSigner = () => {}});};++export const useEnableSigner = () => {+ const queryClient = useQueryClient();++ return useMutation<TSigner, object, TEnableSignerDTO>({+ mutationFn: async ({ signerId }) => {+ const { data } = await apiRequest.post<TSigner>(+ `/api/v1/cert-manager/signers/${signerId}/enable`+ );+ return data;+ },+ onSuccess: (signer) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.byId(signer.id) });+ queryClient.invalidateQueries({ queryKey: signerKeys.list(signer.projectId) });+ createNotification({ text: "Signer enabled", type: "success" });+ }+ });+};++export const useDisableSigner = () => {+ const queryClient = useQueryClient();++ return useMutation<TSigner, object, TDisableSignerDTO>({+ mutationFn: async ({ signerId }) => {+ const { data } = await apiRequest.post<TSigner>(+ `/api/v1/cert-manager/signers/${signerId}/disable`+ );+ return data;+ },+ onSuccess: (signer) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.byId(signer.id) });+ queryClient.invalidateQueries({ queryKey: signerKeys.list(signer.projectId) });+ createNotification({ text: "Signer disabled", type: "success" });+ }+ });+};++export const useReissueSignerCertificate = () => {+ const queryClient = useQueryClient();++ return useMutation<TSigner, object, TReissueSignerCertificateDTO>({+ mutationFn: async ({ signerId, ...body }) => {+ const { data } = await apiRequest.post<TSigner>(+ `/api/v1/cert-manager/signers/${signerId}/certificate/reissue`,+ body+ );+ return data;+ },+ onSuccess: (signer) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.byId(signer.id) });+ queryClient.invalidateQueries({ queryKey: signerKeys.list(signer.projectId) });+ queryClient.invalidateQueries({ queryKey: signerKeys.certificate(signer.id) });+ createNotification({ text: "Certificate re-issue scheduled", type: "success" });+ }+ });+};++export const useAddSignerUserMembers = () => {+ const queryClient = useQueryClient();++ return useMutation<unknown, object, TAddSignerUserMembersDTO>({+ mutationFn: async ({ signerId, ...body }) => {+ const { data } = await apiRequest.post(+ `/api/v1/cert-manager/signers/${signerId}/users`,+ body+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.members(signerId, "user") });+ queryClient.invalidateQueries({ queryKey: signerKeys.effectiveMembersAll(signerId) });+ queryClient.invalidateQueries({ queryKey: signerKeys.policy(signerId) });+ createNotification({ text: "Members added", type: "success" });+ }+ });+};++export const useUpdateSignerUserRole = () => {+ const queryClient = useQueryClient();++ return useMutation<{ membership: TSignerMember }, object, TUpdateSignerUserRoleDTO>({+ mutationFn: async ({ signerId, userId, role }) => {+ const { data } = await apiRequest.patch<{ membership: TSignerMember }>(+ `/api/v1/cert-manager/signers/${signerId}/users/${userId}`,+ { role }+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.members(signerId, "user") });+ queryClient.invalidateQueries({ queryKey: signerKeys.effectiveMembersAll(signerId) });+ queryClient.invalidateQueries({ queryKey: signerKeys.policy(signerId) });+ createNotification({ text: "Role updated", type: "success" });+ }+ });+};++export const useRemoveSignerUserMember = () => {+ const queryClient = useQueryClient();++ return useMutation<unknown, object, TRemoveSignerUserDTO>({+ mutationFn: async ({ signerId, userId }) => {+ const { data } = await apiRequest.delete(+ `/api/v1/cert-manager/signers/${signerId}/users/${userId}`+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.members(signerId, "user") });+ queryClient.invalidateQueries({ queryKey: signerKeys.effectiveMembersAll(signerId) });+ queryClient.invalidateQueries({ queryKey: signerKeys.policy(signerId) });+ createNotification({ text: "Member removed", type: "success" });+ }+ });+};++export const useAddSignerIdentityMember = () => {+ const queryClient = useQueryClient();++ return useMutation<TSignerMember, object, TAddSignerIdentityMemberDTO>({+ mutationFn: async ({ signerId, identityId, role }) => {+ const { data } = await apiRequest.post<TSignerMember>(+ `/api/v1/cert-manager/signers/${signerId}/identities`,+ { identityId, role }+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.members(signerId, "identity") });+ queryClient.invalidateQueries({ queryKey: signerKeys.effectiveMembersAll(signerId) });+ queryClient.invalidateQueries({ queryKey: signerKeys.policy(signerId) });+ }+ });+};++export const useUpdateSignerIdentityRole = () => {+ const queryClient = useQueryClient();++ return useMutation<{ membership: TSignerMember }, object, TUpdateSignerIdentityRoleDTO>({+ mutationFn: async ({ signerId, identityId, role }) => {+ const { data } = await apiRequest.patch<{ membership: TSignerMember }>(+ `/api/v1/cert-manager/signers/${signerId}/identities/${identityId}`,+ { role }+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.members(signerId, "identity") });+ queryClient.invalidateQueries({ queryKey: signerKeys.effectiveMembersAll(signerId) });+ queryClient.invalidateQueries({ queryKey: signerKeys.policy(signerId) });+ createNotification({ text: "Role updated", type: "success" });+ }+ });+};++export const useRemoveSignerIdentityMember = () => {+ const queryClient = useQueryClient();++ return useMutation<unknown, object, TRemoveSignerIdentityDTO>({+ mutationFn: async ({ signerId, identityId }) => {+ const { data } = await apiRequest.delete(+ `/api/v1/cert-manager/signers/${signerId}/identities/${identityId}`+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.members(signerId, "identity") });+ queryClient.invalidateQueries({ queryKey: signerKeys.effectiveMembersAll(signerId) });+ queryClient.invalidateQueries({ queryKey: signerKeys.policy(signerId) });+ createNotification({ text: "Member removed", type: "success" });+ }+ });+};++export const useAddSignerGroupMember = () => {+ const queryClient = useQueryClient();++ return useMutation<TSignerMember, object, TAddSignerGroupMemberDTO>({+ mutationFn: async ({ signerId, groupId, role }) => {+ const { data } = await apiRequest.post<TSignerMember>(+ `/api/v1/cert-manager/signers/${signerId}/groups`,+ { groupId, role }+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.members(signerId, "group") });+ queryClient.invalidateQueries({ queryKey: signerKeys.effectiveMembersAll(signerId) });+ queryClient.invalidateQueries({ queryKey: signerKeys.policy(signerId) });+ }+ });+};++export const useUpdateSignerGroupRole = () => {+ const queryClient = useQueryClient();++ return useMutation<{ membership: TSignerMember }, object, TUpdateSignerGroupRoleDTO>({+ mutationFn: async ({ signerId, groupId, role }) => {+ const { data } = await apiRequest.patch<{ membership: TSignerMember }>(+ `/api/v1/cert-manager/signers/${signerId}/groups/${groupId}`,+ { role }+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.members(signerId, "group") });+ queryClient.invalidateQueries({ queryKey: signerKeys.effectiveMembersAll(signerId) });+ queryClient.invalidateQueries({ queryKey: signerKeys.policy(signerId) });+ createNotification({ text: "Role updated", type: "success" });+ }+ });+};++export const useRemoveSignerGroupMember = () => {+ const queryClient = useQueryClient();++ return useMutation<unknown, object, TRemoveSignerGroupDTO>({+ mutationFn: async ({ signerId, groupId }) => {+ const { data } = await apiRequest.delete(+ `/api/v1/cert-manager/signers/${signerId}/groups/${groupId}`+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.members(signerId, "group") });+ queryClient.invalidateQueries({ queryKey: signerKeys.effectiveMembersAll(signerId) });+ queryClient.invalidateQueries({ queryKey: signerKeys.policy(signerId) });+ createNotification({ text: "Member removed", type: "success" });+ }+ });+};++export const useUpdateSignerPolicy = () => {+ const queryClient = useQueryClient();++ return useMutation<TSignerPolicy, object, TUpdateSignerPolicyDTO>({+ mutationFn: async ({ signerId, ...body }) => {+ const { data } = await apiRequest.patch<TSignerPolicy>(+ `/api/v1/cert-manager/signers/${signerId}/approval-policy`,+ body+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.policy(signerId) });+ queryClient.invalidateQueries({ queryKey: signerKeys.byId(signerId) });+ createNotification({ text: "Approval policy updated", type: "success" });+ }+ });+};++export const useRequestToSign = () => {+ const queryClient = useQueryClient();++ return useMutation<unknown, object, TRequestToSignDTO>({+ mutationFn: async ({ signerId, ...body }) => {+ const { data } = await apiRequest.post(+ `/api/v1/cert-manager/signers/${signerId}/requests`,+ body+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.requests(signerId) });+ queryClient.invalidateQueries({ queryKey: approvalRequestQuery.allKey() });+ createNotification({ text: "Signing request submitted", type: "success" });+ }+ });+};++export const usePreApproveSigning = () => {+ const queryClient = useQueryClient();++ return useMutation<unknown, object, TPreApproveSigningDTO>({+ mutationFn: async ({ signerId, ...body }) => {+ const { data } = await apiRequest.post(+ `/api/v1/cert-manager/signers/${signerId}/requests/pre-approve`,+ body+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.requests(signerId) });+ queryClient.invalidateQueries({ queryKey: approvalRequestQuery.allKey() });+ createNotification({ text: "Signing pre-approved", type: "success" });+ }+ });+};++export const useRevokeSignerRequest = () => {+ const queryClient = useQueryClient();++ return useMutation<unknown, object, TRevokeSignerRequestDTO>({+ mutationFn: async ({ signerId, requestId }) => {+ const { data } = await apiRequest.post(+ `/api/v1/cert-manager/signers/${signerId}/requests/${requestId}/revoke`+ );+ return data;+ },+ onSuccess: (_, { signerId }) => {+ queryClient.invalidateQueries({ queryKey: signerKeys.requests(signerId) });+ queryClient.invalidateQueries({ queryKey: approvalRequestQuery.allKey() });+ createNotification({ text: "Request revoked", type: "success" });+ }+ });+};diff --git a/frontend/src/hooks/api/signers/queries.tsx b/frontend/src/hooks/api/signers/queries.tsxindex 0b2a199e9a..1d7e2cfa64 100644--- a/frontend/src/hooks/api/signers/queries.tsx+++ b/frontend/src/hooks/api/signers/queries.tsx@@ -3,14 +3,25 @@ import { useQuery } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";import {+ SignerStatus,TGetPublicKeyResponse,+ TListEffectiveSignerMembersDTO,+ TListEffectiveSignerMembersResponse,+ TListSignerMembersDTO,+ TListSignerMembersResponse,+ TListSignerRequestsDTO,+ TListSignerRequestsResponse,TListSignersDTO,TListSignersResponse,TListSigningOperationsDTO,TListSigningOperationsResponse,- TSigner+ TSigner,+ TSignerPolicy} from "./types";+const SIGNER_LIST_POLL_MS = 4000;+const SIGNER_DETAIL_POLL_MS = 3000;+export const signerKeys = {all: ["signers"] as const,list: (projectId: string) => [...signerKeys.all, "list", projectId] as const,@@ -20,7 +31,47 @@ export const signerKeys = {publicKey: (signerId: string) => [...signerKeys.all, "publicKey", signerId] as const,operations: (signerId: string) => [...signerKeys.all, "operations", signerId] as const,operationsWithOpts: (filters: TListSigningOperationsDTO) =>- [...signerKeys.operations(filters.signerId), filters] as const+ [...signerKeys.operations(filters.signerId), filters] as const,+ members: (signerId: string, kind: string) =>+ [...signerKeys.all, "members", signerId, kind] as const,+ effectiveMembers: (signerId: string, kind: "user" | "identity") =>+ [...signerKeys.all, "effective-members", signerId, kind] as const,+ effectiveMembersAll: (signerId: string) =>+ [...signerKeys.all, "effective-members", signerId] as const,+ policy: (signerId: string) => [...signerKeys.all, "policy", signerId] as const,+ requestsAll: () => [...signerKeys.all, "requests"] as const,+ requests: (signerId: string) => [...signerKeys.requestsAll(), signerId] as const,+ requestsWithOpts: (filters: TListSignerRequestsDTO) =>+ [...signerKeys.requests(filters.signerId), filters] as const,+ certificate: (signerId: string) => [...signerKeys.all, "certificate", signerId] as const,+ myPermissions: (signerId: string) => [...signerKeys.all, "my-permissions", signerId] as const+};++export type TSignerMyPermissions = {+ canRead: boolean;+ canEdit: boolean;+ canDelete: boolean;+ canEnableDisable: boolean;+ canManageMembers: boolean;+ canManagePolicy: boolean;+ canSign: boolean;+ canRequestSign: boolean;+ canPreApprove: boolean;+ canReissueCertificate: boolean;+ canExportCertificate: boolean;+};++export const useGetSignerMyPermissions = (signerId: string) => {+ return useQuery({+ queryKey: signerKeys.myPermissions(signerId),+ queryFn: async () => {+ const { data } = await apiRequest.get<TSignerMyPermissions>(+ `/api/v1/cert-manager/signers/${signerId}/my-permissions`+ );+ return data;+ },+ enabled: Boolean(signerId)+ });};export const useListSigners = (dto: TListSignersDTO) => {@@ -40,7 +91,11 @@ export const useListSigners = (dto: TListSignersDTO) => {return data;},enabled: Boolean(dto.projectId),- placeholderData: (previousData) => previousData+ placeholderData: (previousData) => previousData,+ refetchInterval: (query) =>+ query.state.data?.signers?.some((s) => s.status === SignerStatus.Pending)+ ? SIGNER_LIST_POLL_MS+ : false});};@@ -51,7 +106,9 @@ export const useGetSigner = (signerId: string) => {const { data } = await apiRequest.get<TSigner>(`/api/v1/cert-manager/signers/${signerId}`);return data;},- enabled: Boolean(signerId)+ enabled: Boolean(signerId),+ refetchInterval: (query) =>+ query.state.data?.status === SignerStatus.Pending ? SIGNER_DETAIL_POLL_MS : false});};@@ -87,3 +144,83 @@ export const useListSigningOperations = (dto: TListSigningOperationsDTO) => {placeholderData: (previousData) => previousData});};++const memberPathSegment = (kind: "user" | "identity" | "group") => {+ if (kind === "user") return "users";+ if (kind === "identity") return "identities";+ return "groups";+};++export const useListSignerMembers = (dto: TListSignerMembersDTO) => {+ return useQuery({+ queryKey: signerKeys.members(dto.signerId, dto.kind),+ queryFn: async () => {+ const { data } = await apiRequest.get<TListSignerMembersResponse>(+ `/api/v1/cert-manager/signers/${dto.signerId}/${memberPathSegment(dto.kind)}`+ );+ return data;+ },+ enabled: Boolean(dto.signerId)+ });+};++export const useListEffectiveSignerMembers = (dto: TListEffectiveSignerMembersDTO) => {+ const segment = dto.kind === "user" ? "effective-users" : "effective-identities";+ return useQuery({+ queryKey: signerKeys.effectiveMembers(dto.signerId, dto.kind),+ queryFn: async () => {+ const { data } = await apiRequest.get<TListEffectiveSignerMembersResponse>(+ `/api/v1/cert-manager/signers/${dto.signerId}/${segment}`+ );+ return data;+ },+ enabled: Boolean(dto.signerId)+ });+};++export const useGetSignerPolicy = (signerId: string) => {+ return useQuery({+ queryKey: signerKeys.policy(signerId),+ queryFn: async () => {+ const { data } = await apiRequest.get<TSignerPolicy>(+ `/api/v1/cert-manager/signers/${signerId}/approval-policy`+ );+ return data;+ },+ enabled: Boolean(signerId)+ });+};++export const useListSignerRequests = (dto: TListSignerRequestsDTO) => {+ return useQuery({+ queryKey: signerKeys.requestsWithOpts(dto),+ queryFn: async () => {+ const params = new URLSearchParams();+ if (dto.statuses?.length) params.set("statuses", dto.statuses.join(","));+ if (dto.offset !== undefined) params.set("offset", String(dto.offset));+ if (dto.limit !== undefined) params.set("limit", String(dto.limit));+ const url = params.toString()+ ? `/api/v1/cert-manager/signers/${dto.signerId}/requests?${params.toString()}`+ : `/api/v1/cert-manager/signers/${dto.signerId}/requests`;+ const { data } = await apiRequest.get<TListSignerRequestsResponse>(url);+ return data;+ },+ enabled: Boolean(dto.signerId),+ placeholderData: (previousData) => previousData+ });+};++export const useExportSignerCertificate = (signerId: string, enabled = false) => {+ return useQuery({+ queryKey: signerKeys.certificate(signerId),+ queryFn: async () => {+ const { data } = await apiRequest.get<{+ certificatePem: string;+ serialNumber: string;+ signerName: string;+ }>(`/api/v1/cert-manager/signers/${signerId}/certificate`);+ return data;+ },+ enabled: enabled && Boolean(signerId)+ });+};diff --git a/frontend/src/hooks/api/signers/types.ts b/frontend/src/hooks/api/signers/types.tsindex 5ffdd415f9..d9035b1f00 100644--- a/frontend/src/hooks/api/signers/types.ts+++ b/frontend/src/hooks/api/signers/types.ts@@ -1,19 +1,49 @@export enum SignerStatus {+ Pending = "pending",Active = "active",- Disabled = "disabled"+ Failed = "failed",+ Disabled = "disabled",+ Expired = "expired"+}++export enum SignerKeyAlgorithm {+ RSA_2048 = "RSA_2048",+ RSA_3072 = "RSA_3072",+ RSA_4096 = "RSA_4096",+ ECDSA_P256 = "EC_prime256v1",+ ECDSA_P384 = "EC_secp384r1",+ ECDSA_P521 = "EC_secp521r1"}+export const signerKeyAlgorithmLabels: Record<SignerKeyAlgorithm, string> = {+ [SignerKeyAlgorithm.RSA_2048]: "RSA-2048",+ [SignerKeyAlgorithm.RSA_3072]: "RSA-3072",+ [SignerKeyAlgorithm.RSA_4096]: "RSA-4096",+ [SignerKeyAlgorithm.ECDSA_P256]: "ECDSA P-256",+ [SignerKeyAlgorithm.ECDSA_P384]: "ECDSA P-384",+ [SignerKeyAlgorithm.ECDSA_P521]: "ECDSA P-521"+};+export const signerStatusLabels: Record<SignerStatus, string> = {+ [SignerStatus.Pending]: "Pending",[SignerStatus.Active]: "Active",- [SignerStatus.Disabled]: "Disabled"+ [SignerStatus.Failed]: "Failed",+ [SignerStatus.Disabled]: "Disabled",+ [SignerStatus.Expired]: "Expired"};export const getSignerStatusBadgeVariant = (status: SignerStatus) => {switch (status) {case SignerStatus.Active:return "success" as const;- case SignerStatus.Disabled:+ case SignerStatus.Pending:return "warning" as const;+ case SignerStatus.Failed:+ return "danger" as const;+ case SignerStatus.Expired:+ return "danger" as const;+ case SignerStatus.Disabled:+ return "neutral" as const;default:return "neutral" as const;}@@ -37,8 +67,13 @@ export type TSigner = {name: string;description?: string | null;status: SignerStatus;- certificateId: string;+ certificateId?: string | null;approvalPolicyId?: string | null;+ caId?: string | null;+ commonName?: string | null;+ certificateTtlDays?: number | null;+ renewBeforeDays?: number | null;+ keyAlgorithm?: SignerKeyAlgorithm | string | null;lastSignedAt?: string | null;createdAt: string;updatedAt: string;@@ -46,6 +81,7 @@ export type TSigner = {certificateSerialNumber?: string | null;certificateNotAfter?: string | null;approvalPolicyName?: string | null;+ failureReason?: string | null;};export enum SigningActorType {@@ -74,6 +110,94 @@ export type TSigningOperation = {createdAt: string;};+export enum SignerMemberRole {+ Administrator = "admin",+ Operator = "operator",+ Auditor = "auditor"+}++export const signerMemberRoleLabels: Record<SignerMemberRole, string> = {+ [SignerMemberRole.Administrator]: "Administrator",+ [SignerMemberRole.Operator]: "Operator",+ [SignerMemberRole.Auditor]: "Auditor"+};++export const signerMemberRoleDescriptions: Record<SignerMemberRole, string> = {+ [SignerMemberRole.Administrator]: "Manage members, approval policy, and settings.",+ [SignerMemberRole.Operator]: "Sign artifacts and submit signing requests for this signer.",+ [SignerMemberRole.Auditor]: "View members, activity, and the audit log for this signer."+};++export type TSignerMember = {+ membershipId: string;+ signerId: string;+ actorUserId?: string | null;+ actorIdentityId?: string | null;+ actorGroupId?: string | null;+ role: string;+ customRoleId?: string | null;+ createdAt: string;+ updatedAt: string;+ details?: {+ name: string | null;+ email?: string | null;+ username?: string | null;+ authMethod?: string | null;+ slug?: string | null;+ } | null;+};++export type TSignerPolicyStep = {+ requiredApprovals: number;+ approvers: { type: "user" | "group"; id: string }[];+ name?: string | null;+ stepNumber?: number;+};++export type TSignerPolicy = {+ id: string;+ signerId: string;+ hasSteps: boolean;+ steps: TSignerPolicyStep[];+ constraints: {+ maxSignings: number | null;+ maxWindowDuration: string | null;+ };+};++export enum SignerRequestStatus {+ Pending = "pending",+ Approved = "approved",+ Rejected = "rejected",+ Cancelled = "cancelled",+ Expired = "expired"+}++export type TSignerRequest = {+ id: string;+ projectId: string;+ organizationId: string;+ policyId: string;+ requesterId?: string | null;+ machineIdentityId?: string | null;+ requesterName: string;+ requesterEmail: string;+ type: string;+ status: SignerRequestStatus;+ justification?: string | null;+ currentStep: number;+ requestData: unknown;+ expiresAt?: string | null;+ scopeType?: string | null;+ scopeId?: string | null;+ grantedByUserId?: string | null;+ maxSignings?: number | null;+ usedSignings?: number;+ grantStatus?: string | null;+ createdAt: string;+ updatedAt: string;+};+export type TListSignersDTO = {projectId: string;offset?: number;@@ -86,27 +210,59 @@ export type TListSignersResponse = {totalCount: number;};+export type TCreateSignerMemberInput = {+ kind: "user" | "identity" | "group";+ id: string;+ role: SignerMemberRole;+};++export type TCreateSignerApprovalPolicyInput = {+ steps: {+ stepNumber: number;+ name?: string | null;+ requiredApprovals: number;+ approverUserIds: string[];+ approverGroupIds?: string[];+ }[];+ constraints?: { maxSignings?: number | null; maxWindowDuration?: string | null };+};+export type TCreateSignerDTO = {projectId: string;name: string;description?: string;- certificateId: string;+ caId?: string;+ commonName?: string;+ certificateTtlDays?: number;+ renewBeforeDays?: number | null;+ keyAlgorithm?: SignerKeyAlgorithm;+ certificateId?: string;approvalPolicyId?: string;+ members?: TCreateSignerMemberInput[];+ approvalPolicy?: TCreateSignerApprovalPolicyInput;};export type TUpdateSignerDTO = {signerId: string;name?: string;description?: string | null;- status?: SignerStatus;- certificateId?: string;- approvalPolicyId?: string | null;+ renewBeforeDays?: number | null;};export type TDeleteSignerDTO = {signerId: string;};+export type TReissueSignerCertificateDTO = {+ signerId: string;+ caId: string;+ commonName?: string;+ certificateTtlDays?: number;+};++export type TEnableSignerDTO = { signerId: string };+export type TDisableSignerDTO = { signerId: string };+export type TGetPublicKeyResponse = {publicKey: string;algorithm: string;@@ -123,3 +279,102 @@ export type TListSigningOperationsResponse = {operations: TSigningOperation[];totalCount: number;};++export type TListSignerMembersDTO = { signerId: string; kind: "user" | "identity" | "group" };+export type TListSignerMembersResponse = { memberships: TSignerMember[] };++export type TEffectiveSignerMember = {+ actorUserId: string | null;+ actorIdentityId: string | null;+ role: string;+ viaGroupIds: string[];+ isDirect: boolean;+ details: {+ name: string | null;+ email?: string | null;+ username?: string | null;+ authMethod?: string | null;+ } | null;+};+export type TListEffectiveSignerMembersDTO = { signerId: string; kind: "user" | "identity" };+export type TListEffectiveSignerMembersResponse = { members: TEffectiveSignerMember[] };+export type TAddSignerUserMembersDTO = {+ signerId: string;+ userIds?: string[];+ emails?: string[];+ role: SignerMemberRole;+};+export type TUpdateSignerUserRoleDTO = {+ signerId: string;+ userId: string;+ role: SignerMemberRole;+};+export type TRemoveSignerUserDTO = { signerId: string; userId: string };++export type TAddSignerIdentityMemberDTO = {+ signerId: string;+ identityId: string;+ role: SignerMemberRole;+};+export type TUpdateSignerIdentityRoleDTO = {+ signerId: string;+ identityId: string;+ role: SignerMemberRole;+};+export type TRemoveSignerIdentityDTO = { signerId: string; identityId: string };++export type TAddSignerGroupMemberDTO = {+ signerId: string;+ groupId: string;+ role: SignerMemberRole;+};++export type TUpdateSignerGroupRoleDTO = {+ signerId: string;+ groupId: string;+ role: SignerMemberRole;+};+export type TRemoveSignerGroupDTO = { signerId: string; groupId: string };++export type TUpdateSignerPolicyDTO = {+ signerId: string;+ steps: {+ stepNumber: number;+ name?: string | null;+ requiredApprovals: number;+ approverUserIds: string[];+ approverGroupIds?: string[];+ }[];+ constraints?: { maxSignings?: number | null; maxWindowDuration?: string | null };+};++export type TSignerRequestStatusFilter = "pending" | "approved" | "expired" | "revoked";++export type TListSignerRequestsDTO = {+ signerId: string;+ statuses?: TSignerRequestStatusFilter[];+ offset?: number;+ limit?: number;+};++export type TListSignerRequestsResponse = {+ requests: TSignerRequest[];+ totalCount: number;+};+export type TRequestToSignDTO = {+ signerId: string;+ justification: string;+ requestedSignings?: number;+ requestedWindowStart?: string;+ requestedWindowEnd?: string;+};+export type TPreApproveSigningDTO = {+ signerId: string;+ granteeUserId?: string;+ granteeIdentityId?: string;+ justification: string;+ requestedSignings?: number;+ requestedWindowStart?: string;+ requestedWindowEnd?: string;+};+export type TRevokeSignerRequestDTO = { signerId: string; requestId: string };diff --git a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsxindex 2b39373e31..4e462be994 100644--- a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx+++ b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx@@ -159,7 +159,7 @@ const PageContent = () => {orgId: currentProject.orgId,projectId: currentProject.id},- search: isCodeSigning ? { tab: "approvals" } : undefined+ search: undefined});}}@@ -324,7 +324,7 @@ const PageContent = () => {: "/organizations/$orgId/projects/cert-manager/$projectId/approvals"}params={{ orgId: currentOrg.id, projectId: currentProject.id }}- search={isCodeSigning ? { tab: "approvals" } : { section: "certificates" }}+ search={isCodeSigning ? undefined : { section: "certificates" }}className={linkClass}><FontAwesomeIcon icon={faChevronLeft} />diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/CodeSigningPage.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/CodeSigningPage.tsxindex 08ba72f6d2..1aed823846 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/CodeSigningPage.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/CodeSigningPage.tsx@@ -1,30 +1,18 @@import { useState } from "react";import { Helmet } from "react-helmet";import { useTranslation } from "react-i18next";-import { useNavigate, useSearch } from "@tanstack/react-router";+import { PenTool } from "lucide-react";-import { PageHeader, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";+import { PageHeader } from "@app/components/v2";import { useProject } from "@app/context";import { ProjectType } from "@app/hooks/api/projects/types";-import { CodeSigningGrantsTab } from "../ApprovalsPage/components/CodeSigningGrantsTab";-import { CodeSigningPolicyTab } from "../ApprovalsPage/components/CodeSigningPolicyTab";-import { CreateSignerModal } from "./components/CreateSignerModal";+import { CreateSignerWizard } from "./components/CreateSignerWizard";import { SignersTable } from "./components/SignersTable";-const TABS = ["signers", "signing-policies", "grants"] as const;-export const CodeSigningPage = () => {const { t } = useTranslation();const { currentProject } = useProject();- const navigate = useNavigate();- const { selectedTab } = useSearch({- from: "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/code-signing/"- });-- const activeTab: (typeof TABS)[number] = TABS.includes(selectedTab as (typeof TABS)[number])- ? (selectedTab as (typeof TABS)[number])- : "signers";const [isCreateOpen, setIsCreateOpen] = useState(false);return (@@ -35,45 +23,13 @@ export const CodeSigningPage = () => {<div className="mx-auto mb-6 w-full max-w-8xl"><PageHeaderscope={ProjectType.CertificateManager}+ icon={PenTool}title="Code Signing"- description="Securely sign code and artifacts with centralized key management and approval workflows."+ description="Sign release artifacts and binaries with managed signing certificates."/>- <Tabs- value={activeTab}- onValueChange={(v) =>- navigate({- to: "/organizations/$orgId/projects/cert-manager/$projectId/code-signing",- params: { orgId: currentProject.orgId, projectId: currentProject.id },- search: { selectedTab: v }- })- }- >- <TabList>- <Tab variant="project" value="signers">- Signers- </Tab>- <Tab variant="project" value="grants">- Grants- </Tab>- <Tab variant="project" value="signing-policies">- Signer Policies- </Tab>- </TabList>- <TabPanel value="signers">- <SignersTable- projectId={currentProject.id}- onCreateSigner={() => setIsCreateOpen(true)}- />- </TabPanel>- <TabPanel value="grants">- <CodeSigningGrantsTab />- </TabPanel>- <TabPanel value="signing-policies">- <CodeSigningPolicyTab />- </TabPanel>- </Tabs>+ <SignersTable projectId={currentProject.id} onCreateSigner={() => setIsCreateOpen(true)} /></div>- <CreateSignerModal+ <CreateSignerWizardisOpen={isCreateOpen}onOpenChange={setIsCreateOpen}projectId={currentProject.id}diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerModal.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerModal.tsxdeleted file mode 100644index 5fc7f75139..0000000000--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerModal.tsx+++ /dev/null@@ -1,200 +0,0 @@-import { useMemo } from "react";-import { Controller, useForm } from "react-hook-form";-import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";-import { z } from "zod";--import {- Button,- FilterableSelect,- FormControl,- Input,- Modal,- ModalContent,- Select,- SelectClear,- SelectItem,- TextArea-} from "@app/components/v2";-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";--type Props = {- isOpen: boolean;- onOpenChange: (open: boolean) => void;- projectId: string;-};--const formSchema = z.object({- name: slugSchema({ min: 1, max: 64, field: "Name" }),- description: z.string().trim().max(256).optional(),- certificateId: z.string().uuid("Certificate is required"),- approvalPolicyId: z.string().uuid().optional().or(z.literal(""))-});--type FormData = z.infer<typeof formSchema>;--type CertOption = {- label: string;- value: string;-};--export const CreateSignerModal = ({ isOpen, onOpenChange, projectId }: Props) => {- const createSigner = useCreateSigner();-- const { data: certificatesData, isPending: isCertsLoading } = useListWorkspaceCertificates({- projectId,- offset: 0,- limit: 100,- status: "active",- extendedKeyUsage: "codeSigning"- });-- const { data: policies = [], isPending: isPoliciesLoading } = useQuery(- approvalPolicyQuery.list({- policyType: ApprovalPolicyType.CertCodeSigning,- scope: ApprovalPolicyScope.Project,- scopeId: projectId- })- );-- const certOptions: CertOption[] = useMemo(() => {- const certs = certificatesData?.certificates ?? [];- return certs.map((cert) => {- const display = cert.friendlyName || cert.commonName || cert.id;- const subtitle = cert.altNames ? ` (${cert.altNames})` : "";- return {- label: `${display}${subtitle}`,- value: cert.id- };- });- }, [certificatesData?.certificates]);-- const {- control,- handleSubmit,- reset,- formState: { isSubmitting }- } = useForm<FormData>({- resolver: zodResolver(formSchema),- defaultValues: {- name: "",- description: "",- certificateId: "",- approvalPolicyId: ""- }- });-- const handleOpenChange = (open: boolean) => {- if (!open) reset();- onOpenChange(open);- };-- const onSubmit = async (data: FormData) => {- await createSigner.mutateAsync({- projectId,- name: data.name,- description: data.description,- certificateId: data.certificateId,- ...(data.approvalPolicyId ? { approvalPolicyId: data.approvalPolicyId } : {})- });- handleOpenChange(false);- };-- return (- <Modal isOpen={isOpen} onOpenChange={handleOpenChange}>- <ModalContent title="Create Signer">- <form onSubmit={handleSubmit(onSubmit)}>- <Controller- name="name"- control={control}- render={({ field, fieldState: { error } }) => (- <FormControl label="Name" isError={Boolean(error)} errorText={error?.message}>- <Input {...field} placeholder="my-code-signer" />- </FormControl>- )}- />- <Controller- name="description"- control={control}- render={({ field, fieldState: { error } }) => (- <FormControl label="Description" isError={Boolean(error)} errorText={error?.message}>- <TextArea {...field} placeholder="Optional description" rows={2} />- </FormControl>- )}- />- <Controller- name="certificateId"- control={control}- render={({ field, fieldState: { error } }) => (- <FormControl- label="Certificate"- isError={Boolean(error)}- errorText={error?.message}- helperText="Only active code signing certificates in Certificate Manager are shown"- >- <FilterableSelect<CertOption>- isLoading={isCertsLoading}- options={certOptions}- value={certOptions.find((opt) => opt.value === field.value) ?? null}- onChange={(selected) => {- const option = selected as CertOption | null;- field.onChange(option?.value ?? "");- }}- placeholder="Search by common name or SAN..."- noOptionsMessage={() =>- "No active code signing certificates found in Certificate Manager"- }- maxMenuHeight={200}- />- </FormControl>- )}- />- <Controller- name="approvalPolicyId"- control={control}- render={({ field, fieldState: { error } }) => (- <FormControl- label="Approval Policy"- isError={Boolean(error)}- errorText={error?.message}- helperText="Optional. Without a policy, signing is allowed without approval."- >- <Select- value={field.value}- onValueChange={field.onChange}- className="w-full"- isLoading={isPoliciesLoading}- placeholder="None (no approval required)"- >- <SelectClear selectValue={field.value ?? ""} onClear={() => field.onChange("")}>- None (no approval required)- </SelectClear>- {policies.map((policy) => (- <SelectItem key={policy.id} value={policy.id}>- {policy.name}- </SelectItem>- ))}- </Select>- </FormControl>- )}- />- <div className="mt-4 flex justify-end gap-2">- <Button variant="outline_bg" onClick={() => handleOpenChange(false)}>- Cancel- </Button>- <Button type="submit" isLoading={isSubmitting}>- Create- </Button>- </div>- </form>- </ModalContent>- </Modal>- );-};diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/ApprovalPolicyStep.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/ApprovalPolicyStep.tsxnew file mode 100644index 0000000000..bf9aaae024--- /dev/null+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/ApprovalPolicyStep.tsx@@ -0,0 +1,265 @@+import { ClockIcon, PlusIcon, ShieldIcon, XIcon } from "lucide-react";++import {+ Button,+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ Field,+ FieldContent,+ FieldDescription,+ FieldLabel,+ FilterableSelect,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3";++import {+ ApproverOption,+ approverOptionKey,+ makeStepKey,+ NO_WINDOW_LIMIT,+ PolicyStep,+ WINDOW_DURATION_OPTIONS,+ WizardState+} from "./types";++type ApprovalPolicyStepProps = {+ state: WizardState;+ setState: React.Dispatch<React.SetStateAction<WizardState>>;+ approverOptions: ApproverOption[];+};++export const ApprovalPolicyStep = ({+ state,+ setState,+ approverOptions+}: ApprovalPolicyStepProps) => {+ const addStep = () => {+ setState((prev) => ({+ ...prev,+ policySteps: [+ ...prev.policySteps,+ {+ key: makeStepKey(),+ name: `Step ${prev.policySteps.length + 1}`,+ approverUserIds: [],+ approverGroupIds: [],+ requiredApprovals: 1+ }+ ]+ }));+ };++ const removeStep = (key: string) => {+ setState((prev) => ({+ ...prev,+ policySteps: prev.policySteps.filter((s) => s.key !== key)+ }));+ };++ const patchStep = (key: string, patch: Partial<PolicyStep>) => {+ setState((prev) => ({+ ...prev,+ policySteps: prev.policySteps.map((s) => (s.key === key ? { ...s, ...patch } : s))+ }));+ };++ const hasSteps = state.policySteps.length > 0;++ if (!hasSteps) {+ return (+ <div>+ <Empty className="border border-solid">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <ShieldIcon />+ </EmptyMedia>+ <EmptyTitle>No approval required</EmptyTitle>+ <EmptyDescription>+ Members can sign without approval from anyone else. Add an approval step to change+ this.+ </EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button variant="outline" size="sm" onClick={addStep}>+ <PlusIcon className="h-3.5 w-3.5" />+ <span>Add approval step</span>+ </Button>+ </EmptyContent>+ </Empty>+ </div>+ );+ }++ return (+ <div>+ <div className="mb-4 flex items-center justify-between gap-4">+ <div className="min-w-0">+ <div className="text-sm font-semibold text-mineshaft-100">Approves</div>+ <p className="text-xs text-mineshaft-400">+ Approvals run in order. Each step needs the listed number of approvers to approve.+ </p>+ </div>+ <Button variant="outline" size="sm" onClick={addStep} className="shrink-0">+ <PlusIcon className="h-3.5 w-3.5" />+ <span>Add step</span>+ </Button>+ </div>++ <div className="space-y-3">+ {state.policySteps.map((s, idx) => {+ const takenUsers = new Set(s.approverUserIds);+ const takenGroups = new Set(s.approverGroupIds);+ const isTaken = (o: ApproverOption) =>+ o.kind === "user" ? takenUsers.has(o.value) : takenGroups.has(o.value);+ const optionsForStep = approverOptions.filter((o) => !isTaken(o));+ const valueForStep = approverOptions.filter(isTaken);++ return (+ <div+ key={s.key}+ className="rounded-md border border-mineshaft-700 bg-mineshaft-900/40 p-4"+ >+ <div className="mb-4 flex items-center gap-3">+ <div className="flex h-6 w-6 items-center justify-center rounded-full border border-border bg-mineshaft-800 text-[11px] font-medium text-muted">+ {idx + 1}+ </div>+ <Input+ value={s.name}+ onChange={(e) => patchStep(s.key, { name: e.target.value })}+ placeholder={`Step ${idx + 1}`}+ className="h-9 flex-1"+ />+ <Button+ variant="ghost"+ size="xs"+ onClick={() => removeStep(s.key)}+ aria-label="Remove step"+ >+ <XIcon className="h-3.5 w-3.5 text-mineshaft-300" />+ </Button>+ </div>++ <div className="grid grid-cols-[1fr_140px] gap-3">+ <Field>+ <FieldLabel>Approvers</FieldLabel>+ <FieldContent>+ <FilterableSelect<ApproverOption>+ isMulti+ options={optionsForStep}+ groupBy="kind"+ getGroupHeaderLabel={(g) => (g === "group" ? "Groups" : "Users")}+ getOptionValue={(o) => approverOptionKey(o as ApproverOption)}+ isOptionSelected={(o) => isTaken(o as ApproverOption)}+ value={valueForStep}+ onChange={(selected) => {+ const picks = (selected as ApproverOption[] | null) ?? [];+ patchStep(s.key, {+ approverUserIds: picks+ .filter((p) => p.kind === "user")+ .map((p) => p.value),+ approverGroupIds: picks+ .filter((p) => p.kind === "group")+ .map((p) => p.value)+ });+ }}+ placeholder="Pick approvers from members..."+ noOptionsMessage={() => "Add member users in the previous step first."}+ />+ <FieldDescription>Approvers must already be members.</FieldDescription>+ </FieldContent>+ </Field>+ <Field>+ <FieldLabel>Required</FieldLabel>+ <FieldContent>+ <Input+ type="number"+ min={1}+ value={s.requiredApprovals}+ onChange={(e) => {+ const raw = e.target.value;+ const n = raw === "" ? 1 : Math.max(1, Number(raw));+ patchStep(s.key, { requiredApprovals: n });+ }}+ />+ </FieldContent>+ </Field>+ </div>+ </div>+ );+ })}+ </div>++ <div className="mt-6 text-sm font-semibold text-mineshaft-100">What an approval allows</div>+ <p className="mb-3 text-xs text-mineshaft-300">+ Once approval is granted, define how it can be used. At least one limit is required.+ </p>++ <div className="overflow-hidden rounded-md border border-mineshaft-700 bg-mineshaft-900/40">+ <div className="grid grid-cols-[1fr_auto] items-center gap-4 border-b border-mineshaft-800 px-4 py-3">+ <div className="flex min-w-0 items-start gap-3">+ <ShieldIcon className="mt-0.5 h-4 w-4 shrink-0 text-mineshaft-300" />+ <div className="min-w-0">+ <div className="text-sm font-medium text-mineshaft-100">Signatures per approval</div>+ <p className="text-xs text-mineshaft-400">+ How many signatures one approval is good for. Leave empty for unlimited.+ </p>+ </div>+ </div>+ <Input+ type="number"+ min={1}+ value={state.maxSignings ?? ""}+ onChange={(e) =>+ setState((prev) => ({+ ...prev,+ maxSignings: e.target.value ? Number(e.target.value) : null+ }))+ }+ placeholder="Unlimited"+ className="w-36"+ />+ </div>+ <div className="grid grid-cols-[1fr_auto] items-center gap-4 px-4 py-3">+ <div className="flex min-w-0 items-start gap-3">+ <ClockIcon className="mt-0.5 h-4 w-4 shrink-0 text-mineshaft-300" />+ <div className="min-w-0">+ <div className="text-sm font-medium text-mineshaft-100">Signing window</div>+ <p className="text-xs text-mineshaft-400">+ After approval is granted, how long signing is allowed before it expires.+ </p>+ </div>+ </div>+ <Select+ value={state.maxWindowDuration ?? NO_WINDOW_LIMIT}+ onValueChange={(v) =>+ setState((prev) => ({+ ...prev,+ maxWindowDuration: v === NO_WINDOW_LIMIT ? null : v+ }))+ }+ >+ <SelectTrigger className="w-36">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {WINDOW_DURATION_OPTIONS.map((opt) => (+ <SelectItem key={opt.value} value={opt.value}>+ {opt.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>+ </div>+ );+};diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/BasicsStep.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/BasicsStep.tsxnew file mode 100644index 0000000000..ef3840e83e--- /dev/null+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/BasicsStep.tsx@@ -0,0 +1,56 @@+import { Controller, useForm } from "react-hook-form";++import {+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ Input,+ TextArea+} from "@app/components/v3";++import { BasicsForm } from "./schemas";++type BasicsStepProps = { form: ReturnType<typeof useForm<BasicsForm>> };++export const BasicsStep = ({ form }: BasicsStepProps) => (+ <FieldGroup>+ <Controller+ name="name"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Signer name <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Input {...field} placeholder="e.g. mobile-app-prod" isError={Boolean(error)} />+ <FieldDescription>Lowercase, with dashes.</FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ name="description"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Description</FieldLabel>+ <FieldContent>+ <TextArea+ {...field}+ value={field.value ?? ""}+ placeholder="What this signer signs (e.g. iOS + Android production bundles)."+ rows={3}+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ </FieldGroup>+);diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsxnew file mode 100644index 0000000000..92a20ca856--- /dev/null+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CertificateStep.tsx@@ -0,0 +1,160 @@+import { Controller, useForm } from "react-hook-form";++import {+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ FilterableSelect,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3";+import { SignerKeyAlgorithm, signerKeyAlgorithmLabels } from "@app/hooks/api/signers";++import { CertificateForm } from "./schemas";+import { CaGroup, CaOption } from "./types";++type CertificateStepProps = {+ form: ReturnType<typeof useForm<CertificateForm>>;+ caOptions: CaOption[];+ isCasLoading: boolean;+};++export const CertificateStep = ({ form, caOptions, isCasLoading }: CertificateStepProps) => (+ <FieldGroup>+ <Controller+ name="caId"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Certificate Authority <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <FilterableSelect<CaOption>+ isLoading={isCasLoading}+ options={caOptions}+ value={caOptions.find((o) => o.id === field.value) ?? null}+ onChange={(selected) => {+ const opt = selected as CaOption | null;+ field.onChange(opt?.id ?? "");+ }}+ getOptionLabel={(opt) => opt.name}+ getOptionValue={(opt) => opt.id}+ groupBy={caOptions.length > 0 ? "groupType" : undefined}+ getGroupHeaderLabel={+ caOptions.length > 0+ ? (groupType: CaGroup) =>+ groupType === "internal" ? "Internal CAs" : "External CAs"+ : undefined+ }+ placeholder="Select a Certificate Authority..."+ noOptionsMessage={() => "No active CAs found in this project."}+ isError={Boolean(error)}+ />+ <FieldDescription>The CA that will issue the certificate.</FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ name="commonName"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Common Name <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Input {...field} placeholder="Acme Mobile, Inc." isError={Boolean(error)} />+ <FieldDescription>The legal name shown on the certificate.</FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ name="keyAlgorithm"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Key algorithm <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Select value={field.value} onValueChange={field.onChange}>+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {Object.values(SignerKeyAlgorithm).map((value) => (+ <SelectItem key={value} value={value}>+ {signerKeyAlgorithmLabels[value]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ name="certificateTtlDays"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Validity (days) <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Input+ type="number"+ min={1}+ max={3650}+ value={field.value ?? ""}+ onChange={(e) => field.onChange(Number(e.target.value))}+ placeholder="365"+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ name="renewBeforeDays"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Renew before (days)</FieldLabel>+ <FieldContent>+ <Input+ type="number"+ min={1}+ max={30}+ value={field.value ?? ""}+ onChange={(e) => {+ const raw = e.target.value;+ field.onChange(raw === "" ? null : Number(raw));+ }}+ placeholder="Leave empty to disable auto-renewal"+ isError={Boolean(error)}+ />+ <FieldDescription>+ Renew the certificate this many days before it expires.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ </FieldGroup>+);diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsxnew file mode 100644index 0000000000..8720b31471--- /dev/null+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/CreateSignerWizard.tsx@@ -0,0 +1,375 @@+import { useMemo, useState } from "react";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { ShieldIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ DocumentationLinkBadge,+ Sheet,+ SheetContent,+ SheetHeader,+ SheetTitle,+ Stepper,+ StepperList,+ StepperStep+} from "@app/components/v3";+import { useOrganization, useUser } from "@app/context";+import { useListCasByProjectId } from "@app/hooks/api/ca";+import { CaStatus } from "@app/hooks/api/ca/enums";+import {+ useGetIdentityMembershipOrgs,+ useGetOrganizationGroups+} from "@app/hooks/api/organization";+import { SignerKeyAlgorithm, SignerMemberRole, useCreateSigner } from "@app/hooks/api/signers";+import { useGetOrgUsers } from "@app/hooks/api/users";++import { PkiDocsUrls } from "../../../pki-docs-urls";+import { ApprovalPolicyStep } from "./ApprovalPolicyStep";+import { BasicsStep } from "./BasicsStep";+import { CertificateStep } from "./CertificateStep";+import { MembersStep } from "./MembersStep";+import { BasicsForm, basicsSchema, CertificateForm, certificateSchema } from "./schemas";+import { CaOption, INITIAL_WIZARD_STATE, MemberOption, STEPS, WizardState } from "./types";++type Props = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ projectId: string;+};++export const CreateSignerWizard = ({ isOpen, onOpenChange, projectId }: Props) => {+ const { currentOrg } = useOrganization();+ const { user } = useUser();+ const orgId = currentOrg?.id ?? "";++ const creatorLabel =+ [user.firstName, user.lastName].filter(Boolean).join(" ").trim() ||+ user.username ||+ user.email ||+ user.id;++ const [step, setStep] = useState(0);+ const [state, setState] = useState<WizardState>(INITIAL_WIZARD_STATE);+ const [submitting, setSubmitting] = useState(false);++ const cas = useListCasByProjectId();+ const usersQuery = useGetOrgUsers(orgId);+ const identitiesQuery = useGetIdentityMembershipOrgs({ organizationId: orgId, limit: 100 });+ const groupsQuery = useGetOrganizationGroups(orgId);++ const createSigner = useCreateSigner();++ const caOptions: CaOption[] = useMemo(() => {+ const list = cas.data ?? [];+ return list+ .filter((ca) => ca.status === CaStatus.ACTIVE)+ .map((ca) => ({+ id: ca.id,+ name: ca.name,+ groupType: ca.type === "internal" ? "internal" : "external"+ }));+ }, [cas.data]);++ const userOptions: MemberOption[] = useMemo(() => {+ const users = usersQuery.data ?? [];+ return users.map((u) => ({+ value: u.user.id,+ label:+ [u.user.firstName, u.user.lastName].filter(Boolean).join(" ").trim() ||+ u.user.username ||+ u.user.email ||+ u.user.id+ }));+ }, [usersQuery.data]);++ const identityOptions: MemberOption[] = useMemo(() => {+ const memberships = identitiesQuery.data?.identityMemberships ?? [];+ return memberships.map((im) => ({ value: im.identity.id, label: im.identity.name }));+ }, [identitiesQuery.data]);++ const groupOptions: MemberOption[] = useMemo(() => {+ const groups = groupsQuery.data ?? [];+ return groups.map((g) => ({ value: g.id, label: g.name }));+ }, [groupsQuery.data]);++ const basicsForm = useForm<BasicsForm>({+ resolver: zodResolver(basicsSchema),+ values: { name: state.name, description: state.description || undefined }+ });++ const certificateForm = useForm<CertificateForm>({+ resolver: zodResolver(certificateSchema),+ values: {+ caId: state.caId,+ commonName: state.commonName,+ certificateTtlDays: state.certificateTtlDays,+ renewBeforeDays: state.renewBeforeDays,+ keyAlgorithm: state.keyAlgorithm+ }+ });++ const reset = () => {+ setStep(0);+ setState(INITIAL_WIZARD_STATE);+ basicsForm.reset({ name: "", description: undefined });+ certificateForm.reset({+ caId: "",+ commonName: "",+ certificateTtlDays: 365,+ renewBeforeDays: null,+ keyAlgorithm: SignerKeyAlgorithm.RSA_2048+ });+ };++ const handleClose = (open: boolean) => {+ if (!open) reset();+ onOpenChange(open);+ };++ const onCreate = async () => {+ setSubmitting(true);+ try {+ const approvalPolicy =+ state.policySteps.length > 0+ ? {+ steps: state.policySteps.map((s, idx) => ({+ stepNumber: idx + 1,+ name: s.name.trim() || null,+ requiredApprovals: Math.max(1, s.requiredApprovals),+ approverUserIds: s.approverUserIds,+ approverGroupIds: s.approverGroupIds+ })),+ constraints: {+ maxSignings: state.maxSignings,+ maxWindowDuration: state.maxWindowDuration+ }+ }+ : undefined;++ await createSigner.mutateAsync({+ projectId,+ name: state.name,+ description: state.description || undefined,+ caId: state.caId,+ commonName: state.commonName,+ certificateTtlDays: state.certificateTtlDays,+ renewBeforeDays: state.renewBeforeDays,+ keyAlgorithm: state.keyAlgorithm,+ members: state.pendingMembers.map((m) => ({+ kind: m.kind,+ id: m.id,+ role: m.role+ })),+ approvalPolicy+ });++ handleClose(false);+ } catch (err) {+ createNotification({+ type: "error",+ text: err instanceof Error ? err.message : "Failed to create signer"+ });+ } finally {+ setSubmitting(false);+ }+ };++ const goNext = async () => {+ if (step === 0) {+ const ok = await basicsForm.trigger();+ if (!ok) return;+ const values = basicsForm.getValues();+ setState((prev) => ({ ...prev, name: values.name, description: values.description ?? "" }));+ setStep(1);+ return;+ }+ if (step === 1) {+ const ok = await certificateForm.trigger();+ if (!ok) return;+ const values = certificateForm.getValues();+ setState((prev) => ({+ ...prev,+ caId: values.caId,+ commonName: values.commonName,+ certificateTtlDays: values.certificateTtlDays,+ renewBeforeDays: values.renewBeforeDays,+ keyAlgorithm: values.keyAlgorithm+ }));+ setStep(2);+ return;+ }+ if (step === 2) {+ setStep(3);+ return;+ }+ if (step === 3) {+ await onCreate();+ }+ };++ const goBack = () => {+ if (step > 0) setStep((s) => s - 1);+ };++ const dirty =+ step > 0 ||+ state.name !== "" ||+ state.commonName !== "" ||+ state.pendingMembers.length > 0 ||+ state.policySteps.length > 0;++ const currentStep = STEPS[step];+ const isLast = step === STEPS.length - 1;+ const ctaLabel = isLast ? "Create Signer" : "Continue";+ const firstEmptyPolicyStepIndex = state.policySteps.findIndex(+ (s) => s.approverUserIds.length + s.approverGroupIds.length === 0+ );+ const hasEmptyPolicyStep = firstEmptyPolicyStepIndex >= 0;+ const ctaDisabled = isLast && hasEmptyPolicyStep;++ return (+ <Sheet open={isOpen} onOpenChange={handleClose}>+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0 sm:max-w-[1500px]">+ <SheetHeader className="border-b">+ <SheetTitle>+ <div className="flex w-full items-start gap-2">+ <div className="flex h-10 w-10 items-center justify-center rounded-md bg-warning/10 text-warning">+ <ShieldIcon className="h-5 w-5" />+ </div>+ <div>+ <div className="flex items-center gap-x-2 text-mineshaft-300">+ Create Signer+ <DocumentationLinkBadge href={PkiDocsUrls.codeSigning.signers} />+ </div>+ <p className="text-sm leading-4 text-mineshaft-400">+ A Signer bundles a code-signing certificate, the members allowed to use it, and an+ approval policy.+ </p>+ </div>+ </div>+ </SheetTitle>+ </SheetHeader>++ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex min-h-0 flex-1 overflow-hidden">+ <aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">+ <p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">+ Setup steps+ </p>+ <Stepper+ activeStep={step}+ orientation="vertical"+ onStepChange={(i) => {+ if (i < step) setStep(i);+ }}+ >+ <StepperList>+ {STEPS.map((s, i) => (+ <StepperStep+ key={s.name}+ index={i}+ title={s.name}+ description={s.shortDescription}+ />+ ))}+ </StepperList>+ </Stepper>+ </aside>++ <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">+ <div className="mb-6">+ <h2 className="text-lg font-semibold text-foreground">{currentStep.title}</h2>+ <p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p>+ </div>++ {step === 0 && <BasicsStep form={basicsForm} />}+ {step === 1 && (+ <CertificateStep+ form={certificateForm}+ caOptions={caOptions}+ isCasLoading={cas.isPending}+ />+ )}+ {step === 2 && (+ <MembersStep+ userOptions={userOptions.filter((u) => u.value !== user.id)}+ identityOptions={identityOptions}+ groupOptions={groupOptions}+ state={state}+ setState={setState}+ isUsersLoading={usersQuery.isPending}+ isIdentitiesLoading={identitiesQuery.isPending}+ isGroupsLoading={groupsQuery.isPending}+ creator={{ id: user.id, label: creatorLabel }}+ />+ )}+ {step === 3 && (+ <ApprovalPolicyStep+ state={state}+ setState={setState}+ approverOptions={[+ { value: user.id, label: creatorLabel, kind: "user" as const },+ ...state.pendingMembers+ .filter((m) => m.role !== SignerMemberRole.Auditor)+ .filter((m) => m.kind === "user" || m.kind === "group")+ .map((m) => ({+ value: m.id,+ label: m.label,+ kind: m.kind as "user" | "group"+ }))+ ]}+ />+ )}+ </div>++ <aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">+ <div className="mb-auto">+ <div className="flex items-center justify-between gap-2">+ <p className="text-[11px] font-medium tracking-wider text-muted uppercase">+ Step {step + 1} · {currentStep.rightLabel}+ </p>+ <DocumentationLinkBadge href={PkiDocsUrls.codeSigning.signers} />+ </div>+ <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>+ <p className="mt-2 text-sm leading-relaxed text-muted">+ {currentStep.rightDescription}+ </p>+ </div>+ </aside>+ </div>++ <div className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-6 py-4">+ <span className="text-xs text-muted">+ {/* eslint-disable-next-line no-nested-ternary */}+ {ctaDisabled+ ? `Step ${firstEmptyPolicyStepIndex + 1} needs at least one approver, or remove it.`+ : dirty+ ? "Unsaved changes"+ : ""}+ </span>+ <div className="flex items-center gap-3">+ <span className="text-xs text-muted">+ Step {step + 1} of {STEPS.length}+ </span>+ {step > 0 && (+ <Button variant="outline" onClick={goBack}>+ Back+ </Button>+ )}+ <Button+ variant="project"+ onClick={goNext}+ isPending={submitting}+ isDisabled={ctaDisabled}+ >+ {ctaLabel}+ </Button>+ </div>+ </div>+ </div>+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/MembersStep.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/MembersStep.tsxnew file mode 100644index 0000000000..9f65cf92fd--- /dev/null+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/MembersStep.tsx@@ -0,0 +1,190 @@+import { useState } from "react";+import { HardDriveIcon, UserIcon, UserPlusIcon, UsersIcon, XIcon } from "lucide-react";++import {+ Badge,+ Button,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import {+ SignerMemberRole,+ signerMemberRoleDescriptions,+ signerMemberRoleLabels+} from "@app/hooks/api/signers";++import { WizardAddMemberModal } from "../WizardAddMemberModal";+import { KIND_LABEL, MemberKind, MemberOption, WizardState } from "./types";++type MembersStepProps = {+ userOptions: MemberOption[];+ identityOptions: MemberOption[];+ groupOptions: MemberOption[];+ state: WizardState;+ setState: React.Dispatch<React.SetStateAction<WizardState>>;+ isUsersLoading: boolean;+ isIdentitiesLoading: boolean;+ isGroupsLoading: boolean;+ creator: { id: string; label: string };+};++const KindIcon = ({ kind }: { kind: MemberKind }) => {+ // eslint-disable-next-line no-nested-ternary+ const Icon = kind === "user" ? UserIcon : kind === "identity" ? HardDriveIcon : UsersIcon;+ return <Icon className="h-3.5 w-3.5 text-mineshaft-300" />;+};++export const MembersStep = ({+ userOptions,+ identityOptions,+ groupOptions,+ state,+ setState,+ isUsersLoading,+ isIdentitiesLoading,+ isGroupsLoading,+ creator+}: MembersStepProps) => {+ const [isAddOpen, setIsAddOpen] = useState(false);++ const handleAdd = (m: {+ kind: MemberKind;+ id: string;+ label: string;+ role: SignerMemberRole;+ }) => {+ setState((prev) => ({ ...prev, pendingMembers: [...prev.pendingMembers, m] }));+ };++ const handleRemove = (kind: MemberKind, id: string) => {+ setState((prev) => ({+ ...prev,+ pendingMembers: prev.pendingMembers.filter((m) => !(m.kind === kind && m.id === id))+ }));+ };++ const handleChangeRole = (kind: MemberKind, id: string, role: SignerMemberRole) => {+ setState((prev) => ({+ ...prev,+ pendingMembers: prev.pendingMembers.map((m) =>+ m.kind === kind && m.id === id ? { ...m, role } : m+ )+ }));+ };++ const takenKeys = new Set(state.pendingMembers.map((m) => `${m.kind}:${m.id}`));++ return (+ <div>+ <div className="mb-4 flex justify-end">+ <Button variant="outline" size="sm" onClick={() => setIsAddOpen(true)}>+ <UserPlusIcon className="h-3.5 w-3.5" />+ <span>Add member</span>+ </Button>+ </div>++ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Member</TableHead>+ <TableHead className="w-28">Type</TableHead>+ <TableHead className="w-40">Role</TableHead>+ <TableHead className="w-5" />+ </TableRow>+ </TableHeader>+ <TableBody>+ <TableRow className="[&>td]:py-3">+ <TableCell isTruncatable>+ <div className="flex min-w-0 items-center gap-2">+ <KindIcon kind="user" />+ <span className="truncate text-foreground">{creator.label}</span>+ </div>+ </TableCell>+ <TableCell>+ <Badge variant="neutral">User</Badge>+ </TableCell>+ <TableCell>+ <Select value={SignerMemberRole.Administrator} disabled>+ <SelectTrigger size="sm" className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={SignerMemberRole.Administrator}>+ {signerMemberRoleLabels[SignerMemberRole.Administrator]}+ </SelectItem>+ </SelectContent>+ </Select>+ </TableCell>+ <TableCell />+ </TableRow>+ {state.pendingMembers.map((m) => (+ <TableRow key={`${m.kind}:${m.id}`} className="[&>td]:py-3">+ <TableCell isTruncatable>+ <div className="flex min-w-0 items-center gap-2">+ <KindIcon kind={m.kind} />+ <span className="truncate text-foreground">{m.label}</span>+ </div>+ </TableCell>+ <TableCell>+ <Badge variant="neutral">{KIND_LABEL[m.kind]}</Badge>+ </TableCell>+ <TableCell>+ <Select+ value={m.role}+ onValueChange={(v) => handleChangeRole(m.kind, m.id, v as SignerMemberRole)}+ >+ <SelectTrigger size="sm" className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper" align="start" sideOffset={4}>+ {Object.values(SignerMemberRole).map((role) => (+ <SelectItem+ key={role}+ value={role}+ description={signerMemberRoleDescriptions[role]}+ >+ {signerMemberRoleLabels[role]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </TableCell>+ <TableCell className="text-right">+ <Button+ variant="ghost"+ size="xs"+ onClick={() => handleRemove(m.kind, m.id)}+ aria-label="Remove member"+ >+ <XIcon className="h-3 w-3 text-muted" />+ </Button>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>++ <WizardAddMemberModal+ isOpen={isAddOpen}+ onOpenChange={setIsAddOpen}+ userOptions={userOptions}+ identityOptions={identityOptions}+ groupOptions={groupOptions}+ isUsersLoading={isUsersLoading}+ isIdentitiesLoading={isIdentitiesLoading}+ isGroupsLoading={isGroupsLoading}+ takenKeys={takenKeys}+ onAdd={handleAdd}+ />+ </div>+ );+};diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/index.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/index.tsnew file mode 100644index 0000000000..9ac08d43bf--- /dev/null+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/index.ts@@ -0,0 +1 @@+export { CreateSignerWizard } from "./CreateSignerWizard";diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.tsnew file mode 100644index 0000000000..1d4c3cf218--- /dev/null+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/schemas.ts@@ -0,0 +1,43 @@+import { z } from "zod";++import { SignerKeyAlgorithm } from "@app/hooks/api/signers";+import { slugSchema } from "@app/lib/schemas";++export const basicsSchema = z.object({+ name: slugSchema({ min: 1, max: 64, field: "Name" }),+ description: z.string().trim().max(256).optional()+});+export type BasicsForm = z.infer<typeof basicsSchema>;++export const certificateSchema = z+ .object({+ caId: z.string().uuid("Certificate Authority is required"),+ commonName: z.string().trim().min(1, "Common Name is required").max(256),+ certificateTtlDays: z.coerce.number().int().min(1).max(3650).default(365),+ renewBeforeDays: z+ .preprocess(+ (v) => {+ if (v === "" || v === null || v === undefined) return null;+ const n = typeof v === "number" ? v : Number(v);+ return Number.isNaN(n) ? v : n;+ },+ z.union([+ z+ .number()+ .int("Must be a whole number of days")+ .min(1, "Must be at least 1 day")+ .max(30, "Must be at most 30 days"),+ z.null()+ ])+ )+ .default(null),+ keyAlgorithm: z.nativeEnum(SignerKeyAlgorithm).default(SignerKeyAlgorithm.RSA_2048)+ })+ .refine(+ (data) => data.renewBeforeDays == null || data.renewBeforeDays < data.certificateTtlDays,+ {+ message: "Renew before must be less than the certificate validity (days).",+ path: ["renewBeforeDays"]+ }+ );+export type CertificateForm = z.infer<typeof certificateSchema>;diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.tsnew file mode 100644index 0000000000..e1c4abc248--- /dev/null+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/types.ts@@ -0,0 +1,125 @@+import { SignerKeyAlgorithm, SignerMemberRole } from "@app/hooks/api/signers";++export type CaGroup = "internal" | "external";+export type CaOption = { id: string; name: string; groupType: CaGroup };+export type MemberOption = { value: string; label: string };+export type ApproverOption = { value: string; label: string; kind: "user" | "group" };++export const approverOptionKey = (o: ApproverOption | { kind: "user" | "group"; value: string }) =>+ `${o.kind}:${o.value}`;++export type MemberKind = "user" | "identity" | "group";++export const KIND_LABEL: Record<MemberKind, string> = {+ user: "User",+ identity: "Machine Identity",+ group: "Group"+};++export type PendingMember = {+ kind: MemberKind;+ id: string;+ label: string;+ role: SignerMemberRole;+};++export type PolicyStep = {+ key: string;+ name: string;+ approverUserIds: string[];+ approverGroupIds: string[];+ requiredApprovals: number;+};++export type WizardState = {+ name: string;+ description: string;+ caId: string;+ commonName: string;+ certificateTtlDays: number;+ renewBeforeDays: number | null;+ keyAlgorithm: SignerKeyAlgorithm;+ pendingMembers: PendingMember[];+ policySteps: PolicyStep[];+ maxSignings: number | null;+ maxWindowDuration: string | null;+};++export const INITIAL_WIZARD_STATE: WizardState = {+ name: "",+ description: "",+ caId: "",+ commonName: "",+ certificateTtlDays: 365,+ renewBeforeDays: null,+ keyAlgorithm: SignerKeyAlgorithm.RSA_2048,+ pendingMembers: [],+ policySteps: [],+ maxSignings: 1,+ maxWindowDuration: null+};++export type WizardStep = {+ name: string;+ shortDescription: string;+ title: string;+ subtitle: string;+ rightLabel: string;+ rightDescription: string;+};++export const STEPS: WizardStep[] = [+ {+ name: "Basics",+ shortDescription: "Name and description",+ title: "Basics",+ subtitle: "A short name and what this signer is for.",+ rightLabel: "BASICS",+ rightDescription:+ "Set the signer's name and a short description so your team knows what it signs (for example, mobile-app-prod for production iOS and Android bundles)."+ },+ {+ name: "Certificate",+ shortDescription: "How it signs",+ title: "Certificate",+ subtitle: "Pick the Certificate Authority and the name on the certificate.",+ rightLabel: "CERTIFICATE",+ rightDescription:+ "Tells Infisical which CA issues the signing certificate, the name shown on it, and how long it stays valid. The Common Name is fixed once issued."+ },+ {+ name: "Members",+ shortDescription: "Who can sign",+ title: "Members",+ subtitle: "Add users, machine identities, or groups that can work with this signer.",+ rightLabel: "MEMBERS",+ rightDescription:+ "Choose who gets access. Each member has a role: Administrators manage the signer, Operators sign artifacts, Auditors read activity but cannot sign."+ },+ {+ name: "Approval Policy",+ shortDescription: "How approval works",+ title: "Approval Policy",+ subtitle: "Decide if signing needs approval, who approves it, and what each approval allows.",+ rightLabel: "APPROVAL POLICY",+ rightDescription:+ "When approval is on, members ask before signing. Steps run in order with approvers per step. Limits cap how many signatures and how long each approval is valid."+ }+];++export const NO_WINDOW_LIMIT = "__no_limit__";++export const WINDOW_DURATION_OPTIONS = [+ { label: "No limit", value: NO_WINDOW_LIMIT },+ { label: "1 hour", value: "1h" },+ { label: "8 hours", value: "8h" },+ { label: "24 hours", value: "24h" },+ { label: "7 days", value: "7d" },+ { label: "30 days", value: "30d" }+];++let stepCounter = 0;+export const makeStepKey = () => {+ stepCounter += 1;+ return `step-${Date.now()}-${stepCounter}`;+};diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/SignersTable.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/SignersTable.tsxindex 262ad1397c..d785192f8e 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/SignersTable.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/SignersTable.tsx@@ -1,19 +1,9 @@import { useState } from "react";import { useNavigate } from "@tanstack/react-router";import { format } from "date-fns";-import {- BanIcon,- CheckCircleIcon,- ClipboardCopyIcon,- KeyRoundIcon,- MoreHorizontalIcon,- PencilIcon,- PlusIcon,- SearchIcon-} from "lucide-react";+import { PlusIcon, SearchIcon } from "lucide-react";import { ProjectPermissionCan } from "@app/components/permissions";-import { DeleteActionModal } from "@app/components/v2";import {Badge,Button,@@ -24,15 +14,10 @@ import {CardHeader,CardTitle,DocumentationLinkBadge,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,Empty,EmptyDescription,EmptyHeader,EmptyTitle,- IconButton,InputGroup,InputGroupAddon,InputGroupInput,@@ -42,7 +27,11 @@ import {TableCell,TableHead,TableHeader,- TableRow+ TableRow,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger} from "@app/components/v3";import {ProjectPermissionCodeSigningActions,@@ -51,36 +40,27 @@ import {} from "@app/context";import {getSignerStatusBadgeVariant,+ SIGNER_TABLE_PAGE_SIZE,SignerStatus,signerStatusLabels,- TSigner,- useDeleteSigner,- useListSigners,- useUpdateSigner+ useListSigners} from "@app/hooks/api/signers";import { useDebounce } from "@app/hooks/useDebounce";-import { RequestSigningAccessModal } from "../../ApprovalsPage/components/CodeSigningRequestsTab/RequestSigningAccessModal";import { PkiDocsUrls } from "../../pki-docs-urls";-import { EditSignerModal } from "../../SignerDetailPage/components/EditSignerModal";type Props = {projectId: string;onCreateSigner: () => void;};-const PAGE_SIZE = 25;-export const SignersTable = ({ projectId, onCreateSigner }: Props) => {const navigate = useNavigate();const { currentOrg } = useOrganization();const [page, setPage] = useState(1);- const [perPage, setPerPage] = useState(PAGE_SIZE);+ const [perPage, setPerPage] = useState(SIGNER_TABLE_PAGE_SIZE);const [search, setSearch] = useState("");const [debouncedSearch] = useDebounce(search, 300);- const [deleteSignerId, setDeleteSignerId] = useState<string | null>(null);- const [editSigner, setEditSigner] = useState<TSigner | null>(null);- const [requestAccessSigner, setRequestAccessSigner] = useState<TSigner | null>(null);const { data, isLoading } = useListSigners({projectId,@@ -89,243 +69,130 @@ export const SignersTable = ({ projectId, onCreateSigner }: Props) => {search: debouncedSearch || undefined});- const deleteSigner = useDeleteSigner();- const updateSigner = useUpdateSigner();-const signers = data?.signers ?? [];const totalCount = data?.totalCount ?? 0;- const handleDeleteConfirm = async () => {- if (!deleteSignerId) return;- await deleteSigner.mutateAsync({ signerId: deleteSignerId, projectId });- setDeleteSignerId(null);- };-return (- <>- <Card>- <CardHeader>- <CardTitle>- Signers- <DocumentationLinkBadge href={PkiDocsUrls.codeSigning.signers} />- </CardTitle>- <CardDescription>Manage signers and control who can sign artifacts.</CardDescription>- <CardAction>- <ProjectPermissionCan- I={ProjectPermissionCodeSigningActions.Create}- a={ProjectPermissionSub.CodeSigners}- >- {(isAllowed) => (- <Button variant="project" isDisabled={!isAllowed} onClick={onCreateSigner}>- <PlusIcon />- Create Signer- </Button>- )}- </ProjectPermissionCan>- </CardAction>- </CardHeader>- <CardContent>- <div className="mb-4 flex gap-2">- <InputGroup className="flex-1">- <InputGroupAddon>- <SearchIcon />- </InputGroupAddon>- <InputGroupInput- value={search}- onChange={(e) => {- setSearch(e.target.value);- setPage(1);- }}- placeholder="Search signers by name..."- />- </InputGroup>- </div>- <Table>- <TableHeader>- <TableRow>- <TableHead>Name</TableHead>- <TableHead>Status</TableHead>- <TableHead>Certificate CN</TableHead>- <TableHead>Policy</TableHead>- <TableHead>Certificate Expiry</TableHead>- <TableHead>Last Signed</TableHead>- <TableHead className="w-5" />- </TableRow>- </TableHeader>- <TableBody>- {!isLoading &&- signers.map((signer) => (- <TableRow- key={signer.id}- className="cursor-pointer hover:bg-mineshaft-700"- onClick={() =>- navigate({- to: "/organizations/$orgId/projects/cert-manager/$projectId/code-signing/$signerId",- params: {- orgId: currentOrg.id,- projectId,- signerId: signer.id- }- })- }- >- <TableCell>{signer.name}</TableCell>- <TableCell>+ <Card>+ <CardHeader>+ <CardTitle>+ Signers+ <DocumentationLinkBadge href={PkiDocsUrls.codeSigning.signers} />+ </CardTitle>+ <CardDescription>Manage signers and control who can sign artifacts.</CardDescription>+ <CardAction>+ <ProjectPermissionCan+ I={ProjectPermissionCodeSigningActions.Create}+ a={ProjectPermissionSub.CodeSigners}+ >+ {(isAllowed) => (+ <Button variant="project" isDisabled={!isAllowed} onClick={onCreateSigner}>+ <PlusIcon />+ Create Signer+ </Button>+ )}+ </ProjectPermissionCan>+ </CardAction>+ </CardHeader>+ <CardContent>+ <div className="mb-4 flex gap-2">+ <InputGroup className="flex-1">+ <InputGroupAddon>+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ value={search}+ onChange={(e) => {+ setSearch(e.target.value);+ setPage(1);+ }}+ placeholder="Search signers by name..."+ />+ </InputGroup>+ </div>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Name</TableHead>+ <TableHead>Status</TableHead>+ <TableHead>Certificate CN</TableHead>+ <TableHead>Certificate Expiry</TableHead>+ <TableHead>Last Signed</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {!isLoading &&+ signers.map((signer) => (+ <TableRow+ key={signer.id}+ className="cursor-pointer hover:bg-mineshaft-700"+ onClick={() =>+ navigate({+ to: "/organizations/$orgId/projects/cert-manager/$projectId/code-signing/$signerId",+ params: {+ orgId: currentOrg.id,+ projectId,+ signerId: signer.id+ }+ })+ }+ >+ <TableCell>{signer.name}</TableCell>+ <TableCell>+ {signer.status === SignerStatus.Failed && signer.failureReason ? (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="cursor-help">+ <Badge variant={getSignerStatusBadgeVariant(signer.status)}>+ {signerStatusLabels[signer.status] ?? signer.status}+ </Badge>+ </span>+ </TooltipTrigger>+ <TooltipContent className="max-w-[260px] text-pretty break-words">+ {signer.failureReason}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ ) : (<Badge variant={getSignerStatusBadgeVariant(signer.status)}>{signerStatusLabels[signer.status] ?? signer.status}</Badge>- </TableCell>- <TableCell>{signer.certificateCommonName ?? "-"}</TableCell>- <TableCell>{signer.approvalPolicyName ?? "-"}</TableCell>- <TableCell>- {signer.certificateNotAfter- ? format(new Date(signer.certificateNotAfter), "MMM d, yyyy")- : "-"}- </TableCell>- <TableCell>- {signer.lastSignedAt- ? format(new Date(signer.lastSignedAt), "MMM d, yyyy HH:mm")- : "Never"}- </TableCell>- <TableCell>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton variant="ghost" onClick={(e) => e.stopPropagation()}>- <MoreHorizontalIcon />- </IconButton>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>- <DropdownMenuItem- onClick={(e) => {- e.stopPropagation();- navigator.clipboard.writeText(signer.id);- }}- >- <ClipboardCopyIcon />- Copy ID- </DropdownMenuItem>- {signer.approvalPolicyId ? (- <DropdownMenuItem- onClick={(e) => {- e.stopPropagation();- setRequestAccessSigner(signer);- }}- >- <KeyRoundIcon />- Request Signing Access- </DropdownMenuItem>- ) : null}- <ProjectPermissionCan- I={ProjectPermissionCodeSigningActions.Edit}- a={ProjectPermissionSub.CodeSigners}- >- {(isAllowed) => (- <DropdownMenuItem- isDisabled={!isAllowed}- onClick={() => setEditSigner(signer)}- >- <PencilIcon />- Edit Signer- </DropdownMenuItem>- )}- </ProjectPermissionCan>- <ProjectPermissionCan- I={ProjectPermissionCodeSigningActions.Edit}- a={ProjectPermissionSub.CodeSigners}- >- {(isAllowed) => (- <DropdownMenuItem- isDisabled={!isAllowed}- onClick={() =>- updateSigner.mutateAsync({- signerId: signer.id,- status:- signer.status === SignerStatus.Active- ? SignerStatus.Disabled- : SignerStatus.Active- })- }- >- {signer.status === SignerStatus.Active ? (- <>- <BanIcon />- Disable Signer- </>- ) : (- <>- <CheckCircleIcon />- Enable Signer- </>- )}- </DropdownMenuItem>- )}- </ProjectPermissionCan>- <ProjectPermissionCan- I={ProjectPermissionCodeSigningActions.Delete}- a={ProjectPermissionSub.CodeSigners}- >- {(isAllowed) => (- <DropdownMenuItem- variant="danger"- isDisabled={!isAllowed}- onClick={() => setDeleteSignerId(signer.id)}- >- Delete Signer- </DropdownMenuItem>- )}- </ProjectPermissionCan>- </DropdownMenuContent>- </DropdownMenu>- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- {!isLoading && signers.length === 0 && (- <Empty className="border border-solid">- <EmptyHeader>- <EmptyTitle>No signers yet</EmptyTitle>- <EmptyDescription>Create a signer to start signing artifacts</EmptyDescription>- </EmptyHeader>- </Empty>- )}- {Boolean(totalCount) && (- <Pagination- count={totalCount}- page={page}- perPage={perPage}- onChangePage={setPage}- onChangePerPage={setPerPage}- />- )}- </CardContent>- </Card>- <DeleteActionModal- isOpen={Boolean(deleteSignerId)}- deleteKey="delete"- title="Are you sure you want to delete this signer?"- onChange={(isOpen) => {- if (!isOpen) setDeleteSignerId(null);- }}- onDeleteApproved={handleDeleteConfirm}- />- {editSigner && (- <EditSignerModal- isOpen={Boolean(editSigner)}- onOpenChange={(open) => {- if (!open) setEditSigner(null);- }}- signer={editSigner}- projectId={projectId}- />- )}- <RequestSigningAccessModal- isOpen={Boolean(requestAccessSigner)}- onOpenChange={(open) => {- if (!open) setRequestAccessSigner(null);- }}- signer={requestAccessSigner ?? undefined}- />- </>+ )}+ </TableCell>+ <TableCell>{signer.certificateCommonName ?? "-"}</TableCell>+ <TableCell>+ {signer.certificateNotAfter+ ? format(new Date(signer.certificateNotAfter), "MMM d, yyyy")+ : "-"}+ </TableCell>+ <TableCell>+ {signer.lastSignedAt+ ? format(new Date(signer.lastSignedAt), "MMM d, yyyy HH:mm")+ : "Never"}+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ {!isLoading && signers.length === 0 && (+ <Empty className="border border-solid">+ <EmptyHeader>+ <EmptyTitle>No signers yet</EmptyTitle>+ <EmptyDescription>Create a signer to start signing artifacts</EmptyDescription>+ </EmptyHeader>+ </Empty>+ )}+ {Boolean(totalCount) && (+ <Pagination+ count={totalCount}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={setPerPage}+ />+ )}+ </CardContent>+ </Card>);};diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/WizardAddMemberModal.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/WizardAddMemberModal.tsxnew file mode 100644index 0000000000..90d5393ad9--- /dev/null+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/WizardAddMemberModal.tsx@@ -0,0 +1,193 @@+import { useEffect, useState } from "react";+import { HardDriveIcon, UserIcon, UsersIcon } from "lucide-react";++import {+ Button,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldContent,+ FieldGroup,+ FieldLabel,+ FilterableSelect,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3";+import {+ SignerMemberRole,+ signerMemberRoleDescriptions,+ signerMemberRoleLabels+} from "@app/hooks/api/signers";++export type WizardMemberKind = "user" | "identity" | "group";+type Option = { value: string; label: string };++type Props = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ userOptions: Option[];+ identityOptions: Option[];+ groupOptions: Option[];+ isUsersLoading: boolean;+ isIdentitiesLoading: boolean;+ isGroupsLoading: boolean;+ takenKeys: Set<string>;+ onAdd: (member: {+ kind: WizardMemberKind;+ id: string;+ label: string;+ role: SignerMemberRole;+ }) => void;+};++const KIND_LABEL: Record<WizardMemberKind, string> = {+ user: "User",+ identity: "Machine Identity",+ group: "Group"+};++export const WizardAddMemberModal = ({+ isOpen,+ onOpenChange,+ userOptions,+ identityOptions,+ groupOptions,+ isUsersLoading,+ isIdentitiesLoading,+ isGroupsLoading,+ takenKeys,+ onAdd+}: Props) => {+ const [kind, setKind] = useState<WizardMemberKind>("user");+ const [member, setMember] = useState<Option | null>(null);+ const [role, setRole] = useState<SignerMemberRole>(SignerMemberRole.Operator);++ useEffect(() => {+ if (!isOpen) {+ setKind("user");+ setMember(null);+ setRole(SignerMemberRole.Operator);+ }+ }, [isOpen]);++ const optionsByKind: Record<WizardMemberKind, Option[]> = {+ user: userOptions,+ identity: identityOptions,+ group: groupOptions+ };+ const loadingByKind: Record<WizardMemberKind, boolean> = {+ user: isUsersLoading,+ identity: isIdentitiesLoading,+ group: isGroupsLoading+ };+ // eslint-disable-next-line no-nested-ternary+ const Icon = kind === "user" ? UserIcon : kind === "identity" ? HardDriveIcon : UsersIcon;++ const filteredOptions = optionsByKind[kind].filter((o) => !takenKeys.has(`${kind}:${o.value}`));++ const handleAdd = () => {+ if (!member) return;+ onAdd({ kind, id: member.value, label: member.label, role });+ onOpenChange(false);+ };++ return (+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>Add member</DialogTitle>+ <DialogDescription>+ Pick a user, machine identity, or group, and the role they should have on this signer.+ </DialogDescription>+ </DialogHeader>++ <FieldGroup>+ <Field>+ <FieldLabel>Type</FieldLabel>+ <FieldContent>+ <Select+ value={kind}+ onValueChange={(v) => {+ setKind(v as WizardMemberKind);+ setMember(null);+ }}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(["user", "identity", "group"] as WizardMemberKind[]).map((k) => (+ <SelectItem key={k} value={k}>+ <span className="flex items-center gap-2">+ {/* eslint-disable-next-line no-nested-ternary */}+ {k === "user" ? (+ <UserIcon className="h-3.5 w-3.5" />+ ) : k === "identity" ? (+ <HardDriveIcon className="h-3.5 w-3.5" />+ ) : (+ <UsersIcon className="h-3.5 w-3.5" />+ )}+ {KIND_LABEL[k]}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FieldContent>+ </Field>++ <Field>+ <FieldLabel>{KIND_LABEL[kind]}</FieldLabel>+ <FieldContent>+ <FilterableSelect+ isLoading={loadingByKind[kind]}+ options={filteredOptions}+ value={member}+ onChange={(selected) => setMember((selected as Option | null) ?? null)}+ placeholder={`Pick a ${KIND_LABEL[kind].toLowerCase()}...`}+ noOptionsMessage={() =>+ `No ${KIND_LABEL[kind].toLowerCase()}s available — they may already be added.`+ }+ />+ </FieldContent>+ </Field>++ <Field>+ <FieldLabel>Role</FieldLabel>+ <FieldContent>+ <Select value={role} onValueChange={(v) => setRole(v as SignerMemberRole)}>+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper" align="start" sideOffset={4}>+ {Object.values(SignerMemberRole).map((r) => (+ <SelectItem key={r} value={r} description={signerMemberRoleDescriptions[r]}>+ {signerMemberRoleLabels[r]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FieldContent>+ </Field>+ </FieldGroup>++ <DialogFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button variant="project" onClick={handleAdd} isDisabled={!member}>+ <Icon className="h-3.5 w-3.5" />+ <span>Add to signer</span>+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/index.ts b/frontend/src/pages/cert-manager/CodeSigningPage/components/index.tsindex f11de4d68f..b82bcba68f 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/index.ts+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/index.ts@@ -1,2 +1,2 @@-export { CreateSignerModal } from "./CreateSignerModal";+export { CreateSignerWizard } from "./CreateSignerWizard";export { SignersTable } from "./SignersTable";diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/route.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/route.tsxindex 3ea1eac215..418e6592e5 100644--- a/frontend/src/pages/cert-manager/CodeSigningPage/route.tsx+++ b/frontend/src/pages/cert-manager/CodeSigningPage/route.tsx@@ -1,20 +1,11 @@import { createFileRoute } from "@tanstack/react-router";-import { zodValidator } from "@tanstack/zod-adapter";-import { z } from "zod";import { CodeSigningPage } from "./CodeSigningPage";-const CodeSigningSearchSchema = z.object({- selectedTab: z.string().optional().default("signers"),- tab: z.enum(["signers", "approvals"]).optional(),- subtab: z.enum(["requests", "policies", "grants"]).optional()-});-export const Route = createFileRoute("/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/code-signing/")({component: CodeSigningPage,- validateSearch: zodValidator(CodeSigningSearchSchema),beforeLoad: ({ context }) => {return {breadcrumbs: [diff --git a/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx b/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsxindex df07cd7469..4ef60662d4 100644--- a/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx+++ b/frontend/src/pages/cert-manager/RequestsPage/RequestsPage.tsx@@ -95,15 +95,13 @@ 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)- );+const getCodeSigningData = (data: unknown): CodeSigningRequestData | null => {+ if (!data || typeof data !== "object") return null;+ const wrapped = (data as { requestData?: unknown }).requestData;+ if (wrapped && typeof wrapped === "object" && "signerName" in (wrapped as object)) {+ return wrapped as CodeSigningRequestData;+ }+ return null;};export const RequestsPage = () => {@@ -205,9 +203,7 @@ export const RequestsPage = () => {.filter((r) => matchesStatus(r.status as ApprovalRequestStatus)).filter((r) => {if (!norm) return true;- const signerName = isCodeSigningData(r.requestData)- ? (r.requestData.requestData.signerName ?? "")- : "";+ const signerName = getCodeSigningData(r.requestData)?.signerName ?? "";const requester = `${r.requesterName} ${r.requesterEmail}`;return signerName.toLowerCase().includes(norm) || requester.toLowerCase().includes(norm);});@@ -484,9 +480,7 @@ export const RequestsPage = () => {</TableHeader><TableBody>{filteredSigning.map((r) => {- const signingData = isCodeSigningData(r.requestData)- ? r.requestData.requestData- : null;+ const signingData = getCodeSigningData(r.requestData);const signerName = signingData?.signerName ?? "—";const badge = STATUS_BADGE[r.status as ApprovalRequestStatus] ?? {label: r.status,diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/SignerDetailPage.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/SignerDetailPage.tsxindex a69f4c2cca..238de8e1af 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/SignerDetailPage.tsx+++ b/frontend/src/pages/cert-manager/SignerDetailPage/SignerDetailPage.tsx@@ -1,92 +1,328 @@import { useState } from "react";import { Helmet } from "react-helmet";import { useTranslation } from "react-i18next";-import { Link, useParams } from "@tanstack/react-router";-import { ChevronLeftIcon } from "lucide-react";+import { Link, useNavigate, useParams, useSearch } from "@tanstack/react-router";+import {+ AlertTriangleIcon,+ BanIcon,+ CheckCircleIcon,+ ChevronLeftIcon,+ CopyIcon,+ DownloadIcon,+ MoreVerticalIcon,+ PencilIcon,+ PenTool,+ RotateCwIcon,+ Trash2Icon+} from "lucide-react";-import { EmptyState, PageHeader } from "@app/components/v2";-import { Badge, DocumentationLinkBadge, PageLoader } from "@app/components/v3";+import { createNotification } from "@app/components/notifications";+import { PageHeader } from "@app/components/v2";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogMedia,+ AlertDialogTitle,+ Badge,+ Button,+ DocumentationLinkBadge,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Empty,+ EmptyHeader,+ EmptyTitle,+ PageLoader,+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger+} from "@app/components/v3";import { ROUTE_PATHS } from "@app/const/routes";import { useOrganization, useProject } from "@app/context";import { ProjectType } from "@app/hooks/api/projects/types";import {getSignerStatusBadgeVariant,+ SignerStatus,signerStatusLabels,- useGetSigner+ useDeleteSigner,+ useDisableSigner,+ useEnableSigner,+ useGetSigner,+ useGetSignerMyPermissions,+ useReissueSignerCertificate} from "@app/hooks/api/signers";import { PkiDocsUrls } from "../pki-docs-urls";import { EditSignerModal } from "./components/EditSignerModal";-import { SignerOverviewSection } from "./components/SignerOverviewSection";+import { ExportSignerCertModal } from "./components/ExportSignerCertModal";+import { SignerApprovalPolicyTab } from "./components/SignerApprovalPolicyTab";+import { SignerMembersTab } from "./components/SignerMembersTab";+import { SignerRequestsTab } from "./components/SignerRequestsTab";import { SigningOperationsTable } from "./components/SigningOperationsTable";+type Tab = "activity" | "approvals" | "members";+export const SignerDetailPage = () => {const { t } = useTranslation();const { currentOrg } = useOrganization();const { currentProject } = useProject();- const [isEditOpen, setIsEditOpen] = useState(false);+ const navigate = useNavigate();+const { signerId } = useParams({from: ROUTE_PATHS.CertManager.SignerDetailByIDPage.id});+ const { selectedTab } = useSearch({+ from: ROUTE_PATHS.CertManager.SignerDetailByIDPage.id+ });++ const activeTab: Tab = selectedTab ?? "activity";++ const [isEditOpen, setIsEditOpen] = useState(false);+ const [isDeleteOpen, setIsDeleteOpen] = useState(false);+ const [isExportOpen, setIsExportOpen] = useState(false);const { data: signer, isLoading } = useGetSigner(signerId);+ const { data: myPerms } = useGetSignerMyPermissions(signerId);+ const enableSigner = useEnableSigner();+ const disableSigner = useDisableSigner();+ const deleteSigner = useDeleteSigner();+ const reissueSigner = useReissueSignerCertificate();++ if (isLoading) return <PageLoader />;+ if (!signer)+ return (+ <Empty>+ <EmptyHeader>+ <EmptyTitle>Signer not found</EmptyTitle>+ </EmptyHeader>+ </Empty>+ );- if (isLoading) {- return <PageLoader />;- }+ const onCopyId = async () => {+ await navigator.clipboard.writeText(signer.id);+ createNotification({ type: "success", text: "Signer ID copied" });+ };- if (!signer) {- return <EmptyState title="Signer not found" />;- }+ const onOpenExport = () => setIsExportOpen(true);return (- <div className="mx-auto flex h-full flex-col justify-between bg-bunker-800 text-white">+ <><Helmet><title>{t("common.head-title", { title: `Signer: ${signer.name}` })}</title></Helmet>- <div className="mx-auto mb-6 w-full max-w-8xl">- <div className="mb-4">- <Link- to="/organizations/$orgId/projects/cert-manager/$projectId/code-signing"- params={{ orgId: currentOrg.id, projectId: currentProject.id }}- className="flex w-fit items-center gap-x-1 text-sm text-mineshaft-400 transition duration-100 hover:text-mineshaft-400/80"- >- <ChevronLeftIcon size={16} />- Back to Code Signing- </Link>- </div>- <PageHeader- scope={ProjectType.CertificateManager}- title={- <span className="inline-flex items-center gap-x-3">- {signer.name}- <Badge variant={getSignerStatusBadgeVariant(signer.status)}>- {signerStatusLabels[signer.status] ?? signer.status}- </Badge>- <DocumentationLinkBadge href={PkiDocsUrls.codeSigning.signers} />- </span>- }- description={signer.description ?? undefined}- />- <div className="flex flex-col gap-5 lg:flex-row">- <div className="w-full lg:max-w-[24rem]">- <SignerOverviewSection- signer={signer}- projectId={currentProject.id}- onEdit={() => setIsEditOpen(true)}- />- </div>- <div className="flex flex-1 flex-col gap-5">- <SigningOperationsTable signerId={signerId} projectId={currentProject.id} />+ <div className="h-full bg-bunker-800">+ <div className="mx-auto flex flex-col text-white">+ <div className="mx-auto mb-6 w-full max-w-8xl">+ <div className="mb-4">+ <Link+ to={ROUTE_PATHS.CertManager.CodeSigningPage.path}+ params={{ orgId: currentOrg.id, projectId: currentProject.id }}+ className="flex w-fit items-center gap-x-1 text-sm text-mineshaft-400 transition duration-100 hover:text-mineshaft-400/80"+ >+ <ChevronLeftIcon size={16} />+ Back to Signers+ </Link>+ </div>++ <PageHeader+ scope={ProjectType.CertificateManager}+ icon={PenTool}+ title={+ <span className="inline-flex items-center gap-x-2 align-middle">+ {signer.name}+ <DocumentationLinkBadge href={PkiDocsUrls.codeSigning.signers} />+ {signer.status === SignerStatus.Failed && signer.failureReason ? (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="cursor-help">+ <Badge variant={getSignerStatusBadgeVariant(signer.status)}>+ {signerStatusLabels[signer.status] ?? signer.status}+ </Badge>+ </span>+ </TooltipTrigger>+ <TooltipContent className="max-w-[260px] text-pretty break-words">+ {signer.failureReason}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ ) : (+ <Badge variant={getSignerStatusBadgeVariant(signer.status)}>+ {signerStatusLabels[signer.status] ?? signer.status}+ </Badge>+ )}+ </span>+ }+ description={signer.description ?? undefined}+ >+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="outline" size="xs">+ <MoreVerticalIcon />+ Options+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={2}>+ <DropdownMenuItem onClick={onCopyId}>+ <CopyIcon />+ Copy Signer ID+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={onOpenExport}+ isDisabled={!signer.certificateId || myPerms?.canExportCertificate === false}+ >+ <DownloadIcon />+ Export certificate+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => setIsEditOpen(true)}+ isDisabled={myPerms?.canEdit === false}+ >+ <PencilIcon />+ Edit settings+ </DropdownMenuItem>+ {/* eslint-disable-next-line no-nested-ternary */}+ {signer.status === SignerStatus.Active ? (+ <DropdownMenuItem+ onClick={() => disableSigner.mutate({ signerId: signer.id })}+ isDisabled={myPerms?.canEnableDisable === false}+ >+ <BanIcon />+ Disable signer+ </DropdownMenuItem>+ ) : signer.status === SignerStatus.Disabled ? (+ <DropdownMenuItem+ onClick={() => enableSigner.mutate({ signerId: signer.id })}+ isDisabled={myPerms?.canEnableDisable === false}+ >+ <CheckCircleIcon />+ Enable signer+ </DropdownMenuItem>+ ) : null}+ {signer.status === SignerStatus.Failed && signer.caId && (+ <DropdownMenuItem+ onClick={() =>+ reissueSigner.mutate({ signerId: signer.id, caId: signer.caId! })+ }+ isDisabled={myPerms?.canReissueCertificate === false}+ >+ <RotateCwIcon />+ Retry issuance+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ variant="danger"+ onClick={() => setIsDeleteOpen(true)}+ isDisabled={myPerms?.canDelete === false}+ >+ <Trash2Icon />+ Delete signer+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </PageHeader>++ {!signer.caId && (+ <div className="mb-4 rounded-md border border-warning/40 bg-warning/10 p-3 text-sm text-warning">+ This signer has no Certificate Authority attached, so its certificate cannot be+ auto-renewed. Once it expires, signing will stop until you create a new signer.+ </div>+ )}++ <Tabs+ value={activeTab}+ onValueChange={(v) =>+ navigate({+ to: ROUTE_PATHS.CertManager.SignerDetailByIDPage.path,+ params: { orgId: currentOrg.id, projectId: currentProject.id, signerId },+ search: { selectedTab: v as Tab }+ })+ }+ >+ <TabsList variant="project" className="w-full justify-start">+ <TabsTrigger value="activity" className="flex-none">+ Activity+ </TabsTrigger>+ <TabsTrigger value="approvals" className="flex-none">+ Approvals+ </TabsTrigger>+ <TabsTrigger value="members" className="flex-none">+ Members+ </TabsTrigger>+ </TabsList>++ <TabsContent value="activity" className="pt-2">+ <SigningOperationsTable signerId={signerId} projectId={currentProject.id} />+ </TabsContent>+ <TabsContent value="approvals" className="pt-2">+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,5fr)]">+ <SignerApprovalPolicyTab signerId={signerId} />+ <SignerRequestsTab+ signerId={signerId}+ canPreApprove={myPerms?.canPreApprove ?? false}+ canRequestSign={myPerms?.canRequestSign ?? false}+ />+ </div>+ </TabsContent>+ <TabsContent value="members" className="pt-2">+ <SignerMembersTab signerId={signerId} />+ </TabsContent>+ </Tabs></div></div></div>- <EditSignerModal- isOpen={isEditOpen}- onOpenChange={setIsEditOpen}- signer={signer}- projectId={currentProject.id}++ <EditSignerModal isOpen={isEditOpen} onOpenChange={setIsEditOpen} signer={signer} />+ <ExportSignerCertModal+ isOpen={isExportOpen}+ onOpenChange={setIsExportOpen}+ signerId={signer.id}+ signerName={signer.name}/>- </div>+ <AlertDialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogMedia>+ <AlertTriangleIcon className="text-danger" />+ </AlertDialogMedia>+ <AlertDialogTitle>Delete signer '{signer.name}'?</AlertDialogTitle>+ <AlertDialogDescription>+ This permanently removes the signer, its policy, members, requests, and signing+ history. The certificate is preserved for audit but signing will stop immediately.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel isDisabled={deleteSigner.isPending}>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="danger"+ isDisabled={deleteSigner.isPending}+ onClick={async () => {+ await deleteSigner.mutateAsync({+ signerId: signer.id,+ projectId: signer.projectId+ });+ navigate({+ to: ROUTE_PATHS.CertManager.CodeSigningPage.path,+ params: { orgId: currentOrg.id, projectId: currentProject.id }+ });+ }}+ >+ Delete signer+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>);};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/AddSignerMemberModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/AddSignerMemberModal.tsxnew file mode 100644index 0000000000..292885a81a--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/AddSignerMemberModal.tsx@@ -0,0 +1,273 @@+import { useMemo, useState } from "react";+import { HardDriveIcon, UserIcon, UsersIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ ButtonGroup,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldContent,+ FieldGroup,+ FieldLabel,+ FilterableSelect,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3";+import { useOrganization, useProject } from "@app/context";+import {+ useGetIdentityMembershipOrgs,+ useGetOrganizationGroups+} from "@app/hooks/api/organization";+import { useListProjectIdentityMemberships } from "@app/hooks/api/projectIdentityMembership";+import { ProjectType } from "@app/hooks/api/projects/types";+import {+ SignerMemberRole,+ signerMemberRoleDescriptions,+ signerMemberRoleLabels,+ TSignerMember,+ useAddSignerGroupMember,+ useAddSignerIdentityMember,+ useAddSignerUserMembers+} from "@app/hooks/api/signers";+import { useGetOrgUsers } from "@app/hooks/api/users";++type Props = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ signerId: string;+ existingMembers: TSignerMember[];+};++type Kind = "user" | "identity" | "group";++type Option = { value: string; label: string };++export const AddSignerMemberModal = ({+ isOpen,+ onOpenChange,+ signerId,+ existingMembers+}: Props) => {+ const { currentOrg } = useOrganization();+ const { currentProject } = useProject();+ const orgId = currentOrg?.id ?? "";+ const projectId = currentProject?.id ?? "";++ const [kind, setKind] = useState<Kind>("user");+ const [selectedUsers, setSelectedUsers] = useState<Option[]>([]);+ const [selectedIdentities, setSelectedIdentities] = useState<Option[]>([]);+ const [selectedGroups, setSelectedGroups] = useState<Option[]>([]);+ const [role, setRole] = useState<SignerMemberRole>(SignerMemberRole.Operator);+ const [submitting, setSubmitting] = useState(false);++ const usersQuery = useGetOrgUsers(orgId);+ const orgIdentitiesQuery = useGetIdentityMembershipOrgs({ organizationId: orgId, limit: 100 });+ const projectIdentitiesQuery = useListProjectIdentityMemberships({+ projectId,+ projectType: ProjectType.CertificateManager,+ limit: 1000+ });+ const groupsQuery = useGetOrganizationGroups(orgId);++ const addUserMembers = useAddSignerUserMembers();+ const addIdentityMember = useAddSignerIdentityMember();+ const addGroupMember = useAddSignerGroupMember();++ const taken = useMemo(() => {+ const set = new Set<string>();+ existingMembers.forEach((m) => {+ if (m.actorUserId) set.add(`user:${m.actorUserId}`);+ if (m.actorIdentityId) set.add(`identity:${m.actorIdentityId}`);+ if (m.actorGroupId) set.add(`group:${m.actorGroupId}`);+ });+ return set;+ }, [existingMembers]);++ const userOptions: Option[] = useMemo(() => {+ return (usersQuery.data ?? [])+ .filter((u) => !taken.has(`user:${u.user.id}`))+ .map((u) => ({+ value: u.user.id,+ label:+ [u.user.firstName, u.user.lastName].filter(Boolean).join(" ").trim() ||+ u.user.username ||+ u.user.email ||+ u.user.id+ }));+ }, [usersQuery.data, taken]);++ const identityOptions: Option[] = useMemo(() => {+ const seen = new Set<string>();+ const collect = (id: string, name: string) => {+ if (seen.has(id) || taken.has(`identity:${id}`)) return null;+ seen.add(id);+ return { value: id, label: name };+ };+ const fromOrg = (orgIdentitiesQuery.data?.identityMemberships ?? [])+ .map((im) => collect(im.identity.id, im.identity.name))+ .filter((opt): opt is Option => opt !== null);+ const fromProject = (projectIdentitiesQuery.data?.identityMemberships ?? [])+ .map((im) => collect(im.identity.id, im.identity.name))+ .filter((opt): opt is Option => opt !== null);+ return [...fromOrg, ...fromProject].sort((a, b) => a.label.localeCompare(b.label));+ }, [orgIdentitiesQuery.data, projectIdentitiesQuery.data, taken]);++ const groupOptions: Option[] = useMemo(() => {+ return (groupsQuery.data ?? [])+ .filter((g) => !taken.has(`group:${g.id}`))+ .map((g) => ({ value: g.id, label: g.name }));+ }, [groupsQuery.data, taken]);++ const reset = () => {+ setKind("user");+ setSelectedUsers([]);+ setSelectedIdentities([]);+ setSelectedGroups([]);+ setRole(SignerMemberRole.Operator);+ };++ const handleClose = (open: boolean) => {+ if (!open) reset();+ onOpenChange(open);+ };++ const onSubmit = async () => {+ setSubmitting(true);+ try {+ if (kind === "user" && selectedUsers.length > 0) {+ await addUserMembers.mutateAsync({+ signerId,+ userIds: selectedUsers.map((u) => u.value),+ emails: [],+ role+ });+ }+ if (kind === "identity" && selectedIdentities.length > 0) {+ await Promise.all(+ selectedIdentities.map((identity) =>+ addIdentityMember.mutateAsync({ signerId, identityId: identity.value, role })+ )+ );+ createNotification({ type: "success", text: "Members added" });+ }+ if (kind === "group" && selectedGroups.length > 0) {+ await Promise.all(+ selectedGroups.map((group) =>+ addGroupMember.mutateAsync({ signerId, groupId: group.value, role })+ )+ );+ createNotification({ type: "success", text: "Members added" });+ }+ handleClose(false);+ } catch (err) {+ createNotification({+ type: "error",+ text: err instanceof Error ? err.message : "Failed to add members"+ });+ } finally {+ setSubmitting(false);+ }+ };++ const valueForKind =+ // eslint-disable-next-line no-nested-ternary+ kind === "user" ? selectedUsers : kind === "identity" ? selectedIdentities : selectedGroups;++ const optionsForKind =+ // eslint-disable-next-line no-nested-ternary+ kind === "user" ? userOptions : kind === "identity" ? identityOptions : groupOptions;++ const setSelected = (next: Option[]) => {+ if (kind === "user") setSelectedUsers(next);+ else if (kind === "identity") setSelectedIdentities(next);+ else setSelectedGroups(next);+ };++ return (+ <Dialog open={isOpen} onOpenChange={handleClose}>+ <DialogContent className="max-w-xl">+ <DialogHeader>+ <DialogTitle>Add member</DialogTitle>+ <DialogDescription>+ Pick existing org members, machine identities, or groups to attach to this signer.+ </DialogDescription>+ </DialogHeader>++ <FieldGroup>+ <ButtonGroup className="w-full">+ {[+ { value: "user" as const, label: "Users", icon: UserIcon },+ { value: "identity" as const, label: "Machine Identities", icon: HardDriveIcon },+ { value: "group" as const, label: "Groups", icon: UsersIcon }+ ].map((opt) => {+ const Icon = opt.icon;+ return (+ <Button+ key={opt.value}+ variant={kind === opt.value ? "project" : "outline"}+ onClick={() => setKind(opt.value)}+ className="flex-1"+ >+ <Icon className="h-3.5 w-3.5" />+ <span>{opt.label}</span>+ </Button>+ );+ })}+ </ButtonGroup>++ <Field>+ <FieldLabel>+ {/* eslint-disable-next-line no-nested-ternary */}+ Select {kind === "user" ? "users" : kind === "identity" ? "identities" : "groups"}+ </FieldLabel>+ <FieldContent>+ <FilterableSelect+ isMulti+ options={optionsForKind}+ value={valueForKind}+ onChange={(selected) => setSelected((selected as Option[] | null) ?? [])}+ placeholder="Pick..."+ />+ </FieldContent>+ </Field>++ <Field>+ <FieldLabel>Role</FieldLabel>+ <FieldContent>+ <Select value={role} onValueChange={(v) => setRole(v as SignerMemberRole)}>+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper" align="start" sideOffset={4}>+ {Object.values(SignerMemberRole).map((r) => (+ <SelectItem key={r} value={r} description={signerMemberRoleDescriptions[r]}>+ {signerMemberRoleLabels[r]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FieldContent>+ </Field>+ </FieldGroup>++ <DialogFooter>+ <Button variant="outline" onClick={() => handleClose(false)}>+ Cancel+ </Button>+ <Button variant="project" onClick={onSubmit} isPending={submitting}>+ Add members+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal.tsxdeleted file mode 100644index a37c8f332b..0000000000--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal.tsx+++ /dev/null@@ -1,149 +0,0 @@-import { Controller, useForm } from "react-hook-form";-import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";-import { z } from "zod";--import {- Button,- FormControl,- Input,- Modal,- ModalContent,- Select,- SelectClear,- SelectItem,- TextArea-} from "@app/components/v2";-import {- approvalPolicyQuery,- ApprovalPolicyScope,- ApprovalPolicyType-} from "@app/hooks/api/approvalPolicies";-import { TSigner, useUpdateSigner } from "@app/hooks/api/signers";-import { slugSchema } from "@app/lib/schemas";--type Props = {- isOpen: boolean;- onOpenChange: (open: boolean) => void;- signer: TSigner;- projectId: string;-};--const formSchema = z.object({- name: slugSchema({ min: 1, max: 64, field: "Name" }),- description: z.string().trim().max(256).optional().or(z.literal("")),- approvalPolicyId: z.string().uuid().optional().or(z.literal(""))-});--type FormData = z.infer<typeof formSchema>;--export const EditSignerModal = ({ isOpen, onOpenChange, signer, projectId }: Props) => {- const updateSigner = useUpdateSigner();-- const { data: policies = [], isPending: isPoliciesLoading } = useQuery(- approvalPolicyQuery.list({- policyType: ApprovalPolicyType.CertCodeSigning,- scope: ApprovalPolicyScope.Project,- scopeId: projectId- })- );-- const {- control,- handleSubmit,- reset,- formState: { isSubmitting }- } = useForm<FormData>({- resolver: zodResolver(formSchema),- defaultValues: {- name: signer.name,- description: signer.description ?? "",- approvalPolicyId: signer.approvalPolicyId ?? ""- }- });-- const handleOpenChange = (open: boolean) => {- if (!open) {- reset({- name: signer.name,- description: signer.description ?? "",- approvalPolicyId: signer.approvalPolicyId ?? ""- });- }- onOpenChange(open);- };-- const onSubmit = async (data: FormData) => {- await updateSigner.mutateAsync({- signerId: signer.id,- name: data.name,- description: data.description || null,- approvalPolicyId: data.approvalPolicyId || null- });- handleOpenChange(false);- };-- return (- <Modal isOpen={isOpen} onOpenChange={handleOpenChange}>- <ModalContent title="Edit Signer">- <form onSubmit={handleSubmit(onSubmit)}>- <Controller- name="name"- control={control}- render={({ field, fieldState: { error } }) => (- <FormControl label="Name" isError={Boolean(error)} errorText={error?.message}>- <Input {...field} placeholder="my-code-signer" />- </FormControl>- )}- />- <Controller- name="description"- control={control}- render={({ field, fieldState: { error } }) => (- <FormControl label="Description" isError={Boolean(error)} errorText={error?.message}>- <TextArea {...field} placeholder="Optional description" rows={2} />- </FormControl>- )}- />- <Controller- name="approvalPolicyId"- control={control}- render={({ field, fieldState: { error } }) => (- <FormControl- label="Approval Policy"- isError={Boolean(error)}- errorText={error?.message}- helperText="Optional. Without a policy, signing is allowed without approval."- >- <Select- value={field.value}- onValueChange={field.onChange}- className="w-full"- isLoading={isPoliciesLoading}- placeholder="None (no approval required)"- >- <SelectClear selectValue={field.value ?? ""} onClear={() => field.onChange("")}>- None (no approval required)- </SelectClear>- {policies.map((policy) => (- <SelectItem key={policy.id} value={policy.id}>- {policy.name}- </SelectItem>- ))}- </Select>- </FormControl>- )}- />- <div className="mt-4 flex justify-end gap-2">- <Button variant="outline_bg" onClick={() => handleOpenChange(false)}>- Cancel- </Button>- <Button type="submit" isLoading={isSubmitting}>- Save- </Button>- </div>- </form>- </ModalContent>- </Modal>- );-};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/BasicsStep.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/BasicsStep.tsxnew file mode 100644index 0000000000..06ccd5c507--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/BasicsStep.tsx@@ -0,0 +1,54 @@+import { Controller, useForm } from "react-hook-form";++import {+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ Input,+ TextArea+} from "@app/components/v3";++import { BasicsForm } from "./schemas";++export const BasicsStep = ({ form }: { form: ReturnType<typeof useForm<BasicsForm>> }) => (+ <FieldGroup>+ <Controller+ name="name"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Signer name <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Input {...field} placeholder="e.g. mobile-app-prod" isError={Boolean(error)} />+ <FieldDescription>Lowercase, with dashes.</FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ name="description"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Description</FieldLabel>+ <FieldContent>+ <TextArea+ {...field}+ value={field.value ?? ""}+ placeholder="What this signer signs (e.g. iOS + Android production bundles)."+ rows={3}+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ </FieldGroup>+);diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsxnew file mode 100644index 0000000000..221fb0a669--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/CertificateStep.tsx@@ -0,0 +1,195 @@+import { Controller, useForm } from "react-hook-form";++import {+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ FilterableSelect,+ Input+} from "@app/components/v3";++import { CertificateForm } from "./schemas";+import { CaGroup, CaOption } from "./types";++type CertificateStepProps = {+ form: ReturnType<typeof useForm<CertificateForm>>;+ caOptions: CaOption[];+ isCasLoading: boolean;+ commonName: string;+ certificateTtlDays: number | null;+ keyAlgorithmLabel: string;+ caSwap: boolean;+ canEditSubject: boolean;+};++export const CertificateStep = ({+ form,+ caOptions,+ isCasLoading,+ commonName,+ certificateTtlDays,+ keyAlgorithmLabel,+ caSwap,+ canEditSubject+}: CertificateStepProps) => (+ <FieldGroup>+ <Controller+ name="caId"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Certificate Authority <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <FilterableSelect<CaOption>+ isLoading={isCasLoading}+ options={caOptions}+ value={caOptions.find((o) => o.id === field.value) ?? null}+ onChange={(selected) => {+ const opt = selected as CaOption | null;+ field.onChange(opt?.id ?? "");+ }}+ getOptionLabel={(opt) => opt.name}+ getOptionValue={(opt) => opt.id}+ groupBy={caOptions.length > 0 ? "groupType" : undefined}+ getGroupHeaderLabel={+ caOptions.length > 0+ ? (groupType: CaGroup) =>+ groupType === "internal" ? "Internal CAs" : "External CAs"+ : undefined+ }+ placeholder="Select a Certificate Authority..."+ noOptionsMessage={() => "No active CAs found in this project."}+ isError={Boolean(error)}+ />+ <FieldDescription>+ Changing the CA reissues the certificate immediately.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />++ {canEditSubject ? (+ <Controller+ name="commonName"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Common Name <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Input+ {...field}+ value={field.value ?? ""}+ placeholder="Acme Mobile, Inc."+ isError={Boolean(error)}+ />+ <FieldDescription>+ The legal name shown on the certificate. Editable while no certificate has been+ issued. Locked once the signer becomes Active.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ ) : (+ <Field>+ <FieldLabel>Common Name</FieldLabel>+ <FieldContent>+ <Input value={commonName} readOnly disabled />+ <FieldDescription>The legal name shown on the certificate.</FieldDescription>+ </FieldContent>+ </Field>+ )}++ {canEditSubject ? (+ <Controller+ name="certificateTtlDays"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ Validity (days) <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <Input+ type="number"+ min={1}+ max={3650}+ value={field.value ?? ""}+ onChange={(e) => field.onChange(Number(e.target.value))}+ placeholder="365"+ isError={Boolean(error)}+ />+ <FieldDescription>+ How long each issued certificate stays valid. Locked once the signer becomes Active.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ ) : (+ <Field>+ <FieldLabel>Validity (days)</FieldLabel>+ <FieldContent>+ <Input+ value={certificateTtlDays != null ? String(certificateTtlDays) : "—"}+ readOnly+ disabled+ />+ <FieldDescription>How long each issued certificate stays valid.</FieldDescription>+ </FieldContent>+ </Field>+ )}++ <Field>+ <FieldLabel>Key algorithm</FieldLabel>+ <FieldContent>+ <Input value={keyAlgorithmLabel} readOnly disabled />+ </FieldContent>+ </Field>++ <Controller+ name="renewBeforeDays"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Renew before (days)</FieldLabel>+ <FieldContent>+ <Input+ type="number"+ min={1}+ max={30}+ value={field.value ?? ""}+ onChange={(e) => {+ const raw = e.target.value;+ field.onChange(raw === "" ? null : Number(raw));+ }}+ placeholder="Leave empty to disable auto-renewal"+ isError={Boolean(error)}+ />+ <FieldDescription>+ Renew the certificate this many days before it expires.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />++ {caSwap && (+ <div className="rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning">+ Saving will issue a new certificate from the selected CA right away.+ </div>+ )}+ </FieldGroup>+);diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsxnew file mode 100644index 0000000000..f8d3046589--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/EditSignerModal.tsx@@ -0,0 +1,279 @@+import { useMemo, useState } from "react";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { ShieldIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ DocumentationLinkBadge,+ Sheet,+ SheetContent,+ SheetHeader,+ SheetTitle,+ Stepper,+ StepperList,+ StepperStep+} from "@app/components/v3";+import { useListCasByProjectId } from "@app/hooks/api/ca";+import { CaStatus } from "@app/hooks/api/ca/enums";+import {+ SignerKeyAlgorithm,+ signerKeyAlgorithmLabels,+ SignerStatus,+ TSigner,+ useReissueSignerCertificate,+ useUpdateSigner+} from "@app/hooks/api/signers";++import { PkiDocsUrls } from "../../../pki-docs-urls";+import { BasicsStep } from "./BasicsStep";+import { CertificateStep } from "./CertificateStep";+import { BasicsForm, basicsSchema, CertificateForm, certificateSchema } from "./schemas";+import { CaOption, STEPS } from "./types";++type Props = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ signer: TSigner;+};++export const EditSignerModal = ({ isOpen, onOpenChange, signer }: Props) => {+ const [step, setStep] = useState(0);+ const [submitting, setSubmitting] = useState(false);++ const cas = useListCasByProjectId();+ const updateSigner = useUpdateSigner();+ const reissueCertificate = useReissueSignerCertificate();++ const caOptions: CaOption[] = useMemo(() => {+ const list = cas.data ?? [];+ return list+ .filter((ca) => ca.status === CaStatus.ACTIVE)+ .map((ca) => ({+ id: ca.id,+ name: ca.name,+ groupType: ca.type === "internal" ? "internal" : "external"+ }));+ }, [cas.data]);++ const basicsForm = useForm<BasicsForm>({+ resolver: zodResolver(basicsSchema),+ values: { name: signer.name, description: signer.description ?? "" }+ });++ const canEditSubject =+ signer.status === SignerStatus.Pending || signer.status === SignerStatus.Failed;++ const certificateForm = useForm<CertificateForm>({+ resolver: zodResolver(certificateSchema),+ values: {+ caId: signer.caId ?? "",+ renewBeforeDays: signer.renewBeforeDays ?? null,+ commonName: signer.commonName ?? "",+ certificateTtlDays: signer.certificateTtlDays ?? 365+ }+ });++ const watchedCaId = certificateForm.watch("caId");+ const watchedCommonName = certificateForm.watch("commonName");+ const watchedTtl = certificateForm.watch("certificateTtlDays");++ const caSwap = Boolean(watchedCaId) && watchedCaId !== signer.caId;+ const subjectChanged =+ canEditSubject &&+ ((watchedCommonName ?? "") !== (signer.commonName ?? "") ||+ (watchedTtl ?? 0) !== (signer.certificateTtlDays ?? 0));+ const shouldReissue = caSwap || subjectChanged;++ const handleOpenChange = (open: boolean) => {+ if (!open) {+ setStep(0);+ basicsForm.reset({ name: signer.name, description: signer.description ?? "" });+ certificateForm.reset({+ caId: signer.caId ?? "",+ renewBeforeDays: signer.renewBeforeDays ?? null,+ commonName: signer.commonName ?? "",+ certificateTtlDays: signer.certificateTtlDays ?? 365+ });+ }+ onOpenChange(open);+ };++ const onSave = async () => {+ setSubmitting(true);+ try {+ const basics = basicsForm.getValues();+ const cert = certificateForm.getValues();++ const nameChanged = basics.name !== signer.name;+ const descChanged = (basics.description || "") !== (signer.description ?? "");+ const currentRenew = signer.renewBeforeDays ?? null;+ const nextRenew = cert.renewBeforeDays ?? null;+ const renewChanged = nextRenew !== currentRenew;++ if (shouldReissue) {+ await reissueCertificate.mutateAsync({+ signerId: signer.id,+ caId: cert.caId,+ commonName: canEditSubject && subjectChanged ? cert.commonName : undefined,+ certificateTtlDays: canEditSubject && subjectChanged ? cert.certificateTtlDays : undefined+ });+ }++ if (nameChanged || descChanged || renewChanged) {+ await updateSigner.mutateAsync({+ signerId: signer.id,+ name: nameChanged ? basics.name : undefined,+ description: descChanged ? basics.description || null : undefined,+ renewBeforeDays: renewChanged ? nextRenew : undefined+ });+ }++ handleOpenChange(false);+ } catch (err) {+ createNotification({+ type: "error",+ text: err instanceof Error ? err.message : "Failed to update signer"+ });+ } finally {+ setSubmitting(false);+ }+ };++ const goNext = async () => {+ if (step === 0) {+ const ok = await basicsForm.trigger();+ if (!ok) return;+ setStep(1);+ return;+ }+ if (step === 1) {+ const ok = await certificateForm.trigger();+ if (!ok) return;+ await onSave();+ }+ };++ const goBack = () => {+ if (step > 0) setStep((s) => s - 1);+ };++ const currentStep = STEPS[step];+ const isLast = step === STEPS.length - 1;+ // eslint-disable-next-line no-nested-ternary+ const ctaLabel = isLast ? (shouldReissue ? "Save and reissue" : "Save") : "Continue";++ return (+ <Sheet open={isOpen} onOpenChange={handleOpenChange}>+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0 sm:max-w-[1100px]">+ <SheetHeader className="border-b">+ <SheetTitle>+ <div className="flex w-full items-start gap-2">+ <div className="flex h-10 w-10 items-center justify-center rounded-md bg-warning/10 text-warning">+ <ShieldIcon className="h-5 w-5" />+ </div>+ <div>+ <div className="flex items-center gap-x-2 text-mineshaft-300">+ Edit Signer+ <DocumentationLinkBadge href={PkiDocsUrls.codeSigning.signers} />+ </div>+ <p className="text-sm leading-4 text-mineshaft-400">+ Update the signer's name, validity, and certificate authority.+ </p>+ </div>+ </div>+ </SheetTitle>+ </SheetHeader>++ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex min-h-0 flex-1 overflow-hidden">+ <aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">+ <p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">+ Edit steps+ </p>+ <Stepper+ activeStep={step}+ orientation="vertical"+ onStepChange={(i) => {+ if (i < step) setStep(i);+ }}+ >+ <StepperList>+ {STEPS.map((s, i) => (+ <StepperStep+ key={s.name}+ index={i}+ title={s.name}+ description={s.shortDescription}+ />+ ))}+ </StepperList>+ </Stepper>+ </aside>++ <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">+ <div className="mb-6">+ <h2 className="text-lg font-semibold text-foreground">{currentStep.title}</h2>+ <p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p>+ </div>++ {step === 0 && <BasicsStep form={basicsForm} />}+ {step === 1 && (+ <CertificateStep+ form={certificateForm}+ caOptions={caOptions}+ isCasLoading={cas.isPending}+ commonName={signer.commonName ?? signer.certificateCommonName ?? "—"}+ certificateTtlDays={signer.certificateTtlDays ?? null}+ keyAlgorithmLabel={+ signer.keyAlgorithm+ ? (signerKeyAlgorithmLabels[signer.keyAlgorithm as SignerKeyAlgorithm] ??+ String(signer.keyAlgorithm))+ : "RSA-2048"+ }+ caSwap={caSwap}+ canEditSubject={canEditSubject}+ />+ )}+ </div>++ <aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">+ <div className="mb-auto">+ <div className="flex items-center justify-between gap-2">+ <p className="text-[11px] font-medium tracking-wider text-muted uppercase">+ Step {step + 1} · {currentStep.rightLabel}+ </p>+ <DocumentationLinkBadge href={PkiDocsUrls.codeSigning.signers} />+ </div>+ <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>+ <p className="mt-2 text-sm leading-relaxed text-muted">+ {currentStep.rightDescription}+ </p>+ </div>+ </aside>+ </div>++ <div className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-6 py-4">+ <span className="text-xs text-muted">+ {shouldReissue ? "Saving will reissue the certificate immediately." : ""}+ </span>+ <div className="flex items-center gap-3">+ <span className="text-xs text-muted">+ Step {step + 1} of {STEPS.length}+ </span>+ {step > 0 && (+ <Button variant="outline" onClick={goBack}>+ Back+ </Button>+ )}+ <Button variant="project" onClick={goNext} isPending={submitting}>+ {ctaLabel}+ </Button>+ </div>+ </div>+ </div>+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/index.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/index.tsnew file mode 100644index 0000000000..6e457a9939--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/index.ts@@ -0,0 +1 @@+export { EditSignerModal } from "./EditSignerModal";diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.tsnew file mode 100644index 0000000000..17388ce079--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/schemas.ts@@ -0,0 +1,44 @@+import { z } from "zod";++import { slugSchema } from "@app/lib/schemas";++export const basicsSchema = z.object({+ name: slugSchema({ min: 1, max: 64, field: "Name" }),+ description: z.string().trim().max(256).optional().or(z.literal(""))+});+export type BasicsForm = z.infer<typeof basicsSchema>;++export const certificateSchema = z+ .object({+ caId: z.string().uuid("Certificate Authority is required"),+ renewBeforeDays: z+ .preprocess(+ (v) => {+ if (v === "" || v === null || v === undefined) return null;+ const n = typeof v === "number" ? v : Number(v);+ return Number.isNaN(n) ? v : n;+ },+ z.union([+ z+ .number()+ .int("Must be a whole number of days")+ .min(1, "Must be at least 1 day")+ .max(30, "Must be at most 30 days"),+ z.null()+ ])+ )+ .default(null),+ commonName: z.string().trim().min(1, "Common Name is required").max(256).optional(),+ certificateTtlDays: z.coerce.number().int().min(1).max(3650).optional()+ })+ .refine(+ (data) =>+ data.renewBeforeDays == null ||+ data.certificateTtlDays == null ||+ data.renewBeforeDays < data.certificateTtlDays,+ {+ message: "Renew before must be less than the certificate validity (days).",+ path: ["renewBeforeDays"]+ }+ );+export type CertificateForm = z.infer<typeof certificateSchema>;diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/types.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/types.tsnew file mode 100644index 0000000000..ef834ecaf0--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerModal/types.ts@@ -0,0 +1,32 @@+export type CaGroup = "internal" | "external";+export type CaOption = { id: string; name: string; groupType: CaGroup };++export type StepConfig = {+ name: string;+ shortDescription: string;+ title: string;+ subtitle: string;+ rightLabel: string;+ rightDescription: string;+};++export const STEPS: StepConfig[] = [+ {+ name: "Basics",+ shortDescription: "Name and description",+ title: "Basics",+ subtitle: "A short name and what this signer is for.",+ rightLabel: "BASICS",+ rightDescription:+ "Update the signer's name and description so your team can recognize it. Changing these does not affect the certificate."+ },+ {+ name: "Certificate",+ shortDescription: "Validity and CA",+ title: "Certificate",+ subtitle: "The certificate behind this signer.",+ rightLabel: "CERTIFICATE",+ rightDescription:+ "Adjust how early to auto-renew, and which CA issues the certificate. Swapping the CA reissues the certificate right away."+ }+];diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/ApproversStep.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/ApproversStep.tsxnew file mode 100644index 0000000000..f84600dd1a--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/ApproversStep.tsx@@ -0,0 +1,147 @@+import { ArrowDownIcon, InfoIcon, PlusIcon, ShieldIcon, XIcon } from "lucide-react";++import {+ Button,+ Field,+ FieldContent,+ FieldDescription,+ FieldGroup,+ FieldLabel,+ FilterableSelect,+ IconButton,+ Input+} from "@app/components/v3";++import { approverKey, ApproverOption, StepDraft } from "./types";++type Props = {+ steps: StepDraft[];+ approverOptions: ApproverOption[];+ onAddStep: () => void;+ onRemoveStep: (key: string) => void;+ onUpdateStep: (key: string, patch: Partial<StepDraft>) => void;+};++export const ApproversStep = ({+ steps,+ approverOptions,+ onAddStep,+ onRemoveStep,+ onUpdateStep+}: Props) => (+ <>+ <h2 className="text-xl font-semibold text-mineshaft-100">Approval policy</h2>+ <p className="mt-1 mb-4 text-sm text-mineshaft-300">+ Add approvers if signing should require approval. Otherwise members can sign directly.+ </p>++ <div className="mb-4 flex items-start justify-between gap-4">+ <div>+ <p className="text-sm font-semibold text-mineshaft-100">Approves</p>+ <p className="mt-0.5 text-xs text-mineshaft-300">+ Approvals run in order. Each step needs the listed number of approvers to approve.+ </p>+ </div>+ <Button variant="outline" size="sm" onClick={onAddStep}>+ <PlusIcon className="h-3.5 w-3.5" />+ <span>Add step</span>+ </Button>+ </div>++ {steps.length === 0 ? (+ <div className="flex flex-col items-center gap-2 rounded-md border border-dashed border-mineshaft-700 p-8 text-center">+ <ShieldIcon className="h-5 w-5 text-mineshaft-500" />+ <p className="text-sm text-mineshaft-300">No approval steps. Members can sign directly.</p>+ <Button variant="outline" size="sm" onClick={onAddStep}>+ <PlusIcon className="h-3.5 w-3.5" />+ <span>Add a step</span>+ </Button>+ </div>+ ) : (+ <div className="space-y-3">+ {steps.map((s, idx) => (+ <div key={s.key}>+ {idx > 0 && (+ <div className="flex justify-center py-1">+ <ArrowDownIcon className="h-4 w-4 text-mineshaft-500" />+ </div>+ )}+ <div className="rounded-md border border-mineshaft-700 bg-mineshaft-900/40 p-4">+ <div className="flex items-start gap-3">+ <div className="mt-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border bg-mineshaft-800 text-[11px] font-medium text-muted">+ {idx + 1}+ </div>+ <Input+ placeholder="Step name (e.g. Engineering lead)"+ value={s.name}+ onChange={(e) => onUpdateStep(s.key, { name: e.target.value })}+ className="flex-1"+ />+ <IconButton+ variant="ghost"+ size="sm"+ aria-label="Remove step"+ onClick={() => onRemoveStep(s.key)}+ >+ <XIcon className="h-4 w-4" />+ </IconButton>+ </div>+ <FieldGroup className="mt-3 grid grid-cols-1 gap-3 md:grid-cols-3">+ <div className="md:col-span-2">+ <Field>+ <FieldLabel>Approvers</FieldLabel>+ <FieldContent>+ <FilterableSelect+ isMulti+ options={approverOptions}+ groupBy="kind"+ getGroupHeaderLabel={(g) => (g === "group" ? "Groups" : "Users")}+ getOptionValue={(o) =>+ approverKey((o as ApproverOption).kind, (o as ApproverOption).value)+ }+ isOptionSelected={(o) => {+ const opt = o as ApproverOption;+ return s.approvers.some(+ (a) => a.kind === opt.kind && a.value === opt.value+ );+ }}+ value={s.approvers}+ onChange={(selected) => {+ const opts = (selected ?? []) as ApproverOption[];+ onUpdateStep(s.key, { approvers: opts });+ }}+ placeholder="Pick approvers from members..."+ noOptionsMessage={() => "No eligible members"}+ />+ <FieldDescription>Approvers must already be members.</FieldDescription>+ </FieldContent>+ </Field>+ </div>+ <Field>+ <FieldLabel>Required</FieldLabel>+ <FieldContent>+ <Input+ type="number"+ min={1}+ value={s.requiredApprovals}+ onChange={(e) => {+ const raw = e.target.value;+ const n = raw === "" ? 1 : Math.max(1, Number(raw));+ onUpdateStep(s.key, { requiredApprovals: n });+ }}+ />+ </FieldContent>+ </Field>+ </FieldGroup>+ </div>+ </div>+ ))}++ <p className="flex items-center gap-1.5 text-xs text-mineshaft-400">+ <InfoIcon className="h-3.5 w-3.5" />+ You can add or change approvers any time.+ </p>+ </div>+ )}+ </>+);diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/EditSignerPolicyModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/EditSignerPolicyModal.tsxnew file mode 100644index 0000000000..f9a0446b20--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/EditSignerPolicyModal.tsx@@ -0,0 +1,330 @@+import { useEffect, useMemo, useState } from "react";+import { ShieldIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ DocumentationLinkBadge,+ Sheet,+ SheetContent,+ SheetHeader,+ SheetTitle,+ Stepper,+ StepperList,+ StepperStep+} from "@app/components/v3";+import {+ SignerMemberRole,+ TSignerPolicy,+ useListSignerMembers,+ useUpdateSignerPolicy+} from "@app/hooks/api/signers";++import { PkiDocsUrls } from "../../../pki-docs-urls";+import { ApproversStep } from "./ApproversStep";+import { LimitsStep } from "./LimitsStep";+import {+ approverKey,+ ApproverKind,+ ApproverOption,+ APPROVERS_STEP,+ LIMITS_STEP,+ newStepDraft,+ StepDraft+} from "./types";++type Props = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ signerId: string;+ existingPolicy: TSignerPolicy | undefined;+};++export const EditSignerPolicyModal = ({+ isOpen,+ onOpenChange,+ signerId,+ existingPolicy+}: Props) => {+ const users = useListSignerMembers({ signerId, kind: "user" });+ const groups = useListSignerMembers({ signerId, kind: "group" });+ const updatePolicy = useUpdateSignerPolicy();++ const [step, setStep] = useState(0);+ const [steps, setSteps] = useState<StepDraft[]>([]);+ const [maxSignings, setMaxSignings] = useState<number | null>(null);+ const [maxWindow, setMaxWindow] = useState<string | null>("24h");+ const [submitting, setSubmitting] = useState(false);++ const approverOptions = useMemo<ApproverOption[]>(() => {+ const userOpts: ApproverOption[] = (users.data?.memberships ?? [])+ .filter((m) => m.actorUserId && (m.role as SignerMemberRole) !== SignerMemberRole.Auditor)+ .map((m) => ({+ value: m.actorUserId as string,+ label:+ m.details?.name || m.details?.username || m.details?.email || (m.actorUserId as string),+ kind: "user" as const+ }));+ const groupOpts: ApproverOption[] = (groups.data?.memberships ?? [])+ .filter((m) => m.actorGroupId && (m.role as SignerMemberRole) !== SignerMemberRole.Auditor)+ .map((m) => ({+ value: m.actorGroupId as string,+ label: m.details?.name || m.details?.slug || (m.actorGroupId as string),+ kind: "group" as const+ }));+ return [...userOpts, ...groupOpts];+ }, [users.data, groups.data]);++ useEffect(() => {+ if (!isOpen) return;+ setStep(0);+ if (existingPolicy && existingPolicy.steps.length > 0) {+ const labelLookup = new Map(+ approverOptions.map((o) => [approverKey(o.kind, o.value), o.label])+ );+ setSteps(+ existingPolicy.steps.map((s) => ({+ key: crypto.randomUUID(),+ name: s.name ?? "",+ approvers: s.approvers+ .filter((a) => a.type === "user" || a.type === "group")+ .map<ApproverOption>((a) => {+ const kind = a.type as ApproverKind;+ return {+ value: a.id,+ label: labelLookup.get(approverKey(kind, a.id)) ?? a.id,+ kind+ };+ }),+ requiredApprovals: s.requiredApprovals+ }))+ );+ setMaxSignings(existingPolicy.constraints.maxSignings ?? null);+ setMaxWindow(existingPolicy.constraints.maxWindowDuration ?? "24h");+ } else {+ setSteps([]);+ setMaxSignings(1);+ setMaxWindow(null);+ }+ }, [isOpen, existingPolicy]);++ useEffect(() => {+ if (!isOpen || approverOptions.length === 0) return;+ const lookup = new Map(approverOptions.map((o) => [approverKey(o.kind, o.value), o.label]));+ setSteps((prev) =>+ prev.map((stp) => {+ let changed = false;+ const patched = stp.approvers.map((a) => {+ if (a.label !== a.value) return a;+ const resolved = lookup.get(approverKey(a.kind, a.value));+ if (!resolved || resolved === a.label) return a;+ changed = true;+ return { ...a, label: resolved };+ });+ return changed ? { ...stp, approvers: patched } : stp;+ })+ );+ }, [isOpen, approverOptions]);++ const addStep = () => setSteps((prev) => [...prev, newStepDraft()]);+ const removeStep = (key: string) => setSteps((prev) => prev.filter((s) => s.key !== key));+ const updateStep = (key: string, patch: Partial<StepDraft>) =>+ setSteps((prev) => prev.map((s) => (s.key === key ? { ...s, ...patch } : s)));++ const handleClose = (open: boolean) => {+ if (!open) setStep(0);+ onOpenChange(open);+ };++ const totalApprovers = steps.reduce((sum, s) => sum + s.approvers.length, 0);+ const firstEmptyStepIndex = steps.findIndex((s) => s.approvers.length === 0);+ const hasEmptyStep = firstEmptyStepIndex >= 0;++ const WIZARD_STEPS = steps.length > 0 ? [APPROVERS_STEP, LIMITS_STEP] : [APPROVERS_STEP];+ const safeStep = Math.min(step, WIZARD_STEPS.length - 1);++ const onSave = async () => {+ const invalidStepIndex = steps.findIndex((s) => {+ if (s.approvers.length === 0) return true;+ if (s.requiredApprovals < 1) return true;+ const userCount = s.approvers.filter((a) => a.kind === "user").length;+ const groupCount = s.approvers.length - userCount;+ return groupCount === 0 && s.requiredApprovals > userCount;+ });+ if (invalidStepIndex !== -1) {+ const s = steps[invalidStepIndex];+ const userCount = s.approvers.filter((a) => a.kind === "user").length;+ if (s.approvers.length === 0) {+ createNotification({+ type: "error",+ text: `Step ${invalidStepIndex + 1}: pick at least one approver.`+ });+ } else if (s.requiredApprovals < 1) {+ createNotification({+ type: "error",+ text: `Step ${invalidStepIndex + 1}: required approvals must be at least 1.`+ });+ } else {+ createNotification({+ type: "error",+ text: `Step ${invalidStepIndex + 1}: required approvals (${s.requiredApprovals}) can't exceed ${userCount} approver${userCount === 1 ? "" : "s"}. Add a group to allow more.`+ });+ }+ return;+ }++ setSubmitting(true);+ try {+ await updatePolicy.mutateAsync({+ signerId,+ steps:+ steps.length === 0+ ? []+ : steps.map((s, i) => ({+ stepNumber: i + 1,+ name: s.name.trim() || null,+ requiredApprovals: s.requiredApprovals,+ approverUserIds: s.approvers.filter((a) => a.kind === "user").map((a) => a.value),+ approverGroupIds: s.approvers.filter((a) => a.kind === "group").map((a) => a.value)+ })),+ constraints: steps.length === 0 ? undefined : { maxSignings, maxWindowDuration: maxWindow }+ });+ handleClose(false);+ } catch (err) {+ createNotification({+ type: "error",+ text: err instanceof Error ? err.message : "Failed to save policy"+ });+ } finally {+ setSubmitting(false);+ }+ };++ const isLast = safeStep === WIZARD_STEPS.length - 1;+ const showLimitsTab = safeStep === 1;++ return (+ <Sheet open={isOpen} onOpenChange={handleClose}>+ <SheetContent className="flex h-full max-h-full flex-col gap-y-0 sm:max-w-[1500px]">+ <SheetHeader className="border-b">+ <SheetTitle>+ <div className="flex w-full items-start gap-2">+ <div className="flex h-10 w-10 items-center justify-center rounded-md bg-warning/10 text-warning">+ <ShieldIcon className="h-5 w-5" />+ </div>+ <div>+ <div className="flex items-center gap-x-2 text-mineshaft-300">+ Edit approval policy+ <DocumentationLinkBadge href={PkiDocsUrls.codeSigning.signers} />+ </div>+ <p className="text-sm leading-4 text-mineshaft-400">+ Choose who approves, and how much each approval gives.+ </p>+ </div>+ </div>+ </SheetTitle>+ </SheetHeader>++ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex min-h-0 flex-1 overflow-hidden">+ <aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">+ <p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">+ Setup steps+ </p>+ <Stepper+ activeStep={safeStep}+ orientation="vertical"+ onStepChange={(i) => {+ if (i < safeStep) setStep(i);+ }}+ >+ <StepperList>+ {WIZARD_STEPS.map((s, i) => (+ <StepperStep key={s.title} index={i} title={s.title} description={s.subtitle} />+ ))}+ </StepperList>+ </Stepper>+ </aside>++ <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">+ {!showLimitsTab ? (+ <ApproversStep+ steps={steps}+ approverOptions={approverOptions}+ onAddStep={addStep}+ onRemoveStep={removeStep}+ onUpdateStep={updateStep}+ />+ ) : (+ <LimitsStep+ maxSignings={maxSignings}+ setMaxSignings={setMaxSignings}+ maxWindow={maxWindow}+ setMaxWindow={setMaxWindow}+ />+ )}+ </div>++ <aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">+ <div className="mb-auto">+ <div className="flex items-center justify-between gap-2">+ <p className="text-[11px] font-medium tracking-wider text-muted uppercase">+ Step {safeStep + 1} · {WIZARD_STEPS[safeStep].title.toUpperCase()}+ </p>+ <DocumentationLinkBadge href={PkiDocsUrls.codeSigning.signers} />+ </div>+ <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>+ <p className="mt-2 text-sm leading-relaxed text-muted">+ {!showLimitsTab+ ? 'Approvals run in order. Each step has its own approvers and "required" count — the number of approvers that must approve before moving on.'+ : "Limits decide how many signatures one approval can make and how long it stays valid before expiring."}+ </p>+ </div>+ </aside>+ </div>++ <div className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-6 py-4">+ <span className="text-xs text-muted">+ {/* eslint-disable-next-line no-nested-ternary */}+ {hasEmptyStep+ ? `Step ${firstEmptyStepIndex + 1} needs at least one approver, or remove it.`+ : steps.length === 0+ ? "Approval is off"+ : `${steps.length} step${steps.length === 1 ? "" : "s"} · ${totalApprovers} approver${+ totalApprovers === 1 ? "" : "s"+ }`}+ </span>+ <div className="flex items-center gap-3">+ <span className="text-xs text-muted">+ Step {safeStep + 1} of {WIZARD_STEPS.length}+ </span>+ {safeStep > 0 && (+ <Button variant="outline" onClick={() => setStep((s) => s - 1)}>+ Back+ </Button>+ )}+ {!isLast ? (+ <Button+ variant="project"+ onClick={() => setStep((s) => s + 1)}+ isDisabled={hasEmptyStep}+ >+ Continue+ </Button>+ ) : (+ <Button+ variant="project"+ onClick={onSave}+ isPending={submitting}+ isDisabled={hasEmptyStep}+ >+ Save policy+ </Button>+ )}+ </div>+ </div>+ </div>+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/LimitsStep.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/LimitsStep.tsxnew file mode 100644index 0000000000..dd52689e50--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/LimitsStep.tsx@@ -0,0 +1,73 @@+import {+ Field,+ FieldContent,+ FieldDescription,+ FieldGroup,+ FieldLabel,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3";++import { NO_WINDOW_LIMIT, WINDOW_DURATION_OPTIONS } from "./types";++type Props = {+ maxSignings: number | null;+ setMaxSignings: (v: number | null) => void;+ maxWindow: string | null;+ setMaxWindow: (v: string | null) => void;+};++export const LimitsStep = ({ maxSignings, setMaxSignings, maxWindow, setMaxWindow }: Props) => (+ <>+ <h2 className="text-xl font-semibold text-mineshaft-100">What an approval allows</h2>+ <p className="mt-1 mb-4 text-sm text-mineshaft-300">+ Once approval is granted, define how it can be used. At least one limit is required.+ </p>++ <FieldGroup>+ <Field>+ <FieldLabel>Signatures per approval</FieldLabel>+ <FieldContent>+ <Input+ type="number"+ min={1}+ value={maxSignings ?? ""}+ onChange={(e) => setMaxSignings(e.target.value ? Number(e.target.value) : null)}+ placeholder="10"+ />+ <FieldDescription>+ How many times one approval can be used to sign. Leave empty for unlimited.+ </FieldDescription>+ </FieldContent>+ </Field>++ <Field>+ <FieldLabel>Signing window</FieldLabel>+ <FieldContent>+ <Select+ value={maxWindow ?? NO_WINDOW_LIMIT}+ onValueChange={(v) => setMaxWindow(v === NO_WINDOW_LIMIT ? null : v)}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {WINDOW_DURATION_OPTIONS.map((opt) => (+ <SelectItem key={opt.value} value={opt.value}>+ {opt.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldDescription>+ After approval is granted, how long signing is allowed before it expires.+ </FieldDescription>+ </FieldContent>+ </Field>+ </FieldGroup>+ </>+);diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/index.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/index.tsnew file mode 100644index 0000000000..950041cdcd--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/index.ts@@ -0,0 +1 @@+export { EditSignerPolicyModal } from "./EditSignerPolicyModal";diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/types.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/types.tsnew file mode 100644index 0000000000..a25caf86c6--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/types.ts@@ -0,0 +1,34 @@+export type ApproverKind = "user" | "group";+export type ApproverOption = { value: string; label: string; kind: ApproverKind };++export type StepDraft = {+ key: string;+ name: string;+ approvers: ApproverOption[];+ requiredApprovals: number;+};++export const approverKey = (kind: ApproverKind, id: string) => `${kind}:${id}`;++export const APPROVERS_STEP = { title: "Approvers", subtitle: "Who approves" } as const;+export const LIMITS_STEP = {+ title: "Approval limits",+ subtitle: "What each approval allows"+} as const;++export const NO_WINDOW_LIMIT = "__no_limit__";+export const WINDOW_DURATION_OPTIONS = [+ { label: "No limit", value: NO_WINDOW_LIMIT },+ { label: "1 hour", value: "1h" },+ { label: "8 hours", value: "8h" },+ { label: "24 hours", value: "24h" },+ { label: "7 days", value: "7d" },+ { label: "30 days", value: "30d" }+];++export const newStepDraft = (): StepDraft => ({+ key: crypto.randomUUID(),+ name: "",+ approvers: [],+ requiredApprovals: 1+});diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/ExportSignerCertModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/ExportSignerCertModal.tsxnew file mode 100644index 0000000000..3155cd9894--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/ExportSignerCertModal.tsx@@ -0,0 +1,148 @@+import FileSaver from "file-saver";+import { CheckIcon, CopyIcon, DownloadIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ PageLoader,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger+} from "@app/components/v3";+import { useTimedReset } from "@app/hooks";+import { useExportSignerCertificate } from "@app/hooks/api/signers";++type Props = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ signerId: string;+ signerName: string;+};++export const ExportSignerCertModal = ({ isOpen, onOpenChange, signerId, signerName }: Props) => {+ const { data, isLoading } = useExportSignerCertificate(signerId, isOpen);++ const [, didCopySerial, setCopySerialLabel] = useTimedReset<string>({+ initialState: "Copy"+ });+ const [, didCopyPem, setCopyPemLabel] = useTimedReset<string>({+ initialState: "Copy"+ });++ const onCopySerial = async () => {+ if (!data?.serialNumber) return;+ await navigator.clipboard.writeText(data.serialNumber);+ setCopySerialLabel("Copied");+ };++ const onCopyPem = async () => {+ if (!data?.certificatePem) return;+ await navigator.clipboard.writeText(data.certificatePem);+ setCopyPemLabel("Copied");+ };++ const onDownload = () => {+ if (!data?.certificatePem) return;+ try {+ const blob = new Blob([data.certificatePem], { type: "application/x-pem-file" });+ FileSaver.saveAs(blob, `${signerName || data.signerName || "signer"}.pem`);+ } catch (err) {+ createNotification({+ type: "error",+ text: err instanceof Error ? err.message : "Failed to download certificate"+ });+ }+ };++ return (+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-lg">+ <DialogHeader>+ <DialogTitle>Export certificate</DialogTitle>+ <DialogDescription>+ The signer's public certificate. The private key never leaves the server and is not+ included here.+ </DialogDescription>+ </DialogHeader>++ {isLoading || !data ? (+ <div className="py-8">+ <PageLoader />+ </div>+ ) : (+ <TooltipProvider>+ <div className="flex flex-col gap-5">+ <section>+ <div className="mb-2 flex items-center justify-between">+ <span className="text-sm font-medium text-foreground">Serial number</span>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="xs"+ onClick={onCopySerial}+ aria-label="Copy serial number"+ >+ {didCopySerial ? <CheckIcon /> : <CopyIcon />}+ {didCopySerial ? "Copied" : "Copy"}+ </Button>+ </TooltipTrigger>+ <TooltipContent>Copy serial number</TooltipContent>+ </Tooltip>+ </div>+ <div className="rounded-md border border-border bg-mineshaft-900 px-3 py-2 font-mono text-xs break-all text-foreground">+ {data.serialNumber || "—"}+ </div>+ </section>++ <section>+ <div className="mb-2 flex items-center justify-between">+ <span className="text-sm font-medium text-foreground">Certificate body</span>+ <div className="flex items-center gap-1">+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="xs"+ onClick={onCopyPem}+ aria-label="Copy certificate PEM"+ >+ {didCopyPem ? <CheckIcon /> : <CopyIcon />}+ {didCopyPem ? "Copied" : "Copy"}+ </Button>+ </TooltipTrigger>+ <TooltipContent>Copy PEM</TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="xs"+ onClick={onDownload}+ aria-label="Download certificate PEM"+ >+ <DownloadIcon />+ Download+ </Button>+ </TooltipTrigger>+ <TooltipContent>Download .pem</TooltipContent>+ </Tooltip>+ </div>+ </div>+ <pre className="max-h-72 thin-scrollbar overflow-y-auto rounded-md border border-border bg-mineshaft-900 px-3 py-2.5 font-mono text-[11px] leading-relaxed break-all whitespace-pre-wrap text-mineshaft-200">+ {data.certificatePem}+ </pre>+ </section>+ </div>+ </TooltipProvider>+ )}+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/PreApproveSigningModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/PreApproveSigningModal.tsxnew file mode 100644index 0000000000..495523737e--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/PreApproveSigningModal.tsx@@ -0,0 +1,272 @@+import { useMemo, useState } from "react";+import { Controller, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { z } from "zod";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ FilterableSelect,+ Input,+ TextArea+} from "@app/components/v3";+import {+ SignerMemberRole,+ TEffectiveSignerMember,+ useListEffectiveSignerMembers,+ usePreApproveSigning+} from "@app/hooks/api/signers";++type Props = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ signerId: string;+};++type MemberOption = { value: string; label: string; kind: "user" | "identity" };++const schema = z+ .object({+ granteeKey: z.string().min(1, "Pick a member"),+ requestedSignings: z.preprocess(+ (v) => {+ if (v === "" || v === null || v === undefined) return null;+ const n = typeof v === "number" ? v : Number(v);+ return Number.isNaN(n) ? v : n;+ },+ z+ .union([z.number().int("Must be a whole number").min(1, "Must be at least 1"), z.null()])+ .optional()+ ),+ requestedWindowStart: z.string().optional(),+ requestedWindowEnd: z.string().optional(),+ justification: z.string().trim().min(1, "Reason is required").max(2048)+ })+ .refine((d) => d.requestedSignings || d.requestedWindowEnd, {+ message: "Provide a signature count or a window end",+ path: ["requestedSignings"]+ });++type FormData = z.infer<typeof schema>;++const isoNow = () => new Date().toISOString().slice(0, 16);+const isoIn24h = () => new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().slice(0, 16);++export const PreApproveSigningModal = ({ isOpen, onOpenChange, signerId }: Props) => {+ const users = useListEffectiveSignerMembers({ signerId, kind: "user" });+ const identities = useListEffectiveSignerMembers({ signerId, kind: "identity" });+ const preApprove = usePreApproveSigning();+ const [submitting, setSubmitting] = useState(false);++ const memberOptions: MemberOption[] = useMemo(() => {+ const opts: MemberOption[] = [];+ (users.data?.members ?? []).forEach((m: TEffectiveSignerMember) => {+ if (!m.actorUserId) return;+ if (m.role === SignerMemberRole.Auditor) return;+ opts.push({+ value: `user:${m.actorUserId}`,+ label: m.details?.name || m.details?.username || m.details?.email || m.actorUserId,+ kind: "user"+ });+ });+ (identities.data?.members ?? []).forEach((m: TEffectiveSignerMember) => {+ if (!m.actorIdentityId) return;+ if (m.role === SignerMemberRole.Auditor) return;+ opts.push({+ value: `identity:${m.actorIdentityId}`,+ label: m.details?.name || m.actorIdentityId,+ kind: "identity"+ });+ });+ return opts;+ }, [users.data, identities.data]);++ const { control, handleSubmit, reset } = useForm<FormData>({+ resolver: zodResolver(schema),+ defaultValues: {+ granteeKey: "",+ requestedSignings: 3,+ requestedWindowStart: isoNow(),+ requestedWindowEnd: isoIn24h(),+ justification: ""+ }+ });++ const handleClose = (open: boolean) => {+ if (!open) reset();+ onOpenChange(open);+ };++ const onSubmit = async (data: FormData) => {+ setSubmitting(true);+ try {+ const [kind, id] = data.granteeKey.split(":");+ await preApprove.mutateAsync({+ signerId,+ granteeUserId: kind === "user" ? id : undefined,+ granteeIdentityId: kind === "identity" ? id : undefined,+ justification: data.justification,+ requestedSignings: data.requestedSignings ?? undefined,+ requestedWindowStart: data.requestedWindowStart+ ? new Date(data.requestedWindowStart).toISOString()+ : undefined,+ requestedWindowEnd: data.requestedWindowEnd+ ? new Date(data.requestedWindowEnd).toISOString()+ : undefined+ });+ handleClose(false);+ } catch (err) {+ createNotification({+ type: "error",+ text: err instanceof Error ? err.message : "Failed to pre-approve"+ });+ } finally {+ setSubmitting(false);+ }+ };++ return (+ <Dialog open={isOpen} onOpenChange={handleClose}>+ <DialogContent className="max-w-lg">+ <DialogHeader>+ <DialogTitle>Pre-approve signing</DialogTitle>+ <DialogDescription>+ Grant an Operator or machine identity a signed-off window without an approval flow.+ </DialogDescription>+ </DialogHeader>++ <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">+ <FieldGroup>+ <Controller+ name="granteeKey"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Member</FieldLabel>+ <FieldContent>+ <FilterableSelect+ options={memberOptions}+ value={memberOptions.find((o) => o.value === field.value) ?? null}+ onChange={(selected) =>+ field.onChange((selected as MemberOption | null)?.value ?? "")+ }+ placeholder="Pick a member..."+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />++ <Controller+ name="requestedSignings"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>How many signatures</FieldLabel>+ <FieldContent>+ <Input+ type="number"+ min={1}+ value={field.value ?? ""}+ onChange={(e) => {+ const raw = e.target.value;+ field.onChange(raw === "" ? null : Number(raw));+ }}+ placeholder="Leave empty to rely on the time window"+ isError={Boolean(error)}+ />+ <FieldDescription>Leave empty to rely on the time window.</FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />++ <div className="grid grid-cols-2 gap-3">+ <Controller+ name="requestedWindowStart"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Starts</FieldLabel>+ <FieldContent>+ <Input+ type="datetime-local"+ value={field.value ?? ""}+ onChange={(e) => field.onChange(e.target.value || undefined)}+ isError={Boolean(error)}+ />+ <FieldDescription>When access begins.</FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ name="requestedWindowEnd"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Ends</FieldLabel>+ <FieldContent>+ <Input+ type="datetime-local"+ value={field.value ?? ""}+ onChange={(e) => field.onChange(e.target.value || undefined)}+ isError={Boolean(error)}+ />+ <FieldDescription>When access expires.</FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ </div>++ <Controller+ name="justification"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Reason</FieldLabel>+ <FieldContent>+ <TextArea+ {...field}+ placeholder="Why is this being pre-approved?"+ rows={3}+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ </FieldGroup>++ <DialogFooter>+ <Button variant="outline" onClick={() => handleClose(false)}>+ Cancel+ </Button>+ <Button type="submit" variant="project" isPending={submitting}>+ Pre-approve+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/RequestToSignModal.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/RequestToSignModal.tsxnew file mode 100644index 0000000000..5ea5454d89--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/RequestToSignModal.tsx@@ -0,0 +1,214 @@+import { useState } from "react";+import { Controller, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { z } from "zod";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ Input,+ TextArea+} from "@app/components/v3";+import { useRequestToSign } from "@app/hooks/api/signers";++type Props = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ signerId: string;+};++const schema = z+ .object({+ requestedSignings: z.preprocess(+ (v) => {+ if (v === "" || v === null || v === undefined) return null;+ const n = typeof v === "number" ? v : Number(v);+ return Number.isNaN(n) ? v : n;+ },+ z+ .union([z.number().int("Must be a whole number").min(1, "Must be at least 1"), z.null()])+ .optional()+ ),+ requestedWindowStart: z.string().optional(),+ requestedWindowEnd: z.string().optional(),+ justification: z.string().trim().min(1, "Reason is required").max(2048)+ })+ .refine((d) => d.requestedSignings || d.requestedWindowEnd, {+ message: "Provide a signature count or a window end",+ path: ["requestedSignings"]+ });++type FormData = z.infer<typeof schema>;++const isoNow = () => new Date().toISOString().slice(0, 16);+const isoIn24h = () => new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().slice(0, 16);++export const RequestToSignModal = ({ isOpen, onOpenChange, signerId }: Props) => {+ const requestToSign = useRequestToSign();+ const [submitting, setSubmitting] = useState(false);++ const { control, handleSubmit, reset } = useForm<FormData>({+ resolver: zodResolver(schema),+ defaultValues: {+ requestedSignings: 3,+ requestedWindowStart: isoNow(),+ requestedWindowEnd: isoIn24h(),+ justification: ""+ }+ });++ const handleClose = (open: boolean) => {+ if (!open) reset();+ onOpenChange(open);+ };++ const onSubmit = async (data: FormData) => {+ setSubmitting(true);+ try {+ await requestToSign.mutateAsync({+ signerId,+ justification: data.justification,+ requestedSignings: data.requestedSignings ?? undefined,+ requestedWindowStart: data.requestedWindowStart+ ? new Date(data.requestedWindowStart).toISOString()+ : undefined,+ requestedWindowEnd: data.requestedWindowEnd+ ? new Date(data.requestedWindowEnd).toISOString()+ : undefined+ });+ handleClose(false);+ } catch (err) {+ createNotification({+ type: "error",+ text: err instanceof Error ? err.message : "Failed to open request"+ });+ } finally {+ setSubmitting(false);+ }+ };++ return (+ <Dialog open={isOpen} onOpenChange={handleClose}>+ <DialogContent className="max-w-lg">+ <DialogHeader>+ <DialogTitle>Request to sign</DialogTitle>+ <DialogDescription>+ Ask the approvers to let you sign. Pick how many signatures you need and when.+ </DialogDescription>+ </DialogHeader>++ <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">+ <FieldGroup>+ <Controller+ name="requestedSignings"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>How many signatures</FieldLabel>+ <FieldContent>+ <Input+ type="number"+ min={1}+ value={field.value ?? ""}+ onChange={(e) => {+ const raw = e.target.value;+ field.onChange(raw === "" ? null : Number(raw));+ }}+ placeholder="Leave empty to rely on the time window"+ isError={Boolean(error)}+ />+ <FieldDescription>+ Leave empty to rely on the time window instead.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />++ <div className="grid grid-cols-2 gap-3">+ <Controller+ name="requestedWindowStart"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Starts</FieldLabel>+ <FieldContent>+ <Input+ type="datetime-local"+ value={field.value ?? ""}+ onChange={(e) => field.onChange(e.target.value || undefined)}+ isError={Boolean(error)}+ />+ <FieldDescription>When access starts.</FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ name="requestedWindowEnd"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Ends</FieldLabel>+ <FieldContent>+ <Input+ type="datetime-local"+ value={field.value ?? ""}+ onChange={(e) => field.onChange(e.target.value || undefined)}+ isError={Boolean(error)}+ />+ <FieldDescription>When access ends.</FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ </div>++ <Controller+ name="justification"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>Reason</FieldLabel>+ <FieldContent>+ <TextArea+ {...field}+ placeholder="What are you signing?"+ rows={3}+ isError={Boolean(error)}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ </FieldGroup>++ <DialogFooter>+ <Button variant="outline" onClick={() => handleClose(false)}>+ Cancel+ </Button>+ <Button type="submit" variant="project" isPending={submitting}>+ Send request+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerApprovalPolicyTab.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerApprovalPolicyTab.tsxnew file mode 100644index 0000000000..327cbc9d7d--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerApprovalPolicyTab.tsx@@ -0,0 +1,275 @@+import { useLayoutEffect, useMemo, useRef, useState } from "react";+import { PencilIcon, UsersIcon } from "lucide-react";++import {+ Card,+ CardContent,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ IconButton,+ PageLoader,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import {+ TSignerMember,+ useGetSignerMyPermissions,+ useGetSignerPolicy,+ useListSignerMembers+} from "@app/hooks/api/signers";++import { EditSignerPolicyModal } from "./EditSignerPolicyModal";++type Props = {+ signerId: string;+};++type ApproverDisplay = {+ id: string;+ label: string;+ kind: "user" | "group";+};++const labelForMember = (m: TSignerMember): string => {+ if (m.actorUserId) {+ return m.details?.name || m.details?.username || m.details?.email || m.actorUserId;+ }+ if (m.actorGroupId) {+ return m.details?.name || m.details?.slug || m.actorGroupId;+ }+ return m.actorIdentityId ?? "Unknown";+};++const initialsOf = (label: string): string => {+ const trimmed = label.trim();+ if (!trimmed) return "??";+ const parts = trimmed.split(/\s+/).filter(Boolean);+ if (parts.length >= 2) {+ return (parts[0][0] + parts[1][0]).toUpperCase();+ }+ return trimmed.slice(0, 2).toUpperCase();+};++const ApproverAvatar = ({ approver }: { approver: ApproverDisplay }) => (+ <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-mineshaft-700 bg-mineshaft-800 text-[10px] font-medium text-muted ring-1 ring-mineshaft-900">+ {approver.kind === "group" ? <UsersIcon className="h-3 w-3" /> : initialsOf(approver.label)}+ </span>+);++const StepName = ({ name }: { name: string }) => {+ const ref = useRef<HTMLSpanElement | null>(null);+ const [isTruncated, setIsTruncated] = useState(false);++ useLayoutEffect(() => {+ const el = ref.current;+ if (!el) return undefined;+ const check = () => setIsTruncated(el.scrollWidth > el.clientWidth);+ check();+ const observer = new ResizeObserver(check);+ observer.observe(el);+ return () => observer.disconnect();+ }, [name]);++ const label = (+ <span ref={ref} className="min-w-0 flex-1 truncate text-xs font-semibold text-foreground">+ {name}+ </span>+ );++ if (!isTruncated) return label;++ return (+ <Tooltip>+ <TooltipTrigger asChild>{label}</TooltipTrigger>+ <TooltipContent className="max-w-xs break-words">{name}</TooltipContent>+ </Tooltip>+ );+};++const ApproverStack = ({ approvers }: { approvers: ApproverDisplay[] }) => {+ if (!approvers.length) return null;+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="flex -space-x-2">+ {approvers.map((a) => (+ <ApproverAvatar key={`${a.kind}:${a.id}`} approver={a} />+ ))}+ </div>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ <ul className="space-y-0.5">+ {approvers.map((a) => (+ <li key={`${a.kind}:${a.id}`} className="text-xs">+ {a.label}+ </li>+ ))}+ </ul>+ </TooltipContent>+ </Tooltip>+ );+};++export const SignerApprovalPolicyTab = ({ signerId }: Props) => {+ const { data: policy, isLoading } = useGetSignerPolicy(signerId);+ const { data: myPerms } = useGetSignerMyPermissions(signerId);+ const users = useListSignerMembers({ signerId, kind: "user" });+ const groups = useListSignerMembers({ signerId, kind: "group" });+ const [isEditOpen, setIsEditOpen] = useState(false);++ const userLabels = useMemo(() => {+ const map = new Map<string, string>();+ (users.data?.memberships ?? []).forEach((m) => {+ if (m.actorUserId) map.set(m.actorUserId, labelForMember(m));+ });+ return map;+ }, [users.data]);++ const groupLabels = useMemo(() => {+ const map = new Map<string, string>();+ (groups.data?.memberships ?? []).forEach((m) => {+ if (m.actorGroupId) map.set(m.actorGroupId, labelForMember(m));+ });+ return map;+ }, [groups.data]);++ if (isLoading) return <PageLoader />;++ const constraints = policy?.constraints;+ const hasSteps = policy?.hasSteps ?? false;++ const resolveApprover = (a: { id: string; type: "user" | "group" }): ApproverDisplay => {+ if (a.type === "user") {+ return {+ id: a.id,+ label: userLabels.get(a.id) ?? `${a.id.slice(0, 8)}…`,+ kind: "user"+ };+ }+ return {+ id: a.id,+ label: groupLabels.get(a.id) ?? `${a.id.slice(0, 8)}…`,+ kind: "group"+ };+ };++ const stepsCount = policy?.steps.length ?? 0;++ return (+ <>+ <Card>+ <div className="flex items-start justify-between gap-2">+ <div className="min-w-0">+ <div className="text-lg leading-none font-semibold text-foreground">+ Approval Policy+ </div>+ <p className="mt-1 text-sm text-accent">+ {hasSteps+ ? "Control when approval is required before signing."+ : "Approval is off. Members can sign directly."}+ </p>+ </div>+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ aria-label="Edit policy"+ variant="ghost"+ onClick={() => setIsEditOpen(true)}+ isDisabled={myPerms?.canManagePolicy === false}+ >+ <PencilIcon />+ </IconButton>+ </TooltipTrigger>+ <TooltipContent>Edit policy</TooltipContent>+ </Tooltip>+ </div>+ <CardContent>+ {hasSteps ? (+ <>+ <div className="mb-3 grid grid-cols-2 gap-3">+ <div>+ <Tooltip>+ <TooltipTrigger asChild>+ <p className="w-fit cursor-help text-[11px] text-muted">Max signings</p>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ How many times one approval can be used to sign. Leave empty for unlimited.+ </TooltipContent>+ </Tooltip>+ <p className="mt-0.5 text-xs text-foreground">+ {constraints?.maxSignings ?? <span className="text-muted">Unlimited</span>}+ </p>+ </div>+ <div>+ <Tooltip>+ <TooltipTrigger asChild>+ <p className="w-fit cursor-help text-[11px] text-muted">Max window</p>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ After approval is granted, how long signing is allowed before it expires.+ </TooltipContent>+ </Tooltip>+ <p className="mt-0.5 text-xs text-foreground">+ {constraints?.maxWindowDuration ?? <span className="text-muted">No limit</span>}+ </p>+ </div>+ </div>++ <div className="mb-1.5 text-[10px] font-semibold tracking-wider text-muted uppercase">+ Approval steps+ </div>+ <div>+ {policy?.steps.map((step, idx) => {+ const approvers = step.approvers.map(resolveApprover);+ const stepNumber = step.stepNumber ?? idx + 1;+ const isLast = idx === stepsCount - 1;+ return (+ <div key={stepNumber} className="flex gap-2">+ <div className="flex flex-col items-center">+ <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full border border-border bg-mineshaft-800 text-[10px] font-medium text-muted">+ {stepNumber}+ </span>+ {!isLast && <span aria-hidden="true" className="w-px flex-1 bg-border" />}+ </div>+ <div+ className={`flex min-w-0 flex-1 items-center gap-2 ${isLast ? "" : "pb-3"}`}+ >+ <StepName name={step.name ?? `Step ${stepNumber}`} />+ <ApproverStack approvers={approvers} />+ <span className="shrink-0 text-[11px] text-muted">+ <span className="font-semibold text-foreground">+ {step.requiredApprovals}+ </span>{" "}+ required+ </span>+ </div>+ </div>+ );+ })}+ </div>+ </>+ ) : (+ <Empty className="border border-solid">+ <EmptyHeader>+ <EmptyTitle>No approval steps</EmptyTitle>+ <EmptyDescription>+ Add approvers in the editor to require approval before signing.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ )}+ </CardContent>+ </Card>++ <EditSignerPolicyModal+ isOpen={isEditOpen}+ onOpenChange={setIsEditOpen}+ signerId={signerId}+ existingPolicy={policy}+ />+ </>+ );+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerMembersTab.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerMembersTab.tsxnew file mode 100644index 0000000000..7625036c32--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerMembersTab.tsx@@ -0,0 +1,241 @@+import { useMemo, useState } from "react";+import { MoreHorizontalIcon, Trash2Icon, UserPlusIcon } from "lucide-react";++import {+ Badge,+ Button,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ IconButton,+ PageLoader,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import {+ SignerMemberRole,+ signerMemberRoleDescriptions,+ signerMemberRoleLabels,+ TSignerMember,+ useGetSignerMyPermissions,+ useListSignerMembers,+ useRemoveSignerGroupMember,+ useRemoveSignerIdentityMember,+ useRemoveSignerUserMember,+ useUpdateSignerGroupRole,+ useUpdateSignerIdentityRole,+ useUpdateSignerUserRole+} from "@app/hooks/api/signers";++import { AddSignerMemberModal } from "./AddSignerMemberModal";++type Props = {+ signerId: string;+};++type MemberKind = "user" | "identity" | "group";++const kindOf = (m: TSignerMember): MemberKind => {+ if (m.actorUserId) return "user";+ if (m.actorIdentityId) return "identity";+ return "group";+};++const KIND_LABEL: Record<MemberKind, string> = {+ user: "User",+ identity: "Machine",+ group: "Group"+};++const labelOf = (m: TSignerMember): string => {+ if (m.actorUserId) {+ return m.details?.name || m.details?.username || m.details?.email || m.actorUserId;+ }+ if (m.actorIdentityId) return m.details?.name || m.actorIdentityId;+ return m.details?.name || m.details?.slug || (m.actorGroupId as string);+};++export const SignerMembersTab = ({ signerId }: Props) => {+ const { data: myPerms } = useGetSignerMyPermissions(signerId);+ const canManageMembers = myPerms?.canManageMembers !== false;+ const users = useListSignerMembers({ signerId, kind: "user" });+ const identities = useListSignerMembers({ signerId, kind: "identity" });+ const groups = useListSignerMembers({ signerId, kind: "group" });+ const updateUserRole = useUpdateSignerUserRole();+ const removeUserMember = useRemoveSignerUserMember();+ const updateIdentityRole = useUpdateSignerIdentityRole();+ const removeIdentityMember = useRemoveSignerIdentityMember();+ const updateGroupRole = useUpdateSignerGroupRole();+ const removeGroupMember = useRemoveSignerGroupMember();+ const [isAddOpen, setIsAddOpen] = useState(false);++ const all: TSignerMember[] = useMemo(+ () => [+ ...(users.data?.memberships ?? []),+ ...(identities.data?.memberships ?? []),+ ...(groups.data?.memberships ?? [])+ ],+ [users.data, identities.data, groups.data]+ );++ const isLoading = users.isPending || identities.isPending || groups.isPending;++ if (isLoading) return <PageLoader />;++ const handleRoleChange = (m: TSignerMember, role: SignerMemberRole) => {+ const kind = kindOf(m);+ if (kind === "user" && m.actorUserId) {+ updateUserRole.mutate({ signerId, userId: m.actorUserId, role });+ } else if (kind === "identity" && m.actorIdentityId) {+ updateIdentityRole.mutate({ signerId, identityId: m.actorIdentityId, role });+ } else if (kind === "group" && m.actorGroupId) {+ updateGroupRole.mutate({ signerId, groupId: m.actorGroupId, role });+ }+ };++ const handleRemove = (m: TSignerMember) => {+ const kind = kindOf(m);+ if (kind === "user" && m.actorUserId) {+ removeUserMember.mutate({ signerId, userId: m.actorUserId });+ } else if (kind === "identity" && m.actorIdentityId) {+ removeIdentityMember.mutate({ signerId, identityId: m.actorIdentityId });+ } else if (kind === "group" && m.actorGroupId) {+ removeGroupMember.mutate({ signerId, groupId: m.actorGroupId });+ }+ };++ return (+ <>+ <Card>+ <CardHeader>+ <CardTitle>Members</CardTitle>+ <CardDescription>+ Users, machine identities, and groups granted access to this signer.+ </CardDescription>+ <CardAction>+ <Button+ variant="outline"+ onClick={() => setIsAddOpen(true)}+ isDisabled={!canManageMembers}+ >+ <UserPlusIcon />+ Add Member+ </Button>+ </CardAction>+ </CardHeader>+ <CardContent>+ {all.length === 0 ? (+ <Empty className="border border-solid">+ <EmptyHeader>+ <EmptyTitle>No members yet</EmptyTitle>+ <EmptyDescription>+ Add a user, identity, or group to grant access to this signer.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Member</TableHead>+ <TableHead>Type</TableHead>+ <TableHead>Role</TableHead>+ <TableHead>Added</TableHead>+ <TableHead className="w-5" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {all.map((m) => {+ const kind = kindOf(m);+ const label = labelOf(m);++ return (+ <TableRow key={m.membershipId} className="[&>td]:py-3">+ <TableCell isTruncatable>+ <div className="text-foreground">{label}</div>+ </TableCell>+ <TableCell>+ <Badge variant="neutral">{KIND_LABEL[kind]}</Badge>+ </TableCell>+ <TableCell>+ <Select+ value={m.role}+ disabled={!canManageMembers}+ onValueChange={(role) => handleRoleChange(m, role as SignerMemberRole)}+ >+ <SelectTrigger size="sm" className="w-40">+ <SelectValue />+ </SelectTrigger>+ <SelectContent position="popper" align="start" sideOffset={4}>+ {Object.values(SignerMemberRole).map((role) => (+ <SelectItem+ key={role}+ value={role}+ description={signerMemberRoleDescriptions[role]}+ >+ {signerMemberRoleLabels[role]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </TableCell>+ <TableCell className="text-accent">+ {new Date(m.createdAt).toLocaleDateString()}+ </TableCell>+ <TableCell>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton variant="ghost" size="xs">+ <MoreHorizontalIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="min-w-40" align="end" sideOffset={2}>+ <DropdownMenuItem+ variant="danger"+ isDisabled={!canManageMembers}+ onClick={() => handleRemove(m)}+ >+ <Trash2Icon />+ Remove Member+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ )}+ </CardContent>+ </Card>++ <AddSignerMemberModal+ isOpen={isAddOpen}+ onOpenChange={setIsAddOpen}+ signerId={signerId}+ existingMembers={all}+ />+ </>+ );+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerOverviewSection.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerOverviewSection.tsxdeleted file mode 100644index cf35152ba7..0000000000--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerOverviewSection.tsx+++ /dev/null@@ -1,209 +0,0 @@-import { Link } from "@tanstack/react-router";-import { format } from "date-fns";-import { CheckIcon, ClipboardListIcon, ExternalLinkIcon, PencilIcon } from "lucide-react";--import { ProjectPermissionCan } from "@app/components/permissions";-import { Tooltip } from "@app/components/v2";-import {- Badge,- Button,- Card,- CardAction,- CardContent,- CardDescription,- CardHeader,- CardTitle,- Detail,- DetailGroup,- DetailLabel,- DetailValue,- IconButton-} from "@app/components/v3";-import {- ProjectPermissionCodeSigningActions,- ProjectPermissionSub,- useOrganization-} from "@app/context";-import { useTimedReset } from "@app/hooks";-import {- getSignerStatusBadgeVariant,- signerStatusLabels,- TSigner,- useGetSignerPublicKey-} from "@app/hooks/api/signers";--type Props = {- signer: TSigner;- projectId: string;- onEdit?: () => void;-};--const ALGORITHM_LABELS: Record<string, string> = {- rsa: "RSA",- "rsa-pss": "RSA-PSS",- ec: "ECDSA",- ed25519: "Ed25519",- ed448: "Ed448"-};--export const SignerOverviewSection = ({ signer, projectId, onEdit }: Props) => {- const { currentOrg } = useOrganization();- const { data: publicKeyData } = useGetSignerPublicKey(signer.id);- // eslint-disable-next-line @typescript-eslint/naming-convention,@typescript-eslint/no-unused-vars- const [_, isCopyingId, setCopyTextId] = useTimedReset<string>({- initialState: "Copy ID to clipboard"- });-- const algorithmLabel = publicKeyData?.algorithm- ? (ALGORITHM_LABELS[publicKeyData.algorithm] ?? publicKeyData.algorithm)- : "—";-- return (- <div className="flex flex-col gap-5">- <Card>- <CardHeader className="border-b">- <CardTitle>Signer Details</CardTitle>- <CardDescription>Signer configuration and key details</CardDescription>- {onEdit && (- <CardAction>- <ProjectPermissionCan- I={ProjectPermissionCodeSigningActions.Edit}- a={ProjectPermissionSub.CodeSigners}- >- {(isAllowed) => (- <IconButton isDisabled={!isAllowed} onClick={onEdit} size="xs" variant="outline">- <PencilIcon />- </IconButton>- )}- </ProjectPermissionCan>- </CardAction>- )}- </CardHeader>- <CardContent>- <DetailGroup>- <Detail>- <DetailLabel>Name</DetailLabel>- <DetailValue>{signer.name}</DetailValue>- </Detail>- <Detail>- <DetailLabel>ID</DetailLabel>- <DetailValue className="flex items-center gap-x-1">- {signer.id}- <Tooltip content="Copy signer ID to clipboard">- <IconButton- onClick={() => {- navigator.clipboard.writeText(signer.id);- setCopyTextId("Copied");- }}- variant="ghost"- size="xs"- >- {isCopyingId ? <CheckIcon /> : <ClipboardListIcon className="text-label" />}- </IconButton>- </Tooltip>- </DetailValue>- </Detail>- <Detail>- <DetailLabel>Status</DetailLabel>- <DetailValue>- <Badge variant={getSignerStatusBadgeVariant(signer.status)}>- {signerStatusLabels[signer.status] ?? signer.status}- </Badge>- </DetailValue>- </Detail>- <Detail>- <DetailLabel>Key Algorithm</DetailLabel>- <DetailValue className="font-mono">{algorithmLabel}</DetailValue>- </Detail>- <Detail>- <DetailLabel>Approval Policy</DetailLabel>- <DetailValue>- {signer.approvalPolicyId && signer.approvalPolicyName ? (- <Link- to="/organizations/$orgId/projects/cert-manager/$projectId/code-signing"- params={{- orgId: currentOrg.id,- projectId- }}- search={{ selectedTab: "signing-policies" }}- className="flex items-center gap-1 text-primary hover:underline"- >- {signer.approvalPolicyName}- <ExternalLinkIcon className="h-3 w-3" />- </Link>- ) : (- <span className="text-muted">None</span>- )}- </DetailValue>- </Detail>- <Detail>- <DetailLabel>Created</DetailLabel>- <DetailValue>{format(new Date(signer.createdAt), "MMM d, yyyy HH:mm")}</DetailValue>- </Detail>- <Detail>- <DetailLabel>Last Signed</DetailLabel>- <DetailValue>- {signer.lastSignedAt ? (- format(new Date(signer.lastSignedAt), "MMM d, yyyy HH:mm")- ) : (- <span className="text-muted">—</span>- )}- </DetailValue>- </Detail>- </DetailGroup>- </CardContent>- </Card>- <Card>- <CardHeader className="border-b">- <CardTitle>Certificate</CardTitle>- <CardDescription>- <div className="flex items-center gap-2">- <div>Linked signing certificate</div>- <Button variant="ghost" size="xs" asChild>- <Link- to="/organizations/$orgId/projects/cert-manager/$projectId/certificates/$certificateId"- params={{- orgId: currentOrg.id,- projectId,- certificateId: signer.certificateId- }}- >- View- <ExternalLinkIcon className="ml-1 h-3 w-3" />- </Link>- </Button>- </div>- </CardDescription>- </CardHeader>- <CardContent>- <DetailGroup>- <Detail>- <DetailLabel>Common Name</DetailLabel>- <DetailValue>- {signer.certificateCommonName || <span className="text-muted">—</span>}- </DetailValue>- </Detail>- <Detail>- <DetailLabel>Serial Number</DetailLabel>- <DetailValue className="font-mono text-xs">- {signer.certificateSerialNumber?.toUpperCase() || (- <span className="text-muted">—</span>- )}- </DetailValue>- </Detail>- <Detail>- <DetailLabel>Expires</DetailLabel>- <DetailValue>- {signer.certificateNotAfter ? (- format(new Date(signer.certificateNotAfter), "MMM d, yyyy")- ) : (- <span className="text-muted">—</span>- )}- </DetailValue>- </Detail>- </DetailGroup>- </CardContent>- </Card>- </div>- );-};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/ExpiresCell.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/ExpiresCell.tsxnew file mode 100644index 0000000000..f2a9a62e19--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/ExpiresCell.tsx@@ -0,0 +1,57 @@+import { format } from "date-fns";+import { ClockIcon } from "lucide-react";++import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";+import { SignerRequestStatus, TSignerRequest } from "@app/hooks/api/signers";++import { compactDuration } from "./types";++export const ExpiresCell = ({ req }: { req: TSignerRequest }) => {+ if (req.status === SignerRequestStatus.Pending) {+ return <span>Awaiting approval</span>;+ }+ if (req.status !== SignerRequestStatus.Approved) return null;++ const max = req.maxSignings ?? null;+ const used = req.usedSignings ?? 0;+ const left = max != null ? Math.max(0, max - used) : null;+ const grantInactive = req.grantStatus != null && req.grantStatus !== "active";++ let expiryLabel: string;+ let expiryTooltip: string;+ if (grantInactive) {+ expiryLabel = `Grant ${req.grantStatus}`;+ expiryTooltip = req.expiresAt+ ? format(new Date(req.expiresAt), "MMM d, yyyy 'at' h:mm a")+ : "Grant no longer active";+ } else if (!req.expiresAt) {+ expiryLabel = "No expiry";+ expiryTooltip = "No time limit";+ } else {+ const expires = new Date(req.expiresAt);+ const diff = expires.getTime() - Date.now();+ expiryLabel =+ diff < 0 ? `Expired ${compactDuration(-diff)} ago` : `Expires in ${compactDuration(diff)}`;+ expiryTooltip = format(expires, "MMM d, yyyy 'at' h:mm a");+ }++ const usageLabel =+ left != null && max != null+ ? `${left} of ${max} signing${max === 1 ? "" : "s"} left`+ : "Unlimited signings";++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="cursor-help">+ <div className="flex items-center gap-1.5">+ <ClockIcon className="h-3 w-3 shrink-0" />+ <span>{expiryLabel}</span>+ </div>+ <div className="mt-0.5 text-xs text-muted">{usageLabel}</div>+ </div>+ </TooltipTrigger>+ <TooltipContent>{expiryTooltip}</TooltipContent>+ </Tooltip>+ );+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/KindIcon.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/KindIcon.tsxnew file mode 100644index 0000000000..6315cb9779--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/KindIcon.tsx@@ -0,0 +1,7 @@+import { HardDriveIcon, UserIcon, UsersIcon } from "lucide-react";++export const KindIcon = ({ kind }: { kind: "user" | "identity" | "group" }) => {+ // eslint-disable-next-line no-nested-ternary+ const Icon = kind === "user" ? UserIcon : kind === "identity" ? HardDriveIcon : UsersIcon;+ return <Icon className="h-3.5 w-3.5 text-mineshaft-300" />;+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/RevokeRequestDialog.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/RevokeRequestDialog.tsxnew file mode 100644index 0000000000..e06ac18263--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/RevokeRequestDialog.tsx@@ -0,0 +1,70 @@+import { createNotification } from "@app/components/notifications";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle+} from "@app/components/v3";+import {+ SignerRequestStatus,+ TSignerRequest,+ useRevokeSignerRequest+} from "@app/hooks/api/signers";++type Props = {+ signerId: string;+ target: TSignerRequest | null;+ onOpenChange: (open: boolean) => void;+};++export const RevokeRequestDialog = ({ signerId, target, onOpenChange }: Props) => {+ const revoke = useRevokeSignerRequest();+ const isPending = target?.status === SignerRequestStatus.Pending;++ return (+ <AlertDialog+ open={target !== null}+ onOpenChange={(open) => {+ if (!open) onOpenChange(false);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {isPending ? "Cancel pending request?" : "Cancel active approval?"}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {isPending+ ? "The request will be cancelled and the member won't be able to sign under it. They can request again at any time."+ : "The active approval will be revoked immediately. Any remaining signings under it will be blocked. A new approval will be required to sign again."}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel isDisabled={revoke.isPending}>Keep it</AlertDialogCancel>+ <AlertDialogAction+ variant="danger"+ isDisabled={revoke.isPending}+ onClick={async () => {+ if (!target) return;+ try {+ await revoke.mutateAsync({ signerId, requestId: target.id });+ onOpenChange(false);+ } catch (err) {+ createNotification({+ type: "error",+ text: err instanceof Error ? err.message : "Failed to revoke request"+ });+ }+ }}+ >+ {isPending ? "Cancel request" : "Revoke approval"}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/SignerRequestsTab.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/SignerRequestsTab.tsxnew file mode 100644index 0000000000..0e5a69b9af--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/SignerRequestsTab.tsx@@ -0,0 +1,348 @@+import { useEffect, useMemo, useState } from "react";+import { format } from "date-fns";+import { FilterIcon, XIcon } from "lucide-react";+import { twMerge } from "tailwind-merge";++import {+ Badge,+ Button,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuLabel,+ DropdownMenuTrigger,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ IconButton,+ PageLoader,+ Pagination,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger+} from "@app/components/v3";+import {+ SIGNER_TABLE_PAGE_SIZE,+ SignerRequestStatus,+ TSignerRequest,+ useGetSignerPolicy,+ useListEffectiveSignerMembers,+ useListSignerMembers,+ useListSignerRequests+} from "@app/hooks/api/signers";++import { PreApproveSigningModal } from "../PreApproveSigningModal";+import { RequestToSignModal } from "../RequestToSignModal";+import { ExpiresCell } from "./ExpiresCell";+import { KindIcon } from "./KindIcon";+import { RevokeRequestDialog } from "./RevokeRequestDialog";+import {+ FILTER_OPTIONS,+ FilterStatus,+ labelForIdentity,+ labelForUser,+ MemberDescriptor,+ statusLabel,+ statusVariant+} from "./types";++type Props = {+ signerId: string;+ canPreApprove: boolean;+ canRequestSign: boolean;+};++export const SignerRequestsTab = ({ signerId, canPreApprove, canRequestSign }: Props) => {+ const [statusFilters, setStatusFilters] = useState<Set<FilterStatus>>(new Set());+ const [isRequestOpen, setIsRequestOpen] = useState(false);+ const [isPreApproveOpen, setIsPreApproveOpen] = useState(false);+ const [page, setPage] = useState(1);+ const [perPage, setPerPage] = useState(SIGNER_TABLE_PAGE_SIZE);+ const [revokeTarget, setRevokeTarget] = useState<TSignerRequest | null>(null);++ const toggleStatusFilter = (status: FilterStatus) => {+ setStatusFilters((prev) => {+ const next = new Set(prev);+ if (next.has(status)) next.delete(status);+ else next.add(status);+ return next;+ });+ };+ const isTableFiltered = statusFilters.size > 0;++ const statusesParam = useMemo(+ () => (statusFilters.size ? Array.from(statusFilters) : undefined),+ [statusFilters]+ );+ const { data, isLoading } = useListSignerRequests({+ signerId,+ statuses: statusesParam,+ offset: (page - 1) * perPage,+ limit: perPage+ });+ const requests = data?.requests ?? [];+ const totalCount = data?.totalCount ?? 0;+ const users = useListSignerMembers({ signerId, kind: "user" });+ const identities = useListSignerMembers({ signerId, kind: "identity" });+ const effectiveUsers = useListEffectiveSignerMembers({ signerId, kind: "user" });+ const effectiveIdentities = useListEffectiveSignerMembers({ signerId, kind: "identity" });+ const { data: policy } = useGetSignerPolicy(signerId);+ const hasPolicy = policy?.hasSteps ?? false;++ const userIndex = useMemo(() => {+ const map = new Map<string, MemberDescriptor>();+ (effectiveUsers.data?.members ?? []).forEach((m) => {+ if (!m.actorUserId) return;+ const label = m.details?.name || m.details?.username || m.details?.email || m.actorUserId;+ map.set(m.actorUserId, { label, kind: "user" });+ });+ (users.data?.memberships ?? []).forEach((m) => {+ if (m.actorUserId && !map.has(m.actorUserId)) map.set(m.actorUserId, labelForUser(m));+ });+ return map;+ }, [users.data, effectiveUsers.data]);++ const identityIndex = useMemo(() => {+ const map = new Map<string, MemberDescriptor>();+ (effectiveIdentities.data?.members ?? []).forEach((m) => {+ if (!m.actorIdentityId) return;+ map.set(m.actorIdentityId, {+ label: m.details?.name || m.actorIdentityId,+ kind: "identity"+ });+ });+ (identities.data?.memberships ?? []).forEach((m) => {+ if (m.actorIdentityId && !map.has(m.actorIdentityId))+ map.set(m.actorIdentityId, labelForIdentity(m));+ });+ return map;+ }, [identities.data, effectiveIdentities.data]);++ const resolveMember = (req: TSignerRequest): MemberDescriptor => {+ if (req.requesterId) {+ return (+ userIndex.get(req.requesterId) ?? {+ label: req.requesterName || req.requesterId,+ kind: "user"+ }+ );+ }+ if (req.machineIdentityId) {+ return (+ identityIndex.get(req.machineIdentityId) ?? {+ label: req.requesterName || req.machineIdentityId,+ kind: "identity"+ }+ );+ }+ return { label: req.requesterName || "Unknown", kind: "user" };+ };++ useEffect(() => {+ setPage(1);+ }, [statusFilters, perPage]);++ if (isLoading && !data) return <PageLoader />;++ return (+ <TooltipProvider>+ <Card>+ <CardHeader>+ <CardTitle>Requests</CardTitle>+ <CardDescription>+ See who can sign right now, and any past requests ever made.+ </CardDescription>+ <CardAction>+ <div className="flex items-center gap-2">+ {hasPolicy &&+ (canPreApprove ? (+ <Button variant="outline" onClick={() => setIsPreApproveOpen(true)}>+ Pre-approve signing+ </Button>+ ) : (+ canRequestSign && (+ <Button variant="outline" onClick={() => setIsRequestOpen(true)}>+ Request to sign+ </Button>+ )+ ))}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="Filter requests"+ variant={isTableFiltered ? "project" : "outline"}+ className={twMerge(isTableFiltered && "text-primary")}+ >+ <FilterIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={2}>+ <DropdownMenuLabel>Status</DropdownMenuLabel>+ {FILTER_OPTIONS.map((opt) => (+ <DropdownMenuCheckboxItem+ key={opt.value}+ checked={statusFilters.has(opt.value)}+ onSelect={(e) => {+ e.preventDefault();+ toggleStatusFilter(opt.value);+ }}+ >+ {opt.label}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </CardAction>+ </CardHeader>+ <CardContent>+ {totalCount === 0 ? (+ <Empty className="border border-solid">+ <EmptyHeader>+ <EmptyTitle>{hasPolicy ? "No requests" : "No approval policy"}</EmptyTitle>+ <EmptyDescription>+ {/* eslint-disable-next-line no-nested-ternary */}+ {!hasPolicy+ ? "No approval policy is in place — any member can sign directly without requesting approval."+ : canRequestSign+ ? "Open a request to sign to get started."+ : "Once requests are opened, they will appear here."}+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Member</TableHead>+ <TableHead className="w-28">Status</TableHead>+ <TableHead className="w-32">When</TableHead>+ <TableHead className="w-44">Expires</TableHead>+ <TableHead className="w-5" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {requests.map((req: TSignerRequest) => {+ const member = resolveMember(req);+ const isRevocable =+ req.status === SignerRequestStatus.Pending ||+ req.status === SignerRequestStatus.Approved;+ const created = new Date(req.createdAt);+ return (+ <TableRow key={req.id} className="group [&>td]:py-3">+ <TableCell isTruncatable>+ <div className="flex items-start gap-2">+ <div className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border bg-mineshaft-800">+ <KindIcon kind={member.kind} />+ </div>+ <div className="min-w-0 flex-1">+ <div className="truncate text-foreground">{member.label}</div>+ {req.justification && (+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="mt-0.5 truncate text-xs text-muted">+ {req.justification}+ </div>+ </TooltipTrigger>+ <TooltipContent className="max-w-md break-words whitespace-pre-wrap">+ {req.justification}+ </TooltipContent>+ </Tooltip>+ )}+ </div>+ </div>+ </TableCell>+ <TableCell>+ <Badge variant={statusVariant(req.status)}>{statusLabel(req.status)}</Badge>+ </TableCell>+ <TableCell className="text-accent">+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="cursor-help">{format(created, "MMM d, yyyy")}</span>+ </TooltipTrigger>+ <TooltipContent>+ {format(created, "MMM d, yyyy 'at' h:mm:ss a")}+ </TooltipContent>+ </Tooltip>+ </TableCell>+ <TableCell className="text-accent">+ <ExpiresCell req={req} />+ </TableCell>+ <TableCell>+ {isRevocable && canPreApprove && (+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ variant="ghost"+ size="xs"+ onClick={() => setRevokeTarget(req)}+ aria-label={+ req.status === SignerRequestStatus.Pending+ ? "Cancel the pending request"+ : "Cancel the active approval"+ }+ className="opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100"+ >+ <XIcon />+ </IconButton>+ </TooltipTrigger>+ <TooltipContent>+ {req.status === SignerRequestStatus.Pending+ ? "Cancel the pending request"+ : "Cancel the active approval"}+ </TooltipContent>+ </Tooltip>+ )}+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ )}+ {totalCount > 0 && (+ <Pagination+ count={totalCount}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={setPerPage}+ />+ )}+ </CardContent>+ </Card>++ <RequestToSignModal+ isOpen={isRequestOpen}+ onOpenChange={setIsRequestOpen}+ signerId={signerId}+ />+ <PreApproveSigningModal+ isOpen={isPreApproveOpen}+ onOpenChange={setIsPreApproveOpen}+ signerId={signerId}+ />+ <RevokeRequestDialog+ signerId={signerId}+ target={revokeTarget}+ onOpenChange={(open) => {+ if (!open) setRevokeTarget(null);+ }}+ />+ </TooltipProvider>+ );+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/index.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/index.tsnew file mode 100644index 0000000000..e6189f828c--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/index.ts@@ -0,0 +1 @@+export { SignerRequestsTab } from "./SignerRequestsTab";diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/types.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/types.tsnew file mode 100644index 0000000000..92cdcb7ea9--- /dev/null+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerRequestsTab/types.ts@@ -0,0 +1,64 @@+import { SignerRequestStatus, TSignerMember } from "@app/hooks/api/signers";++export type FilterStatus = "pending" | "approved" | "expired" | "revoked";++export const FILTER_OPTIONS: { value: FilterStatus; label: string }[] = [+ { value: "pending", label: "Pending" },+ { value: "approved", label: "Active" },+ { value: "expired", label: "Expired" },+ { value: "revoked", label: "Revoked" }+];++export type MemberDescriptor = { label: string; kind: "user" | "identity" | "group" };++export const statusVariant = (status: SignerRequestStatus | string) => {+ switch (status) {+ case SignerRequestStatus.Pending:+ return "warning" as const;+ case SignerRequestStatus.Approved:+ return "success" as const;+ case SignerRequestStatus.Cancelled:+ case SignerRequestStatus.Rejected:+ return "danger" as const;+ case SignerRequestStatus.Expired:+ return "neutral" as const;+ default:+ return "neutral" as const;+ }+};++export const statusLabel = (status: SignerRequestStatus | string) => {+ switch (status) {+ case SignerRequestStatus.Pending:+ return "Pending";+ case SignerRequestStatus.Approved:+ return "Active";+ case SignerRequestStatus.Cancelled:+ return "Revoked";+ case SignerRequestStatus.Rejected:+ return "Rejected";+ case SignerRequestStatus.Expired:+ return "Expired";+ default:+ return status;+ }+};++export const labelForUser = (m: TSignerMember): MemberDescriptor => ({+ label: m.details?.name || m.details?.username || m.details?.email || (m.actorUserId as string),+ kind: "user"+});++export const labelForIdentity = (m: TSignerMember): MemberDescriptor => ({+ label: m.details?.name || (m.actorIdentityId as string),+ kind: "identity"+});++export const compactDuration = (ms: number): string => {+ const minutes = Math.max(1, Math.floor(ms / 60_000));+ if (minutes < 60) return `${minutes}m`;+ const hours = Math.floor(minutes / 60);+ if (hours < 48) return `${hours}h`;+ const days = Math.floor(hours / 24);+ return `${days}d`;+};diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SigningOperationsTable.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/SigningOperationsTable.tsxindex 45896dca6b..ce51f0d248 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/SigningOperationsTable.tsx+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SigningOperationsTable.tsx@@ -12,6 +12,7 @@ import {CardHeader,CardTitle,Empty,+ EmptyDescription,EmptyHeader,EmptyTitle,Pagination,@@ -27,6 +28,7 @@ import {} from "@app/components/v3";import { useOrganization } from "@app/context";import {+ SIGNER_TABLE_PAGE_SIZE,SigningActorType,SigningOperationStatus,signingOperationStatusLabels,@@ -39,8 +41,6 @@ type Props = {projectId: string;};-const PAGE_SIZE = 25;-const getStatusBadgeVariant = (status: SigningOperationStatus) => {switch (status) {case SigningOperationStatus.Success:@@ -81,7 +81,7 @@ const getActorDisplayName = (actorType: SigningActorType, actorName?: string | nexport const SigningOperationsTable = ({ signerId, projectId }: Props) => {const [page, setPage] = useState(1);- const [perPage, setPerPage] = useState(PAGE_SIZE);+ const [perPage, setPerPage] = useState(SIGNER_TABLE_PAGE_SIZE);const navigate = useNavigate();const { currentOrg } = useOrganization();@@ -140,7 +140,7 @@ export const SigningOperationsTable = ({ signerId, projectId }: Props) => {<Card><CardHeader><CardTitle>Signing History</CardTitle>- <CardDescription>Trail of signing operations</CardDescription>+ <CardDescription>Trail of signing operations on this signer.</CardDescription></CardHeader><CardContent><Table>@@ -168,7 +168,7 @@ export const SigningOperationsTable = ({ signerId, projectId }: Props) => {))}{!isLoading &&operations.map((op) => (- <TableRow key={op.id}>+ <TableRow key={op.id} className="[&>td]:py-3"><TableCell>{format(new Date(op.createdAt), "MMM d, yyyy HH:mm:ss")}</TableCell><TableCell><Badge variant={getStatusBadgeVariant(op.status)}>@@ -186,9 +186,9 @@ export const SigningOperationsTable = ({ signerId, projectId }: Props) => {<TooltipTrigger asChild><div className="flex items-center gap-1.5">{op.actorType === SigningActorType.User ? (- <UserIcon className="text-muted-foreground size-3.5" />+ <UserIcon className="size-3.5 text-muted" />) : (- <HardDriveIcon className="text-muted-foreground size-3.5" />+ <HardDriveIcon className="size-3.5 text-muted" />)}<buttontype="button"@@ -196,7 +196,7 @@ export const SigningOperationsTable = ({ signerId, projectId }: Props) => {className={isActorClickable(op)? "cursor-pointer font-medium text-accent underline"- : "text-muted-foreground"+ : "text-muted"}>{getActorDisplayName(op.actorType, op.actorName)}@@ -211,9 +211,12 @@ export const SigningOperationsTable = ({ signerId, projectId }: Props) => {</TableBody></Table>{!isLoading && operations.length === 0 && (- <Empty>+ <Empty className="border border-solid"><EmptyHeader><EmptyTitle>No signing operations yet</EmptyTitle>+ <EmptyDescription>+ Once members sign artifacts with this signer, the activity trail will appear here.+ </EmptyDescription></EmptyHeader></Empty>)}diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/index.ts b/frontend/src/pages/cert-manager/SignerDetailPage/components/index.tsindex 476edcda90..c6a38f6941 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/index.ts+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/index.ts@@ -1,2 +1,8 @@-export { SignerOverviewSection } from "./SignerOverviewSection";+export { EditSignerModal } from "./EditSignerModal";+export { EditSignerPolicyModal } from "./EditSignerPolicyModal";+export { PreApproveSigningModal } from "./PreApproveSigningModal";+export { RequestToSignModal } from "./RequestToSignModal";+export { SignerApprovalPolicyTab } from "./SignerApprovalPolicyTab";+export { SignerMembersTab } from "./SignerMembersTab";+export { SignerRequestsTab } from "./SignerRequestsTab";export { SigningOperationsTable } from "./SigningOperationsTable";diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/route.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/route.tsxindex 8525d4a951..1bc34de1dd 100644--- a/frontend/src/pages/cert-manager/SignerDetailPage/route.tsx+++ b/frontend/src/pages/cert-manager/SignerDetailPage/route.tsx@@ -1,11 +1,18 @@import { createFileRoute } from "@tanstack/react-router";+import { zodValidator } from "@tanstack/zod-adapter";+import { z } from "zod";import { SignerDetailPage } from "./SignerDetailPage";+const SignerDetailSearchSchema = z.object({+ selectedTab: z.enum(["activity", "approvals", "members"]).catch("activity").optional()+});+export const Route = createFileRoute("/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/code-signing/$signerId")({component: SignerDetailPage,+ validateSearch: zodValidator(SignerDetailSearchSchema),beforeLoad: ({ context }) => {return {breadcrumbs: [